-- SCHEMA: fp

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


---------------------------------------------
-- fp.APAdminPerformanceTest ------------------
---------------------------------------------
CREATE TABLE [fp].[APAdminPerformanceTest] (
    [TestID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [TestTypeID] tinyint NOT NULL,
    [TestName] nvarchar(100) NOT NULL,
    [Description] nvarchar(3000) NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [SourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [TestDetailJSON] nvarchar(max) NOT NULL,
    [IsActive] bit NOT NULL,
    [CreatedBy] nvarchar(1000) NOT NULL,
    [Target] int NOT NULL,
    [MaximumTheshold] int NOT NULL,
    [PickableDepartments] nvarchar(max) NOT NULL,
    PRIMARY KEY ([TestID])
);
GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Targe__5375AD4D] DEFAULT ((0)) FOR [Target]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Maxim__5469D186] DEFAULT ((0)) FOR [MaximumTheshold]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Picka__565219F8] DEFAULT ('') FOR [PickableDepartments]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestI__6B4249E6] DEFAULT (newid()) FOR [TestID]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__SortO__6C366E1F] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestT__6D2A9258] DEFAULT ((0)) FOR [TestTypeID]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestN__6E1EB691] DEFAULT ('') FOR [TestName]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Descr__6F12DACA] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Budge__70FB233C] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Sourc__71EF4775] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestD__72E36BAE] DEFAULT ('') FOR [TestDetailJSON]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__IsAct__73D78FE7] DEFAULT ((0)) FOR [IsActive]; GO
ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Creat__74CBB420] DEFAULT ('') FOR [CreatedBy]; GO

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

---------------------------------------------
-- fp.APAdminPerformanceTestResults ------------------
---------------------------------------------
CREATE TABLE [fp].[APAdminPerformanceTestResults] (
    [TestID] uniqueidentifier NOT NULL,
    [StartDate] datetime NOT NULL,
    [EndDate] datetime NOT NULL,
    [Status] tinyint NOT NULL,
    [ErrorDetails] nvarchar(max) NOT NULL
);
GO
ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [FK__APAdminPe__TestI__7B78B1AF] FOREIGN KEY ([TestID]) REFERENCES [fp].[APAdminPerformanceTest] ([TestID]); GO
ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__TestI__76B3FC92] DEFAULT (newid()) FOR [TestID]; GO
ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__Start__77A820CB] DEFAULT (getdate()) FOR [StartDate]; GO
ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__EndDa__789C4504] DEFAULT (getdate()) FOR [EndDate]; GO
ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__Statu__7990693D] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__Error__7A848D76] DEFAULT ('') FOR [ErrorDetails]; GO

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

---------------------------------------------
-- fp.APEDepartmentWorkflowStatus ------------------
---------------------------------------------
CREATE TABLE [fp].[APEDepartmentWorkflowStatus] (
    [DepartmentWorkflowStatusID] int NOT NULL,
    [WorkflowStepID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [Status] tinyint NOT NULL,
    [EnteredStepDateTimeUtc] datetime NOT NULL,
    PRIMARY KEY ([DepartmentWorkflowStatusID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UC_APEDepartmentWorkflowStatus_DepartmentID_WorkflowStepID] ON [fp].[APEDepartmentWorkflowStatus] ([DepartmentID], [WorkflowStepID]);
GO
ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [FK__APEDepart__Workf__0232CC71] FOREIGN KEY ([WorkflowStepID]) REFERENCES [fp].[APEWorkflow] ([WorkflowStepID]); GO
ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [DF__APEDepart__Workf__013EA838] DEFAULT ((0)) FOR [WorkflowStepID]; GO
ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [DF__APEDepart__Depar__0326F0AA] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [DF__APEDepart__Enter__384D811C] DEFAULT (getutcdate()) FOR [EnteredStepDateTimeUtc]; GO

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

---------------------------------------------
-- fp.APEEntityGroupConfigSetting ------------------
---------------------------------------------
CREATE TABLE [fp].[APEEntityGroupConfigSetting] (
    [EntityGroupConfigID] int NOT NULL,
    [IsSalaryWageRateHidden] bit NOT NULL,
    [AdminRoleID] int NOT NULL,
    PRIMARY KEY ([EntityGroupConfigID])
);
GO
ALTER TABLE [fp].[APEEntityGroupConfigSetting] ADD CONSTRAINT [DF__APEEntity__Admin__191631C9] DEFAULT ((0)) FOR [AdminRoleID]; GO

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

---------------------------------------------
-- fp.APESectionRoleAccess ------------------
---------------------------------------------
CREATE TABLE [fp].[APESectionRoleAccess] (
    [SectionRoleAccessID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [Section] nvarchar(100) NOT NULL,
    [RoleID] int NOT NULL,
    [AccessType] int NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([SectionRoleAccessID])
);
GO
ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__Entit__135D5873] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__Secti__14517CAC] DEFAULT ('') FOR [Section]; GO
ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__RoleI__1545A0E5] DEFAULT ((0)) FOR [RoleID]; GO
ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__Acces__1639C51E] DEFAULT ((0)) FOR [AccessType]; GO
ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF_APESectionRoleAccess_BudgetPhaseID] DEFAULT ((3)) FOR [BudgetPhaseID]; GO

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

---------------------------------------------
-- fp.APEViewConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[APEViewConfig] (
    [RowID] bigint NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [ViewName] varchar(35) NOT NULL,
    [PivotConfiguration] varchar(max) NOT NULL,
    [MeasuresConfiguration] varchar(max) NOT NULL,
    [HasFilters] bit NOT NULL,
    [ModifiedDate] datetime NOT NULL,
    [IsShareable] bit NULL,
    [PlanSectionID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [FK_APEViewConfig_PlanSection] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [FK_APEViewConfig_PlanSubsection] FOREIGN KEY ([SubsectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__UserG__0F14CAB1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__ViewN__10FD1323] DEFAULT ('') FOR [ViewName]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Pivot__11F1375C] DEFAULT ('') FOR [PivotConfiguration]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Measu__12E55B95] DEFAULT ('') FOR [MeasuresConfiguration]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__HasFi__13D97FCE] DEFAULT ((0)) FOR [HasFilters]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__PlanS__149AFBE2] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Modif__14CDA407] DEFAULT (getdate()) FOR [ModifiedDate]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Subse__16834454] DEFAULT ((0)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__IsSha__28770C06] DEFAULT ((1)) FOR [IsShareable]; GO

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

---------------------------------------------
-- fp.APEWorkflow ------------------
---------------------------------------------
CREATE TABLE [fp].[APEWorkflow] (
    [WorkflowStepID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [RoleID] int NOT NULL,
    [WorkflowStepOrder] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [IsEditable] bit NOT NULL,
    [IsNotificationEnabled] bit NOT NULL,
    PRIMARY KEY ([WorkflowStepID])
);
GO
ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__Entit__050F391C] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__IsEdi__172DE957] DEFAULT ((0)) FOR [IsEditable]; GO
ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__IsNot__53D8CD5C] DEFAULT ((0)) FOR [IsNotificationEnabled]; GO
ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkflo__Name__56544A33] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__RoleI__583C92A5] DEFAULT ((0)) FOR [RoleID]; GO
ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__Workf__5930B6DE] DEFAULT ((0)) FOR [WorkflowStepOrder]; GO

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

---------------------------------------------
-- fp.APEWorkflowReviewStatusLog ------------------
---------------------------------------------
CREATE TABLE [fp].[APEWorkflowReviewStatusLog] (
    [ReviewStatusLogID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [TargetWorkflowStepID] int NOT NULL,
    [TargetWorkflowStepName] varchar(100) NOT NULL,
    [Status] tinyint NOT NULL,
    [Comment] nvarchar(4000) NOT NULL,
    [SourceWorkflowStepID] int NOT NULL,
    [SourceWorkflowStepName] varchar(100) NOT NULL,
    [TimeStampUtc] datetime NOT NULL,
    PRIMARY KEY ([ReviewStatusLogID])
);
GO
ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Targe__07EBA5C7] DEFAULT ('') FOR [TargetWorkflowStepName]; GO
ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Comme__1BF29E74] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Sourc__1CE6C2AD] DEFAULT ((0)) FOR [SourceWorkflowStepID]; GO
ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Sourc__1DDAE6E6] DEFAULT ('') FOR [SourceWorkflowStepName]; GO
ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__TimeS__37595CE3] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO

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

---------------------------------------------
-- fp.APEWorkflowRole ------------------
---------------------------------------------
CREATE TABLE [fp].[APEWorkflowRole] (
    [WorkflowRoleID] int NOT NULL,
    [WorkflowStepID] int NOT NULL,
    [RoleID] int NOT NULL,
    PRIMARY KEY ([WorkflowRoleID])
);
GO
ALTER TABLE [fp].[APEWorkflowRole] ADD CONSTRAINT [FK__APEWorkfl__Workf__7D6E1754] FOREIGN KEY ([WorkflowStepID]) REFERENCES [fp].[APEWorkflow] ([WorkflowStepID]); GO
ALTER TABLE [fp].[APEWorkflowRole] ADD CONSTRAINT [DF__APEWorkfl__Workf__7C79F31B] DEFAULT ((0)) FOR [WorkflowStepID]; GO
ALTER TABLE [fp].[APEWorkflowRole] ADD CONSTRAINT [DF__APEWorkfl__RoleI__7E623B8D] DEFAULT ((0)) FOR [RoleID]; GO

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

---------------------------------------------
-- fp.AccountFlexConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[AccountFlexConfig] (
    [FlexConfigGUID] uniqueidentifier NOT NULL,
    [AccountID] int NOT NULL,
    [FlexMethodClassName] nvarchar(100) NOT NULL,
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [IsUsingTrailing12] bit NOT NULL,
    PRIMARY KEY ([FlexConfigGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[AccountFlexConfig] ([AccountID], [EntityGroupConfigGUID]);
GO
ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__IsUsi__2FAC82CC] DEFAULT ((0)) FOR [IsUsingTrailing12]; GO
ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__FlexC__3E0D1CED] DEFAULT (newid()) FOR [FlexConfigGUID]; GO
ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__Accou__3F014126] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__FlexM__3FF5655F] DEFAULT ('') FOR [FlexMethodClassName]; GO
ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [df_AccountFlexConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO

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

---------------------------------------------
-- fp.AccountFlexConfigAssignment ------------------
---------------------------------------------
CREATE TABLE [fp].[AccountFlexConfigAssignment] (
    [FlexConfigAssignmentGUID] uniqueidentifier NOT NULL,
    [FlexConfigGUID] uniqueidentifier NOT NULL,
    [JobCodeAssignment] nvarchar(400) NOT NULL,
    [PayCodeGroupAssignment] nvarchar(400) NOT NULL,
    PRIMARY KEY ([FlexConfigAssignmentGUID])
);
GO
ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [FK__AccountFl__FlexC__46A262EE] FOREIGN KEY ([FlexConfigGUID]) REFERENCES [fp].[AccountFlexConfig] ([FlexConfigGUID]); GO
ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__FlexC__42D1D20A] DEFAULT (newid()) FOR [FlexConfigAssignmentGUID]; GO
ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__FlexC__43C5F643] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexConfigGUID]; GO
ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__JobCo__44BA1A7C] DEFAULT ('') FOR [JobCodeAssignment]; GO
ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__PayCo__45AE3EB5] DEFAULT ('') FOR [PayCodeGroupAssignment]; GO

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

---------------------------------------------
-- fp.AccountOBForecastDetailMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[AccountOBForecastDetailMapping] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AccountID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [CLU_AcctOBForecastDetail_ndx] ON [fp].[AccountOBForecastDetailMapping] ([BudgetConfigID], [AccountID], [OBForecastDetailID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[AccountOBForecastDetailMapping] ([BudgetConfigID], [AccountID], [OBForecastDetailID]);
GO
ALTER TABLE [fp].[AccountOBForecastDetailMapping] ADD CONSTRAINT [DF__AccountOB__Budge__6E8D8EEF] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[AccountOBForecastDetailMapping] ADD CONSTRAINT [DF__AccountOB__Accou__6F81B328] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[AccountOBForecastDetailMapping] ADD CONSTRAINT [DF__AccountOB__OBFor__7075D761] DEFAULT ((0)) FOR [OBForecastDetailID]; GO

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

---------------------------------------------
-- fp.AddProviderEncountersDataForCharges ------------------
---------------------------------------------
CREATE TABLE [fp].[AddProviderEncountersDataForCharges] (
    [AddProviderEncountersDataForChargesID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [UnitTypeID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [IsProcessed] bit NOT NULL,
    PRIMARY KEY ([AddProviderEncountersDataForChargesID])
);
GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [FK__AddProvid__Adjus__6B6F9474] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[DepartmentChargeVolumeAdjustment] ([AdjustmentGUID]); GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Adjus__6A7B703B] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Budge__6C63B8AD] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Entit__6D57DCE6] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Depar__6E4C011F] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__6F402558] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Patie__70344991] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Charg__71286DCA] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__AgeCo__721C9203] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Medic__7310B63C] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__UnitT__7404DA75] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__74F8FEAE] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__MSDRG__75ED22E7] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__UBRev__76E14720] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Prima__77D56B59] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__78C98F92] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__79BDB3CB] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Perfo__7AB1D804] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Perfo__7BA5FC3D] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Billi__7E8268E8] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__IsPro__7F768D21] DEFAULT ((0)) FOR [IsProcessed]; GO

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

---------------------------------------------
-- fp.AddProviderSummary ------------------
---------------------------------------------
CREATE TABLE [fp].[AddProviderSummary] (
    [SummaryID] int NOT NULL,
    [SLEncounterAdjustmentGUID] uniqueidentifier NULL,
    [DCVolumeAdjustmentGUID] uniqueidentifier NULL,
    [EmployeeType] int NOT NULL,
    [EmployeeID] int NULL,
    [ProviderID] int NULL,
    [ProviderType] int NOT NULL,
    [Specialty] int NOT NULL,
    [StartDateUTC] datetime NOT NULL,
    [BenchmarkAverage] decimal NOT NULL,
    [ProjectionTotal] decimal NOT NULL,
    [BudgetTotal] decimal NOT NULL,
    [BenchmarkProvidersJSON] nvarchar(max) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    PRIMARY KEY ([SummaryID])
);

CREATE NONCLUSTERED INDEX [IX_AddProviderSummary_LinkedAdjustments] ON [fp].[AddProviderSummary] ([SLEncounterAdjustmentGUID], [DCVolumeAdjustmentGUID]);
GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [FK__AddProvid__Emplo__0ADBBC27] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [FK__AddProvid__Provi__0BCFE060] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [FK__AddProvid__SLEnc__07FF4F7C] FOREIGN KEY ([SLEncounterAdjustmentGUID]) REFERENCES [fp].[ServiceLineEncounterAdjustment] ([AdjustmentGUID]); GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Emplo__09E797EE] DEFAULT ((0)) FOR [EmployeeType]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Provi__0CC40499] DEFAULT ((0)) FOR [ProviderType]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Speci__0DB828D2] DEFAULT ((0)) FOR [Specialty]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Start__0EAC4D0B] DEFAULT (getdate()) FOR [StartDateUTC]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Bench__0FA07144] DEFAULT ((0)) FOR [BenchmarkAverage]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Proje__1094957D] DEFAULT ((0)) FOR [ProjectionTotal]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Budge__1188B9B6] DEFAULT ((0)) FOR [BudgetTotal]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Bench__127CDDEF] DEFAULT ('') FOR [BenchmarkProvidersJSON]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Comme__13710228] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Class__14652661] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Class__15594A9A] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO

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

---------------------------------------------
-- fp.AdjustmentChunkingConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentChunkingConfiguration] (
    [SectionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [IsChunkingEnabled] bit NOT NULL,
    [MaxAdjustmentsPerChunk] int NOT NULL,
    [MaxImportAdjustmentsPerChunk] int NOT NULL,
    [MaxAdjustmentRecordCountForChunking] int NOT NULL,
    PRIMARY KEY ([SectionID])
);
GO
ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__Secti__154F28F9] DEFAULT ((0)) FOR [SectionID]; GO
ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__Descr__16434D32] DEFAULT ((0)) FOR [Description]; GO
ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__IsChu__1737716B] DEFAULT ((0)) FOR [IsChunkingEnabled]; GO
ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__MaxAd__182B95A4] DEFAULT ((0)) FOR [MaxAdjustmentsPerChunk]; GO
ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__MaxIm__191FB9DD] DEFAULT ((0)) FOR [MaxImportAdjustmentsPerChunk]; GO
ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__MaxAd__1A13DE16] DEFAULT ((0)) FOR [MaxAdjustmentRecordCountForChunking]; GO

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

---------------------------------------------
-- fp.AdjustmentClassificationCategory ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentClassificationCategory] (
    [CategoryID] int NOT NULL,
    [GroupID] int NOT NULL,
    [Name] nvarchar(30) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CategoryID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_FP_AdjustmentClassificationCategory_GroupID_Name] ON [fp].[AdjustmentClassificationCategory] ([GroupID], [Name]);
GO
ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [FK_AdjustmentClassificationCategory_GroupID] FOREIGN KEY ([GroupID]) REFERENCES [fp].[AdjustmentClassificationGroup] ([GroupID]); GO
ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [DF__Adjustmen__Group__48583505] DEFAULT ((0)) FOR [GroupID]; GO
ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [DF__Adjustment__Name__494C593E] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [DF__Adjustmen__Membe__49E2ECC9] DEFAULT (newid()) FOR [MemberGUID]; GO

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

---------------------------------------------
-- fp.AdjustmentClassificationGroup ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentClassificationGroup] (
    [GroupID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [Name] nvarchar(30) NOT NULL,
    [IsEncounterVisible] bit NOT NULL,
    [IsChargesVisible] bit NOT NULL,
    [IsStatisticsVisible] bit NOT NULL,
    [IsStaffingVisible] bit NOT NULL,
    [IsBenefitsVisible] bit NOT NULL,
    [IsGeneralLedgerVisible] bit NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [IsProviderCompensationVisible] bit NOT NULL,
    PRIMARY KEY ([GroupID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_FP_AdjustmentClassificationGroup_BudgetConfigID_Name] ON [fp].[AdjustmentClassificationGroup] ([BudgetConfigID], [Name]);
GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__isPro__67B41229] DEFAULT ((0)) FOR [IsProviderCompensationVisible]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__Budge__3DDAA692] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustment__Name__3ECECACB] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsEnc__3FC2EF04] DEFAULT ((0)) FOR [IsEncounterVisible]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsCha__40B7133D] DEFAULT ((0)) FOR [IsChargesVisible]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsSta__41AB3776] DEFAULT ((0)) FOR [IsStatisticsVisible]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsSta__429F5BAF] DEFAULT ((0)) FOR [IsStaffingVisible]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__Membe__4335EF3A] DEFAULT (newid()) FOR [MemberGUID]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsBen__43937FE8] DEFAULT ((0)) FOR [IsBenefitsVisible]; GO
ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsGen__4487A421] DEFAULT ((0)) FOR [IsGeneralLedgerVisible]; GO

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

---------------------------------------------
-- fp.AdjustmentGrouping ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentGrouping] (
    [GroupingGUID] uniqueidentifier NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [ExcelFile] varbinary(max) NULL,
    [IsRecordDeleted] bit NOT NULL,
    PRIMARY KEY ([GroupingGUID])
);
GO
ALTER TABLE [fp].[AdjustmentGrouping] ADD CONSTRAINT [DF__Adjustmen__IsRec__0967A9AA] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[AdjustmentGrouping] ADD CONSTRAINT [DF__Adjustmen__Group__722CAAC8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[AdjustmentGrouping] ADD CONSTRAINT [DF__Adjustmen__Descr__7320CF01] DEFAULT ('') FOR [Description]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReportBatchConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReportBatchConfiguration] (
    [BatchID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [TotalRowCount] int NOT NULL,
    PRIMARY KEY ([BatchID], [EntityID], [PatientClassID], [MedicalSurgicalID])
);
GO
ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__37078484] DEFAULT ((0)) FOR [BatchID]; GO
ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Entit__37FBA8BD] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Patie__38EFCCF6] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Medic__39E3F12F] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Total__3AD81568] DEFAULT ((0)) FOR [TotalRowCount]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReportPendingAdjustments ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReportPendingAdjustments] (
    [AdjustmentGUID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentImpactReportPendingAdjustments] ADD CONSTRAINT [DF__Adjustmen__Adjus__052F6677] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReport_Batches ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReport_Batches] (
    [SortOrder] int NOT NULL,
    [ReportExecutionGUID] uniqueidentifier NOT NULL,
    [BatchID] int NOT NULL,
    [IsInitial] bit NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Repor__5A5A170B] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Batch__5B4E3B44] DEFAULT ((0)) FOR [BatchID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__IsIni__5C425F7D] DEFAULT ((0)) FOR [IsInitial]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Entit__5D3683B6] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Patie__5E2AA7EF] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Servi__5F1ECC28] DEFAULT ((0)) FOR [ServiceLineID]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReport_CombineChargeEncounterAndPrice ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] (
    [ReportExecutionGUID] uniqueidentifier NOT NULL,
    [BatchID] int NOT NULL,
    [IsInitial] bit NOT NULL,
    [Charge_ChargeVolumeID] int NOT NULL,
    [Charge_BudgetConfigID] int NOT NULL,
    [Charge_EntityGroupConfigID] int NOT NULL,
    [Charge_EntityID] int NOT NULL,
    [Charge_DepartmentID] int NOT NULL,
    [Charge_ChargeCodeID] int NOT NULL,
    [Charge_PatientClassID] int NOT NULL,
    [Charge_ServiceProviderSpecialtyID] int NOT NULL,
    [Charge_PerformingProviderID] int NOT NULL,
    [Charge_PerformingProviderSpecialtyID] int NOT NULL,
    [Charge_UBRevCodeID] int NOT NULL,
    [Charge_ChargeImpact01] decimal NOT NULL,
    [Charge_ChargeImpact02] decimal NOT NULL,
    [Charge_ChargeImpact03] decimal NOT NULL,
    [Charge_ChargeImpact04] decimal NOT NULL,
    [Charge_ChargeImpact05] decimal NOT NULL,
    [Charge_ChargeImpact06] decimal NOT NULL,
    [Charge_ChargeImpact07] decimal NOT NULL,
    [Charge_ChargeImpact08] decimal NOT NULL,
    [Charge_ChargeImpact09] decimal NOT NULL,
    [Charge_ChargeImpact10] decimal NOT NULL,
    [Charge_ChargeImpact11] decimal NOT NULL,
    [Charge_ChargeImpact12] decimal NOT NULL,
    [Encounter_ServiceLineEncounterID] int NOT NULL,
    [Encounter_BudgetConfigID] int NOT NULL,
    [Encounter_EntityGroupConfigID] int NOT NULL,
    [Encounter_EntityID] int NOT NULL,
    [Encounter_PatientClassID] int NOT NULL,
    [Encounter_ServiceLineID] int NOT NULL,
    [Encounter_ServiceLineRollupID] int NOT NULL,
    [Encounter_AgeCohortID] int NOT NULL,
    [Encounter_MedicalSurgicalID] int NOT NULL,
    [Encounter_DepartmentID] int NOT NULL,
    [Encounter_PayorID] int NOT NULL,
    [Encounter_PayorGroupID] int NOT NULL,
    [Encounter_MSDRGID] int NOT NULL,
    [Encounter_CPTID] int NOT NULL,
    [Encounter_ProviderID] int NOT NULL,
    [Encounter_PhysicianSpecialtyID] int NOT NULL,
    [Encounter_ServiceEntityID] int NOT NULL,
    [Encounter_PrimaryCPTID] int NOT NULL,
    [Encounter_ServiceProviderID] int NOT NULL,
    [Encounter_IsInitialValue] bit NOT NULL,
    [Encounter_AdjustmentGUID] uniqueidentifier NOT NULL,
    [Encounter_TimeClassID] int NOT NULL,
    [Encounter_BudgetPhaseID] int NOT NULL,
    [Encounter_EncounterImpact01] decimal NOT NULL,
    [Encounter_EncounterImpact02] decimal NOT NULL,
    [Encounter_EncounterImpact03] decimal NOT NULL,
    [Encounter_EncounterImpact04] decimal NOT NULL,
    [Encounter_EncounterImpact05] decimal NOT NULL,
    [Encounter_EncounterImpact06] decimal NOT NULL,
    [Encounter_EncounterImpact07] decimal NOT NULL,
    [Encounter_EncounterImpact08] decimal NOT NULL,
    [Encounter_EncounterImpact09] decimal NOT NULL,
    [Encounter_EncounterImpact10] decimal NOT NULL,
    [Encounter_EncounterImpact11] decimal NOT NULL,
    [Encounter_EncounterImpact12] decimal NOT NULL,
    [Price_BaselineChargeRate] decimal NOT NULL,
    [DollarImpact_ChargeImpact01] decimal NOT NULL,
    [DollarImpact_ChargeImpact02] decimal NOT NULL,
    [DollarImpact_ChargeImpact03] decimal NOT NULL,
    [DollarImpact_ChargeImpact04] decimal NOT NULL,
    [DollarImpact_ChargeImpact05] decimal NOT NULL,
    [DollarImpact_ChargeImpact06] decimal NOT NULL,
    [DollarImpact_ChargeImpact07] decimal NOT NULL,
    [DollarImpact_ChargeImpact08] decimal NOT NULL,
    [DollarImpact_ChargeImpact09] decimal NOT NULL,
    [DollarImpact_ChargeImpact10] decimal NOT NULL,
    [DollarImpact_ChargeImpact11] decimal NOT NULL,
    [DollarImpact_ChargeImpact12] decimal NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__007FBFF3] DEFAULT ((0)) FOR [Encounter_AgeCohortID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0173E42C] DEFAULT ((0)) FOR [Encounter_MedicalSurgicalID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__02680865] DEFAULT ((0)) FOR [Encounter_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__035C2C9E] DEFAULT ((0)) FOR [Encounter_PayorID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__045050D7] DEFAULT ((0)) FOR [Encounter_PayorGroupID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__05447510] DEFAULT ((0)) FOR [Encounter_MSDRGID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__06389949] DEFAULT ((0)) FOR [Encounter_CPTID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__072CBD82] DEFAULT ((0)) FOR [Encounter_ProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0820E1BB] DEFAULT ((0)) FOR [Encounter_PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__091505F4] DEFAULT ((0)) FOR [Encounter_ServiceEntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0A092A2D] DEFAULT ((0)) FOR [Encounter_PrimaryCPTID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0AFD4E66] DEFAULT ((0)) FOR [Encounter_ServiceProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0BF1729F] DEFAULT ((0)) FOR [Encounter_IsInitialValue]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0CE596D8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Encounter_AdjustmentGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0DD9BB11] DEFAULT ((0)) FOR [Encounter_TimeClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0ECDDF4A] DEFAULT ((0)) FOR [Encounter_BudgetPhaseID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0FC20383] DEFAULT ((0)) FOR [Encounter_EncounterImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__10B627BC] DEFAULT ((0)) FOR [Encounter_EncounterImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__11AA4BF5] DEFAULT ((0)) FOR [Encounter_EncounterImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__129E702E] DEFAULT ((0)) FOR [Encounter_EncounterImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__13929467] DEFAULT ((0)) FOR [Encounter_EncounterImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__1486B8A0] DEFAULT ((0)) FOR [Encounter_EncounterImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__157ADCD9] DEFAULT ((0)) FOR [Encounter_EncounterImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__166F0112] DEFAULT ((0)) FOR [Encounter_EncounterImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__1763254B] DEFAULT ((0)) FOR [Encounter_EncounterImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__18574984] DEFAULT ((0)) FOR [Encounter_EncounterImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__194B6DBD] DEFAULT ((0)) FOR [Encounter_EncounterImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__1A3F91F6] DEFAULT ((0)) FOR [Encounter_EncounterImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Price__1B33B62F] DEFAULT ((0)) FOR [Price_BaselineChargeRate]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1C27DA68] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1D1BFEA1] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1E1022DA] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1F044713] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__20EC8F85] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__21E0B3BE] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__22D4D7F7] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__23C8FC30] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__24BD2069] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__25B144A2] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__26A568DB] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__27998D14] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Repor__6107149A] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Batch__61FB38D3] DEFAULT ((0)) FOR [BatchID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__IsIni__62EF5D0C] DEFAULT ((0)) FOR [IsInitial]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__63E38145] DEFAULT ((0)) FOR [Charge_ChargeVolumeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__64D7A57E] DEFAULT ((0)) FOR [Charge_BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__65CBC9B7] DEFAULT ((0)) FOR [Charge_EntityGroupConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__66BFEDF0] DEFAULT ((0)) FOR [Charge_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__67B41229] DEFAULT ((0)) FOR [Charge_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__68A83662] DEFAULT ((0)) FOR [Charge_ChargeCodeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__699C5A9B] DEFAULT ((0)) FOR [Charge_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6A907ED4] DEFAULT ((0)) FOR [Charge_ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6B84A30D] DEFAULT ((0)) FOR [Charge_PerformingProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6C78C746] DEFAULT ((0)) FOR [Charge_PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6D6CEB7F] DEFAULT ((0)) FOR [Charge_UBRevCodeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6E610FB8] DEFAULT ((0)) FOR [Charge_ChargeImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6F5533F1] DEFAULT ((0)) FOR [Charge_ChargeImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7049582A] DEFAULT ((0)) FOR [Charge_ChargeImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__713D7C63] DEFAULT ((0)) FOR [Charge_ChargeImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7231A09C] DEFAULT ((0)) FOR [Charge_ChargeImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7325C4D5] DEFAULT ((0)) FOR [Charge_ChargeImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7419E90E] DEFAULT ((0)) FOR [Charge_ChargeImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__750E0D47] DEFAULT ((0)) FOR [Charge_ChargeImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__76023180] DEFAULT ((0)) FOR [Charge_ChargeImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__76F655B9] DEFAULT ((0)) FOR [Charge_ChargeImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__77EA79F2] DEFAULT ((0)) FOR [Charge_ChargeImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__78DE9E2B] DEFAULT ((0)) FOR [Charge_ChargeImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__79D2C264] DEFAULT ((0)) FOR [Encounter_ServiceLineEncounterID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7AC6E69D] DEFAULT ((0)) FOR [Encounter_BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7BBB0AD6] DEFAULT ((0)) FOR [Encounter_EntityGroupConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7CAF2F0F] DEFAULT ((0)) FOR [Encounter_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7DA35348] DEFAULT ((0)) FOR [Encounter_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7E977781] DEFAULT ((0)) FOR [Encounter_ServiceLineID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7F8B9BBA] DEFAULT ((0)) FOR [Encounter_ServiceLineRollupID]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReport_CombinedChargeVolumeAndStatistics ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] (
    [ReportExecutionGUID] uniqueidentifier NOT NULL,
    [BatchID] int NOT NULL,
    [IsInitial] bit NOT NULL,
    [Charge_ChargeVolumeID] int NOT NULL,
    [Charge_BudgetConfigID] int NOT NULL,
    [Charge_EntityGroupConfigID] int NOT NULL,
    [Charge_EntityID] int NOT NULL,
    [Charge_DepartmentID] int NOT NULL,
    [Charge_ChargeCodeID] int NOT NULL,
    [Charge_PatientClassID] int NOT NULL,
    [Charge_ServiceProviderSpecialtyID] int NOT NULL,
    [Charge_PerformingProviderID] int NOT NULL,
    [Charge_PerformingProviderSpecialtyID] int NOT NULL,
    [Charge_UBRevCodeID] int NOT NULL,
    [Charge_ChargeImpact01] decimal NOT NULL,
    [Charge_ChargeImpact02] decimal NOT NULL,
    [Charge_ChargeImpact03] decimal NOT NULL,
    [Charge_ChargeImpact04] decimal NOT NULL,
    [Charge_ChargeImpact05] decimal NOT NULL,
    [Charge_ChargeImpact06] decimal NOT NULL,
    [Charge_ChargeImpact07] decimal NOT NULL,
    [Charge_ChargeImpact08] decimal NOT NULL,
    [Charge_ChargeImpact09] decimal NOT NULL,
    [Charge_ChargeImpact10] decimal NOT NULL,
    [Charge_ChargeImpact11] decimal NOT NULL,
    [Charge_ChargeImpact12] decimal NOT NULL,
    [Encounter_ServiceLineEncounterID] int NOT NULL,
    [Encounter_BudgetConfigID] int NOT NULL,
    [Encounter_EntityGroupConfigID] int NOT NULL,
    [Encounter_EntityID] int NOT NULL,
    [Encounter_PatientClassID] int NOT NULL,
    [Encounter_ServiceLineID] int NOT NULL,
    [Encounter_ServiceLineRollupID] int NOT NULL,
    [Encounter_AgeCohortID] int NOT NULL,
    [Encounter_MedicalSurgicalID] int NOT NULL,
    [Encounter_DepartmentID] int NOT NULL,
    [Encounter_PayorID] int NOT NULL,
    [Encounter_PayorGroupID] int NOT NULL,
    [Encounter_MSDRGID] int NOT NULL,
    [Encounter_CPTID] int NOT NULL,
    [Encounter_ProviderID] int NOT NULL,
    [Encounter_PhysicianSpecialtyID] int NOT NULL,
    [Encounter_ServiceEntityID] int NOT NULL,
    [Encounter_PrimaryCPTID] int NOT NULL,
    [Encounter_ServiceProviderID] int NOT NULL,
    [Encounter_IsInitialValue] bit NOT NULL,
    [Encounter_AdjustmentGUID] uniqueidentifier NOT NULL,
    [Encounter_TimeClassID] int NOT NULL,
    [Encounter_BudgetPhaseID] int NOT NULL,
    [Encounter_EncounterImpact01] decimal NOT NULL,
    [Encounter_EncounterImpact02] decimal NOT NULL,
    [Encounter_EncounterImpact03] decimal NOT NULL,
    [Encounter_EncounterImpact04] decimal NOT NULL,
    [Encounter_EncounterImpact05] decimal NOT NULL,
    [Encounter_EncounterImpact06] decimal NOT NULL,
    [Encounter_EncounterImpact07] decimal NOT NULL,
    [Encounter_EncounterImpact08] decimal NOT NULL,
    [Encounter_EncounterImpact09] decimal NOT NULL,
    [Encounter_EncounterImpact10] decimal NOT NULL,
    [Encounter_EncounterImpact11] decimal NOT NULL,
    [Encounter_EncounterImpact12] decimal NOT NULL,
    [Crosswalk_EntityGroupConfigID] int NOT NULL,
    [Crosswalk_DepartmentID] int NOT NULL,
    [Crosswalk_ChargeCodeID] int NOT NULL,
    [Crosswalk_PatientClassID] int NOT NULL,
    [Crosswalk_AccountID] int NOT NULL,
    [Crosswalk_RVUWeight] decimal NOT NULL,
    [Stats_StatisticsID] int NOT NULL,
    [Stats_BudgetConfigID] int NOT NULL,
    [Stats_EntityID] int NOT NULL,
    [Stats_DepartmentID] int NOT NULL,
    [Stats_AccountID] int NOT NULL,
    [Stats_FinancialReportingID] int NOT NULL,
    [Stats_PayorID] int NOT NULL,
    [Stats_PatientClassID] int NOT NULL,
    [StatisticsImpact01] decimal NOT NULL,
    [StatisticsImpact02] decimal NOT NULL,
    [StatisticsImpact03] decimal NOT NULL,
    [StatisticsImpact04] decimal NOT NULL,
    [StatisticsImpact05] decimal NOT NULL,
    [StatisticsImpact06] decimal NOT NULL,
    [StatisticsImpact07] decimal NOT NULL,
    [StatisticsImpact08] decimal NOT NULL,
    [StatisticsImpact09] decimal NOT NULL,
    [StatisticsImpact10] decimal NOT NULL,
    [StatisticsImpact11] decimal NOT NULL,
    [StatisticsImpact12] decimal NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__004AB5C9] DEFAULT ((0)) FOR [Charge_ChargeImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__013EDA02] DEFAULT ((0)) FOR [Charge_ChargeImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__0232FE3B] DEFAULT ((0)) FOR [Charge_ChargeImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__03272274] DEFAULT ((0)) FOR [Charge_ChargeImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__041B46AD] DEFAULT ((0)) FOR [Charge_ChargeImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__050F6AE6] DEFAULT ((0)) FOR [Charge_ChargeImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__06038F1F] DEFAULT ((0)) FOR [Charge_ChargeImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__06F7B358] DEFAULT ((0)) FOR [Charge_ChargeImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__07EBD791] DEFAULT ((0)) FOR [Charge_ChargeImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__08DFFBCA] DEFAULT ((0)) FOR [Charge_ChargeImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__09D42003] DEFAULT ((0)) FOR [Encounter_ServiceLineEncounterID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0AC8443C] DEFAULT ((0)) FOR [Encounter_BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0BBC6875] DEFAULT ((0)) FOR [Encounter_EntityGroupConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0CB08CAE] DEFAULT ((0)) FOR [Encounter_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0DA4B0E7] DEFAULT ((0)) FOR [Encounter_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0E98D520] DEFAULT ((0)) FOR [Encounter_ServiceLineID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0F8CF959] DEFAULT ((0)) FOR [Encounter_ServiceLineRollupID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__10811D92] DEFAULT ((0)) FOR [Encounter_AgeCohortID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__117541CB] DEFAULT ((0)) FOR [Encounter_MedicalSurgicalID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__12696604] DEFAULT ((0)) FOR [Encounter_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__135D8A3D] DEFAULT ((0)) FOR [Encounter_PayorID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1451AE76] DEFAULT ((0)) FOR [Encounter_PayorGroupID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1545D2AF] DEFAULT ((0)) FOR [Encounter_MSDRGID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1639F6E8] DEFAULT ((0)) FOR [Encounter_CPTID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__172E1B21] DEFAULT ((0)) FOR [Encounter_ProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__18223F5A] DEFAULT ((0)) FOR [Encounter_PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__19166393] DEFAULT ((0)) FOR [Encounter_ServiceEntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1A0A87CC] DEFAULT ((0)) FOR [Encounter_PrimaryCPTID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1AFEAC05] DEFAULT ((0)) FOR [Encounter_ServiceProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1BF2D03E] DEFAULT ((0)) FOR [Encounter_IsInitialValue]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1CE6F477] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Encounter_AdjustmentGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1DDB18B0] DEFAULT ((0)) FOR [Encounter_TimeClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1ECF3CE9] DEFAULT ((0)) FOR [Encounter_BudgetPhaseID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1FC36122] DEFAULT ((0)) FOR [Encounter_EncounterImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__20B7855B] DEFAULT ((0)) FOR [Encounter_EncounterImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__21ABA994] DEFAULT ((0)) FOR [Encounter_EncounterImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__229FCDCD] DEFAULT ((0)) FOR [Encounter_EncounterImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2393F206] DEFAULT ((0)) FOR [Encounter_EncounterImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2488163F] DEFAULT ((0)) FOR [Encounter_EncounterImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__257C3A78] DEFAULT ((0)) FOR [Encounter_EncounterImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__26705EB1] DEFAULT ((0)) FOR [Encounter_EncounterImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__276482EA] DEFAULT ((0)) FOR [Encounter_EncounterImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2858A723] DEFAULT ((0)) FOR [Encounter_EncounterImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__294CCB5C] DEFAULT ((0)) FOR [Encounter_EncounterImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2A40EF95] DEFAULT ((0)) FOR [Encounter_EncounterImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2B3513CE] DEFAULT ((0)) FOR [Crosswalk_EntityGroupConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2C293807] DEFAULT ((0)) FOR [Crosswalk_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2D1D5C40] DEFAULT ((0)) FOR [Crosswalk_ChargeCodeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2E118079] DEFAULT ((0)) FOR [Crosswalk_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2F05A4B2] DEFAULT ((0)) FOR [Crosswalk_AccountID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2FF9C8EB] DEFAULT ((0)) FOR [Crosswalk_RVUWeight]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__30EDED24] DEFAULT ((0)) FOR [Stats_StatisticsID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__31E2115D] DEFAULT ((0)) FOR [Stats_BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__32D63596] DEFAULT ((0)) FOR [Stats_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__33CA59CF] DEFAULT ((0)) FOR [Stats_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__34BE7E08] DEFAULT ((0)) FOR [Stats_AccountID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__35B2A241] DEFAULT ((0)) FOR [Stats_FinancialReportingID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__36A6C67A] DEFAULT ((0)) FOR [Stats_PayorID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__379AEAB3] DEFAULT ((0)) FOR [Stats_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__388F0EEC] DEFAULT ((0)) FOR [StatisticsImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__39833325] DEFAULT ((0)) FOR [StatisticsImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3A77575E] DEFAULT ((0)) FOR [StatisticsImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3B6B7B97] DEFAULT ((0)) FOR [StatisticsImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3C5F9FD0] DEFAULT ((0)) FOR [StatisticsImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3D53C409] DEFAULT ((0)) FOR [StatisticsImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3E47E842] DEFAULT ((0)) FOR [StatisticsImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3F3C0C7B] DEFAULT ((0)) FOR [StatisticsImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__403030B4] DEFAULT ((0)) FOR [StatisticsImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__412454ED] DEFAULT ((0)) FOR [StatisticsImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__42187926] DEFAULT ((0)) FOR [StatisticsImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__430C9D5F] DEFAULT ((0)) FOR [StatisticsImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Repor__71087239] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Batch__71FC9672] DEFAULT ((0)) FOR [BatchID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__IsIni__72F0BAAB] DEFAULT ((0)) FOR [IsInitial]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__73E4DEE4] DEFAULT ((0)) FOR [Charge_ChargeVolumeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__74D9031D] DEFAULT ((0)) FOR [Charge_BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__75CD2756] DEFAULT ((0)) FOR [Charge_EntityGroupConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__76C14B8F] DEFAULT ((0)) FOR [Charge_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__77B56FC8] DEFAULT ((0)) FOR [Charge_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__78A99401] DEFAULT ((0)) FOR [Charge_ChargeCodeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__799DB83A] DEFAULT ((0)) FOR [Charge_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7A91DC73] DEFAULT ((0)) FOR [Charge_ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7B8600AC] DEFAULT ((0)) FOR [Charge_PerformingProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7C7A24E5] DEFAULT ((0)) FOR [Charge_PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7D6E491E] DEFAULT ((0)) FOR [Charge_UBRevCodeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7E626D57] DEFAULT ((0)) FOR [Charge_ChargeImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7F569190] DEFAULT ((0)) FOR [Charge_ChargeImpact02]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReport_CombinedData_DebugConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] (
    [Batch_EntityID] int NOT NULL,
    [Batch_PatientClassID] int NOT NULL,
    [Batch_ServiceLineID] int NOT NULL,
    [DepartmentID] int NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__4BA1E360] DEFAULT ((0)) FOR [Batch_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__4C960799] DEFAULT ((0)) FOR [Batch_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__4D8A2BD2] DEFAULT ((0)) FOR [Batch_ServiceLineID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Depar__4E7E500B] DEFAULT ((0)) FOR [DepartmentID]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReport_CombinedEncounterAndCharge ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] (
    [ReportExecutionGUID] uniqueidentifier NOT NULL,
    [BatchID] int NOT NULL,
    [IsInitial] bit NOT NULL,
    [Charge_ChargeVolumeID] int NOT NULL,
    [Charge_BudgetConfigID] int NOT NULL,
    [Charge_EntityGroupConfigID] int NOT NULL,
    [Charge_EntityID] int NOT NULL,
    [Charge_DepartmentID] int NOT NULL,
    [Charge_ChargeCodeID] int NOT NULL,
    [Charge_PatientClassID] int NOT NULL,
    [Charge_ServiceProviderSpecialtyID] int NOT NULL,
    [Charge_PerformingProviderID] int NOT NULL,
    [Charge_PerformingProviderSpecialtyID] int NOT NULL,
    [Charge_UBRevCodeID] int NOT NULL,
    [Charge_ChargeImpact01] decimal NOT NULL,
    [Charge_ChargeImpact02] decimal NOT NULL,
    [Charge_ChargeImpact03] decimal NOT NULL,
    [Charge_ChargeImpact04] decimal NOT NULL,
    [Charge_ChargeImpact05] decimal NOT NULL,
    [Charge_ChargeImpact06] decimal NOT NULL,
    [Charge_ChargeImpact07] decimal NOT NULL,
    [Charge_ChargeImpact08] decimal NOT NULL,
    [Charge_ChargeImpact09] decimal NOT NULL,
    [Charge_ChargeImpact10] decimal NOT NULL,
    [Charge_ChargeImpact11] decimal NOT NULL,
    [Charge_ChargeImpact12] decimal NOT NULL,
    [Encounter_ServiceLineEncounterID] int NOT NULL,
    [Encounter_BudgetConfigID] int NOT NULL,
    [Encounter_EntityGroupConfigID] int NOT NULL,
    [Encounter_EntityID] int NOT NULL,
    [Encounter_PatientClassID] int NOT NULL,
    [Encounter_ServiceLineID] int NOT NULL,
    [Encounter_ServiceLineRollupID] int NOT NULL,
    [Encounter_AgeCohortID] int NOT NULL,
    [Encounter_MedicalSurgicalID] int NOT NULL,
    [Encounter_DepartmentID] int NOT NULL,
    [Encounter_PayorID] int NOT NULL,
    [Encounter_PayorGroupID] int NOT NULL,
    [Encounter_MSDRGID] int NOT NULL,
    [Encounter_CPTID] int NOT NULL,
    [Encounter_ProviderID] int NOT NULL,
    [Encounter_PhysicianSpecialtyID] int NOT NULL,
    [Encounter_ServiceEntityID] int NOT NULL,
    [Encounter_PrimaryCPTID] int NOT NULL,
    [Encounter_ServiceProviderID] int NOT NULL,
    [Encounter_IsInitialValue] bit NOT NULL,
    [Encounter_AdjustmentGUID] uniqueidentifier NOT NULL,
    [Encounter_TimeClassID] int NOT NULL,
    [Encounter_BudgetPhaseID] int NOT NULL,
    [Encounter_EncounterImpact01] decimal NOT NULL,
    [Encounter_EncounterImpact02] decimal NOT NULL,
    [Encounter_EncounterImpact03] decimal NOT NULL,
    [Encounter_EncounterImpact04] decimal NOT NULL,
    [Encounter_EncounterImpact05] decimal NOT NULL,
    [Encounter_EncounterImpact06] decimal NOT NULL,
    [Encounter_EncounterImpact07] decimal NOT NULL,
    [Encounter_EncounterImpact08] decimal NOT NULL,
    [Encounter_EncounterImpact09] decimal NOT NULL,
    [Encounter_EncounterImpact10] decimal NOT NULL,
    [Encounter_EncounterImpact11] decimal NOT NULL,
    [Encounter_EncounterImpact12] decimal NOT NULL,
    [UnitImpact_ChargeImpact01] decimal NOT NULL,
    [UnitImpact_ChargeImpact02] decimal NOT NULL,
    [UnitImpact_ChargeImpact03] decimal NOT NULL,
    [UnitImpact_ChargeImpact04] decimal NOT NULL,
    [UnitImpact_ChargeImpact05] decimal NOT NULL,
    [UnitImpact_ChargeImpact06] decimal NOT NULL,
    [UnitImpact_ChargeImpact07] decimal NOT NULL,
    [UnitImpact_ChargeImpact08] decimal NOT NULL,
    [UnitImpact_ChargeImpact09] decimal NOT NULL,
    [UnitImpact_ChargeImpact10] decimal NOT NULL,
    [UnitImpact_ChargeImpact11] decimal NOT NULL,
    [UnitImpact_ChargeImpact12] decimal NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Repor__2A75F9BF] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Batch__2B6A1DF8] DEFAULT ((0)) FOR [BatchID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__IsIni__2C5E4231] DEFAULT ((0)) FOR [IsInitial]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__2D52666A] DEFAULT ((0)) FOR [Charge_ChargeVolumeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__2E468AA3] DEFAULT ((0)) FOR [Charge_BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__2F3AAEDC] DEFAULT ((0)) FOR [Charge_EntityGroupConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__302ED315] DEFAULT ((0)) FOR [Charge_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3122F74E] DEFAULT ((0)) FOR [Charge_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__32171B87] DEFAULT ((0)) FOR [Charge_ChargeCodeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__330B3FC0] DEFAULT ((0)) FOR [Charge_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__33FF63F9] DEFAULT ((0)) FOR [Charge_ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__34F38832] DEFAULT ((0)) FOR [Charge_PerformingProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__35E7AC6B] DEFAULT ((0)) FOR [Charge_PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__36DBD0A4] DEFAULT ((0)) FOR [Charge_UBRevCodeID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__37CFF4DD] DEFAULT ((0)) FOR [Charge_ChargeImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__38C41916] DEFAULT ((0)) FOR [Charge_ChargeImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__39B83D4F] DEFAULT ((0)) FOR [Charge_ChargeImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3AAC6188] DEFAULT ((0)) FOR [Charge_ChargeImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3BA085C1] DEFAULT ((0)) FOR [Charge_ChargeImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3C94A9FA] DEFAULT ((0)) FOR [Charge_ChargeImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3D88CE33] DEFAULT ((0)) FOR [Charge_ChargeImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3E7CF26C] DEFAULT ((0)) FOR [Charge_ChargeImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3F7116A5] DEFAULT ((0)) FOR [Charge_ChargeImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__40653ADE] DEFAULT ((0)) FOR [Charge_ChargeImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__41595F17] DEFAULT ((0)) FOR [Charge_ChargeImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__424D8350] DEFAULT ((0)) FOR [Charge_ChargeImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4341A789] DEFAULT ((0)) FOR [Encounter_ServiceLineEncounterID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4435CBC2] DEFAULT ((0)) FOR [Encounter_BudgetConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4529EFFB] DEFAULT ((0)) FOR [Encounter_EntityGroupConfigID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__461E1434] DEFAULT ((0)) FOR [Encounter_EntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4712386D] DEFAULT ((0)) FOR [Encounter_PatientClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__48065CA6] DEFAULT ((0)) FOR [Encounter_ServiceLineID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__48FA80DF] DEFAULT ((0)) FOR [Encounter_ServiceLineRollupID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__49EEA518] DEFAULT ((0)) FOR [Encounter_AgeCohortID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4AE2C951] DEFAULT ((0)) FOR [Encounter_MedicalSurgicalID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4BD6ED8A] DEFAULT ((0)) FOR [Encounter_DepartmentID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4CCB11C3] DEFAULT ((0)) FOR [Encounter_PayorID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4DBF35FC] DEFAULT ((0)) FOR [Encounter_PayorGroupID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4EB35A35] DEFAULT ((0)) FOR [Encounter_MSDRGID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4FA77E6E] DEFAULT ((0)) FOR [Encounter_CPTID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__509BA2A7] DEFAULT ((0)) FOR [Encounter_ProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__518FC6E0] DEFAULT ((0)) FOR [Encounter_PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5283EB19] DEFAULT ((0)) FOR [Encounter_ServiceEntityID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__53780F52] DEFAULT ((0)) FOR [Encounter_PrimaryCPTID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__546C338B] DEFAULT ((0)) FOR [Encounter_ServiceProviderID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__556057C4] DEFAULT ((0)) FOR [Encounter_IsInitialValue]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__56547BFD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Encounter_AdjustmentGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5748A036] DEFAULT ((0)) FOR [Encounter_TimeClassID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__583CC46F] DEFAULT ((0)) FOR [Encounter_BudgetPhaseID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5930E8A8] DEFAULT ((0)) FOR [Encounter_EncounterImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5A250CE1] DEFAULT ((0)) FOR [Encounter_EncounterImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5B19311A] DEFAULT ((0)) FOR [Encounter_EncounterImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5C0D5553] DEFAULT ((0)) FOR [Encounter_EncounterImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5D01798C] DEFAULT ((0)) FOR [Encounter_EncounterImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5DF59DC5] DEFAULT ((0)) FOR [Encounter_EncounterImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5EE9C1FE] DEFAULT ((0)) FOR [Encounter_EncounterImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5FDDE637] DEFAULT ((0)) FOR [Encounter_EncounterImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__60D20A70] DEFAULT ((0)) FOR [Encounter_EncounterImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__61C62EA9] DEFAULT ((0)) FOR [Encounter_EncounterImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__62BA52E2] DEFAULT ((0)) FOR [Encounter_EncounterImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__63AE771B] DEFAULT ((0)) FOR [Encounter_EncounterImpact12]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__64A29B54] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact01]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6596BF8D] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact02]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__668AE3C6] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact03]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__677F07FF] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact04]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__68732C38] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact05]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__69675071] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact06]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6A5B74AA] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact07]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6B4F98E3] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact08]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6C43BD1C] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact09]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6D37E155] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact10]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6E2C058E] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact11]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6F2029C7] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact12]; GO

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

---------------------------------------------
-- fp.AdjustmentImpactReport_DebugInfo ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentImpactReport_DebugInfo] (
    [SortOrder] int NOT NULL,
    [ReportExecutionGUID] uniqueidentifier NOT NULL,
    [BatchID] int NOT NULL,
    [IsInitial] bit NOT NULL,
    [ReportName] nvarchar(100) NOT NULL,
    [DateCreated] datetime NOT NULL,
    [Message] nvarchar(max) NOT NULL,
    [CorrespondingSql] nvarchar(max) NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Repor__52B8F543] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Batch__53AD197C] DEFAULT ((0)) FOR [BatchID]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__IsIni__54A13DB5] DEFAULT ((0)) FOR [IsInitial]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Repor__559561EE] DEFAULT ('') FOR [ReportName]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__DateC__56898627] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Messa__577DAA60] DEFAULT ('') FOR [Message]; GO
ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Corre__5871CE99] DEFAULT ('') FOR [CorrespondingSql]; GO

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

---------------------------------------------
-- fp.AdjustmentLink ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentLink] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [LinkedAdjustmentGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[AdjustmentLink] ([AdjustmentGUID], [LinkedAdjustmentGUID]);
GO
ALTER TABLE [fp].[AdjustmentLink] ADD CONSTRAINT [DF__Adjustmen__Adjus__4FE5138B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[AdjustmentLink] ADD CONSTRAINT [DF__Adjustmen__Linke__50D937C4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LinkedAdjustmentGUID]; GO

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

---------------------------------------------
-- fp.AdjustmentRemovalHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[AdjustmentRemovalHistory] (
    [DateTimeCreated] datetime NOT NULL,
    [Author] nvarchar(100) NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [Sections] nvarchar(1000) NOT NULL
);
GO
ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__DateT__7C726549] DEFAULT (getdate()) FOR [DateTimeCreated]; GO
ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__Autho__7D668982] DEFAULT ('') FOR [Author]; GO
ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__Budge__7E5AADBB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__Secti__7F4ED1F4] DEFAULT ('') FOR [Sections]; GO

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

---------------------------------------------
-- fp.ArchiveBenefitsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveBenefitsChangeHistory] (
    [RowID] bigint NOT NULL,
    [BenefitsID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [SortOrder] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [FK_ArchiveBenefitsChangeHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Benef__09ECF585] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Adjus__0AE119BE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Adjus__0BD53DF7] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__SortO__0CC96230] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Fisca__0DBD8669] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__UnitT__0EB1AAA2] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__TimeC__0FA5CEDB] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Budge__1099F314] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__OldVa__118E174D] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__NewVa__12823B86] DEFAULT ((0)) FOR [NewValue]; GO

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

---------------------------------------------
-- fp.ArchiveChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveChangeHistory] (
    [RowID] int NOT NULL,
    [ChangeHistoryGUID] uniqueidentifier NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [AdjustedProperty] tinyint NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_ChangeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGUID]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_AdjustmentGUID] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_AdjustmentType] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_OldValue] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_NewValue] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_AdjustedProperty] DEFAULT ((0)) FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Group__1DF3EE32] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO

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

---------------------------------------------
-- fp.ArchiveChargeVolumeChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveChargeVolumeChangeHistory] (
    [RowID] bigint NOT NULL,
    [ChargeVolumeID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [SortOrder] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [FK_ArchiveChargeVolumeChangeHistory_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Charg__20D05ADD] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Adjus__21C47F16] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Adjus__22B8A34F] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__SortO__23ACC788] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Fisca__24A0EBC1] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__UnitT__25950FFA] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__TimeC__26893433] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Budge__277D586C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__OldVa__28717CA5] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__NewVa__2965A0DE] DEFAULT ((0)) FOR [NewValue]; GO

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

---------------------------------------------
-- fp.ArchiveFactBenefits ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactBenefits] (
    [BenefitsID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FlexMethodID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    PRIMARY KEY ([BenefitsID])
);

CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_Account] ON [fp].[ArchiveFactBenefits] ([AccountID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_BudgetConfig] ON [fp].[ArchiveFactBenefits] ([BudgetConfigID]) INCLUDE ([BenefitsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_Department] ON [fp].[ArchiveFactBenefits] ([DepartmentID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_Entity] ON [fp].[ArchiveFactBenefits] ([EntityID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_EntityGroupConfig] ON [fp].[ArchiveFactBenefits] ([EntityGroupConfigID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]);
GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__00ECCFD9] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__01E0F412] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__02D5184B] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__03C93C84] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__04BD60BD] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Budge__4F557445] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Entit__5049987E] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Entit__513DBCB7] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Depar__5231E0F0] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Accou__53260529] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Finan__541A2962] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__UnitT__550E4D9B] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__FlexM__560271D4] DEFAULT ((0)) FOR [FlexMethodID]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__AddDa__56F6960D] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__57EABA46] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__58DEDE7F] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__59D302B8] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5AC726F1] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5BBB4B2A] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5CAF6F63] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5DA3939C] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5E97B7D5] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5F8BDC0E] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__60800047] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__61742480] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__626848B9] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__635C6CF2] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6450912B] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6544B564] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6638D99D] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__672CFDD6] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6821220F] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__69154648] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6A096A81] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6AFD8EBA] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6BF1B2F3] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6CE5D72C] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6DD9FB65] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__6ECE1F9E] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__6FC243D7] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__70B66810] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__71AA8C49] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__729EB082] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7392D4BB] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7486F8F4] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__757B1D2D] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__766F4166] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7763659F] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__785789D8] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__794BAE11] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7A3FD24A] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7B33F683] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7C281ABC] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7D1C3EF5] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7E10632E] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7F048767] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7FF8ABA0] DEFAULT ((0)) FOR [InitialProjection07]; GO

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

---------------------------------------------
-- fp.ArchiveFactBenefitsBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactBenefitsBudget] (
    [RowID] int NOT NULL,
    [BenefitsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactBenefitsBudget] ON [fp].[ArchiveFactBenefitsBudget] ([BenefitsID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [FK_ArchiveFactBenefitsBudget_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Benef__0799CD68] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__088DF1A1] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__098215DA] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__0A763A13] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B6A5E4C] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0C5E8285] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0D52A6BE] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0E46CAF7] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0F3AEF30] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__102F1369] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__112337A2] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12175BDB] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__130B8014] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__13FFA44D] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__14F3C886] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__15E7ECBF] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__16DC10F8] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__17D03531] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__18C4596A] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__19B87DA3] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1AACA1DC] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1BA0C615] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1C94EA4E] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1D890E87] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1E7D32C0] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1F7156F9] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__20657B32] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__21599F6B] DEFAULT ((0)) FOR [FlexedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactBenefitsHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactBenefitsHistory] (
    [RowID] int NOT NULL,
    [BenefitsID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [FK_ArchiveFactBenefitsHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__00989575] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Benef__5E437D71] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5F37A1AA] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__602BC5E3] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__611FEA1C] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__62140E55] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__6308328E] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__63FC56C7] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__64F07B00] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__65E49F39] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__66D8C372] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__67CCE7AB] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__68C10BE4] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__69B5301D] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6AA95456] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6B9D788F] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6C919CC8] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6D85C101] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6E79E53A] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6F6E0973] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__70622DAC] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__715651E5] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__724A761E] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__733E9A57] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7432BE90] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7526E2C9] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__761B0702] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__770F2B3B] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__78034F74] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__78F773AD] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__79EB97E6] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7ADFBC1F] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7BD3E058] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7CC80491] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7DBC28CA] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7EB04D03] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7FA4713C] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO

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

---------------------------------------------
-- fp.ArchiveFactBenefitsProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactBenefitsProjection] (
    [RowID] int NOT NULL,
    [BenefitsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactBenefitsProjection] ON [fp].[ArchiveFactBenefitsProjection] ([BenefitsID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [FK_ArchiveFactBenefitsProjection_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Benef__252A304F] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__261E5488] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__271278C1] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__28069CFA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__28FAC133] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__29EEE56C] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2AE309A5] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2BD72DDE] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2CCB5217] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2DBF7650] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2EB39A89] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2FA7BEC2] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__309BE2FB] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__31900734] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__32842B6D] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__33784FA6] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__346C73DF] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__35609818] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3654BC51] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3748E08A] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__383D04C3] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__393128FC] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3A254D35] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3B19716E] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3C0D95A7] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3D01B9E0] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3DF5DE19] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3EEA0252] DEFAULT ((0)) FOR [FlexedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactChargeVolume ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactChargeVolume] (
    [ChargeVolumeID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [SampledProjectionTotal] decimal NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetTotal] decimal NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialProjectionTotal] decimal NULL,
    [VariableDirectUnitCost] decimal NOT NULL,
    [ChargeEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [BillingProviderID] int NOT NULL,
    [BillingProviderSpecialtyID] int NOT NULL,
    PRIMARY KEY ([ChargeVolumeID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactChargeVolume] ON [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_BudgetConfig] ON [fp].[ArchiveFactChargeVolume] ([BudgetConfigID]) INCLUDE ([ChargeVolumeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_Department] ON [fp].[ArchiveFactChargeVolume] ([DepartmentID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_Entity] ON [fp].[ArchiveFactChargeVolume] ([EntityID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_EntityGroupConfig] ON [fp].[ArchiveFactChargeVolume] ([EntityGroupConfigID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]);
GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Budge__02BF3E5B] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Entit__03B36294] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Entit__04A786CD] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Depar__059BAB06] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Servi__068FCF3F] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Patie__0783F378] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__AgeCo__087817B1] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Medic__096C3BEA] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Charg__0A606023] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__UnitT__0B54845C] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__AddDa__0C48A895] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0D3CCCCE] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0E30F107] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0F251540] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__10193979] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__110D5DB2] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__120181EB] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__12F5A624] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__13E9CA5D] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__14DDEE96] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__15D212CF] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__16C63708] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__17BA5B41] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__18AE7F7A] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__19A2A3B3] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1A96C7EC] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1B8AEC25] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1C7F105E] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1D733497] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1E6758D0] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1F5B7D09] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__204FA142] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2143C57B] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2237E9B4] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__232C0DED] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__24203226] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2514565F] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__26087A98] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__26FC9ED1] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__27F0C30A] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__28E4E743] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__29D90B7C] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2ACD2FB5] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2BC153EE] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2CB57827] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2DA99C60] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2E9DC099] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2F91E4D2] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__3086090B] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__317A2D44] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__326E517D] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__336275B6] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__345699EF] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__354ABE28] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__363EE261] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__3733069A] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__38272AD3] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__391B4F0C] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__3A0F7345] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Varia__3B03977E] DEFAULT ((0)) FOR [VariableDirectUnitCost]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Charg__4F05FDEB] DEFAULT ((0)) FOR [ChargeEntityID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__4FFA2224] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__UBRev__50EE465D] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__CPTID__51E26A96] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Servi__52D68ECF] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Servi__53CAB308] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Billi__54BED741] DEFAULT ((0)) FOR [BillingProviderID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Billi__55B2FB7A] DEFAULT ((0)) FOR [BillingProviderSpecialtyID]; GO

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

---------------------------------------------
-- fp.ArchiveFactChargeVolumeBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactChargeVolumeBudget] (
    [RowID] int NOT NULL,
    [ChargeVolumeID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactChargeVolumeBudget] ON [fp].[ArchiveFactChargeVolumeBudget] ([ChargeVolumeID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [FK_ArchiveFactChargeVolumeBudget_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Charg__3DE00429] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__3ED42862] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__3FC84C9B] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__40BC70D4] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__41B0950D] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__42A4B946] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4398DD7F] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__448D01B8] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__458125F1] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__46754A2A] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__47696E63] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__485D929C] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4951B6D5] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4A45DB0E] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4B39FF47] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4C2E2380] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4D2247B9] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4E166BF2] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4F0A902B] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4FFEB464] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__50F2D89D] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__51E6FCD6] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__52DB210F] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__53CF4548] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__54C36981] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__55B78DBA] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__56ABB1F3] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__579FD62C] DEFAULT ((0)) FOR [FlexedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactChargeVolumeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactChargeVolumeHistory] (
    [RowID] int NOT NULL,
    [ChargeVolumeID] int NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [CurrentYearBudgetValue01] decimal NOT NULL,
    [CurrentYearBudgetValue02] decimal NOT NULL,
    [CurrentYearBudgetValue03] decimal NOT NULL,
    [CurrentYearBudgetValue04] decimal NOT NULL,
    [CurrentYearBudgetValue05] decimal NOT NULL,
    [CurrentYearBudgetValue06] decimal NOT NULL,
    [CurrentYearBudgetValue07] decimal NOT NULL,
    [CurrentYearBudgetValue08] decimal NOT NULL,
    [CurrentYearBudgetValue09] decimal NOT NULL,
    [CurrentYearBudgetValue10] decimal NOT NULL,
    [CurrentYearBudgetValue11] decimal NOT NULL,
    [CurrentYearBudgetValue12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetValueTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [FK_ArchiveFactChargeVolumeHistory_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Charg__04692659] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__055D4A92] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__06516ECB] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__07459304] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0839B73D] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__092DDB76] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0A21FFAF] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0B1623E8] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0C0A4821] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0CFE6C5A] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0DF29093] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0EE6B4CC] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0FDAD905] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__10CEFD3E] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__11C32177] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__12B745B0] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__13AB69E9] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__149F8E22] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1593B25B] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1687D694] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__177BFACD] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__18701F06] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1964433F] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1A586778] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1B4C8BB1] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1C40AFEA] DEFAULT ((0)) FOR [CurrentYearBudgetValue01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1D34D423] DEFAULT ((0)) FOR [CurrentYearBudgetValue02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1E28F85C] DEFAULT ((0)) FOR [CurrentYearBudgetValue03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1F1D1C95] DEFAULT ((0)) FOR [CurrentYearBudgetValue04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__201140CE] DEFAULT ((0)) FOR [CurrentYearBudgetValue05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__21056507] DEFAULT ((0)) FOR [CurrentYearBudgetValue06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__21F98940] DEFAULT ((0)) FOR [CurrentYearBudgetValue07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__22EDAD79] DEFAULT ((0)) FOR [CurrentYearBudgetValue08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__23E1D1B2] DEFAULT ((0)) FOR [CurrentYearBudgetValue09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__24D5F5EB] DEFAULT ((0)) FOR [CurrentYearBudgetValue10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__25CA1A24] DEFAULT ((0)) FOR [CurrentYearBudgetValue11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__26BE3E5D] DEFAULT ((0)) FOR [CurrentYearBudgetValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactChargeVolumeProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactChargeVolumeProjection] (
    [RowID] int NOT NULL,
    [ChargeVolumeID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactChargeVolumeProjection] ON [fp].[ArchiveFactChargeVolumeProjection] ([ChargeVolumeID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [FK_ArchiveFactChargeVolumeProjection_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Charg__5B706710] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__5C648B49] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__5D58AF82] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__5E4CD3BB] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5F40F7F4] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60351C2D] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__61294066] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__621D649F] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__631188D8] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6405AD11] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__64F9D14A] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__65EDF583] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__66E219BC] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67D63DF5] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__68CA622E] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__69BE8667] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6AB2AAA0] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6BA6CED9] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6C9AF312] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6D8F174B] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6E833B84] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6F775FBD] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__706B83F6] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__715FA82F] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7253CC68] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7347F0A1] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__743C14DA] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__75303913] DEFAULT ((0)) FOR [FlexedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactGeneralLedger ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactGeneralLedger] (
    [GeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [SampledProjectionTotal] decimal NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetTotal] decimal NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialProjectionTotal] decimal NULL,
    PRIMARY KEY ([GeneralLedgerID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactGeneralLedger] ON [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_Account] ON [fp].[ArchiveFactGeneralLedger] ([AccountID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_BudgetConfig] ON [fp].[ArchiveFactGeneralLedger] ([BudgetConfigID]) INCLUDE ([GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_Department] ON [fp].[ArchiveFactGeneralLedger] ([DepartmentID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_Entity] ON [fp].[ArchiveFactGeneralLedger] ([EntityID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_EntityGroupConfig] ON [fp].[ArchiveFactGeneralLedger] ([EntityGroupConfigID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]);
GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Budge__22A1FE08] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Entit__23962241] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Entit__248A467A] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Depar__257E6AB3] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Accou__26728EEC] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Finan__2766B325] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Varia__285AD75E] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__UnitT__294EFB97] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__APEMo__2A431FD0] DEFAULT ((0)) FOR [APEModelSectionID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__AddDa__2B374409] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2C2B6842] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2D1F8C7B] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2E13B0B4] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2F07D4ED] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2FFBF926] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__30F01D5F] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__31E44198] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__32D865D1] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__33CC8A0A] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__34C0AE43] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__35B4D27C] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__36A8F6B5] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__379D1AEE] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__38913F27] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__39856360] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3A798799] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3B6DABD2] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3C61D00B] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3D55F444] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3E4A187D] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3F3E3CB6] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__403260EF] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__41268528] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__421AA961] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__430ECD9A] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4402F1D3] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__44F7160C] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__45EB3A45] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__46DF5E7E] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__47D382B7] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__48C7A6F0] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__49BBCB29] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4AAFEF62] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4BA4139B] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4C9837D4] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4D8C5C0D] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4E808046] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4F74A47F] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5068C8B8] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__515CECF1] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5251112A] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__53453563] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5439599C] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__552D7DD5] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5621A20E] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5715C647] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5809EA80] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__58FE0EB9] DEFAULT ((0)) FOR [InitialProjection12]; GO

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

---------------------------------------------
-- fp.ArchiveFactGeneralLedgerBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactGeneralLedgerBudget] (
    [RowID] int NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NULL,
    [PercentAdjustmentFactor01] decimal NOT NULL,
    [PercentAdjustmentFactor02] decimal NOT NULL,
    [PercentAdjustmentFactor03] decimal NOT NULL,
    [PercentAdjustmentFactor04] decimal NOT NULL,
    [PercentAdjustmentFactor05] decimal NOT NULL,
    [PercentAdjustmentFactor06] decimal NOT NULL,
    [PercentAdjustmentFactor07] decimal NOT NULL,
    [PercentAdjustmentFactor08] decimal NOT NULL,
    [PercentAdjustmentFactor09] decimal NOT NULL,
    [PercentAdjustmentFactor10] decimal NOT NULL,
    [PercentAdjustmentFactor11] decimal NOT NULL,
    [PercentAdjustmentFactor12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactGeneralLedgerBudget] ON [fp].[ArchiveFactGeneralLedgerBudget] ([GeneralLedgerID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [FK_ArchiveFactGeneralLedgerBudget_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Gener__55428C6E] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__5636B0A7] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__572AD4E0] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__581EF919] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__59131D52] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5A07418B] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5AFB65C4] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5BEF89FD] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5CE3AE36] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5DD7D26F] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5ECBF6A8] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5FC01AE1] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60B43F1A] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__61A86353] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__629C878C] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6390ABC5] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6484CFFE] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6578F437] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__666D1870] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__67613CA9] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__685560E2] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6949851B] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6A3DA954] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6B31CD8D] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6C25F1C6] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6D1A15FF] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6E0E3A38] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6F025E71] DEFAULT ((0)) FOR [FlexedValue12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__6FF682AA] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__70EAA6E3] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__71DECB1C] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__72D2EF55] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__73C7138E] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__74BB37C7] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__75AF5C00] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__76A38039] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7797A472] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__788BC8AB] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__797FECE4] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7A74111D] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO

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

---------------------------------------------
-- fp.ArchiveFactGeneralLedgerHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactGeneralLedgerHistory] (
    [RowID] int NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [FK_ArchiveFactGeneralLedgerHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Gener__381DD489] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3911F8C2] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3A061CFB] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3AFA4134] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3BEE656D] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3CE289A6] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3DD6ADDF] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3ECAD218] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3FBEF651] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__40B31A8A] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__41A73EC3] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__429B62FC] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__438F8735] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4483AB6E] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4577CFA7] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__466BF3E0] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__47601819] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__48543C52] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4948608B] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4A3C84C4] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4B30A8FD] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4C24CD36] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4D18F16F] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4E0D15A8] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4F0139E1] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4FF55E1A] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__50E98253] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__51DDA68C] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__52D1CAC5] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__53C5EEFE] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__54BA1337] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__55AE3770] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__56A25BA9] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__57967FE2] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__588AA41B] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__597EC854] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__5A72EC8D] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.ArchiveFactGeneralLedgerProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactGeneralLedgerProjection] (
    [RowID] int NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NULL,
    [PercentAdjustmentFactor01] decimal NOT NULL,
    [PercentAdjustmentFactor02] decimal NOT NULL,
    [PercentAdjustmentFactor03] decimal NOT NULL,
    [PercentAdjustmentFactor04] decimal NOT NULL,
    [PercentAdjustmentFactor05] decimal NOT NULL,
    [PercentAdjustmentFactor06] decimal NOT NULL,
    [PercentAdjustmentFactor07] decimal NOT NULL,
    [PercentAdjustmentFactor08] decimal NOT NULL,
    [PercentAdjustmentFactor09] decimal NOT NULL,
    [PercentAdjustmentFactor10] decimal NOT NULL,
    [PercentAdjustmentFactor11] decimal NOT NULL,
    [PercentAdjustmentFactor12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactGeneralLedgerProjection] ON [fp].[ArchiveFactGeneralLedgerProjection] ([GeneralLedgerID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [FK_ArchiveFactGeneralLedgerProjection_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__002CEA73] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__01210EAC] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__021532E5] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0309571E] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__03FD7B57] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__04F19F90] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05E5C3C9] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__06D9E802] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__07CE0C3B] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__08C23074] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__09B654AD] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0AAA78E6] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B9E9D1F] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0C92C158] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__0D86E591] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__0E7B09CA] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__0F6F2E03] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1063523C] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__11577675] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__124B9AAE] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__133FBEE7] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1433E320] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__15280759] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__161C2B92] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__17104FCB] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__18047404] DEFAULT ((0)) FOR [FlexedValue12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__18F8983D] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__19ECBC76] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1AE0E0AF] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1BD504E8] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1CC92921] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1DBD4D5A] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1EB17193] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1FA595CC] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2099BA05] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__218DDE3E] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__22820277] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__237626B0] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Gener__7E44A201] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__7F38C63A] DEFAULT ((0)) FOR [LockType]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementCharges ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementCharges] (
    [ReimbursementChargesID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [InitialBudgetChargeDollars01] decimal NOT NULL,
    [InitialBudgetChargeDollars02] decimal NOT NULL,
    [InitialBudgetChargeDollars03] decimal NOT NULL,
    [InitialBudgetChargeDollars04] decimal NOT NULL,
    [InitialBudgetChargeDollars05] decimal NOT NULL,
    [InitialBudgetChargeDollars06] decimal NOT NULL,
    [InitialBudgetChargeDollars07] decimal NOT NULL,
    [InitialBudgetChargeDollars08] decimal NOT NULL,
    [InitialBudgetChargeDollars09] decimal NOT NULL,
    [InitialBudgetChargeDollars10] decimal NOT NULL,
    [InitialBudgetChargeDollars11] decimal NOT NULL,
    [InitialBudgetChargeDollars12] decimal NOT NULL,
    [InitialBudgetChargeDollarsTotal] decimal NOT NULL,
    [InitialBudgetChargeUnits01] decimal NOT NULL,
    [InitialBudgetChargeUnits02] decimal NOT NULL,
    [InitialBudgetChargeUnits03] decimal NOT NULL,
    [InitialBudgetChargeUnits04] decimal NOT NULL,
    [InitialBudgetChargeUnits05] decimal NOT NULL,
    [InitialBudgetChargeUnits06] decimal NOT NULL,
    [InitialBudgetChargeUnits07] decimal NOT NULL,
    [InitialBudgetChargeUnits08] decimal NOT NULL,
    [InitialBudgetChargeUnits09] decimal NOT NULL,
    [InitialBudgetChargeUnits10] decimal NOT NULL,
    [InitialBudgetChargeUnits11] decimal NOT NULL,
    [InitialBudgetChargeUnits12] decimal NOT NULL,
    [InitialBudgetChargeUnitsTotal] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge01] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge02] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge03] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge04] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge05] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge06] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge07] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge08] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge09] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge10] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge11] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge12] decimal NOT NULL,
    [InitialBudgetNetPerDiem01] decimal NOT NULL,
    [InitialBudgetNetPerDiem02] decimal NOT NULL,
    [InitialBudgetNetPerDiem03] decimal NOT NULL,
    [InitialBudgetNetPerDiem04] decimal NOT NULL,
    [InitialBudgetNetPerDiem05] decimal NOT NULL,
    [InitialBudgetNetPerDiem06] decimal NOT NULL,
    [InitialBudgetNetPerDiem07] decimal NOT NULL,
    [InitialBudgetNetPerDiem08] decimal NOT NULL,
    [InitialBudgetNetPerDiem09] decimal NOT NULL,
    [InitialBudgetNetPerDiem10] decimal NOT NULL,
    [InitialBudgetNetPerDiem11] decimal NOT NULL,
    [InitialBudgetNetPerDiem12] decimal NOT NULL,
    [InitialProjectionChargeDollars01] decimal NOT NULL,
    [InitialProjectionChargeDollars02] decimal NOT NULL,
    [InitialProjectionChargeDollars03] decimal NOT NULL,
    [InitialProjectionChargeDollars04] decimal NOT NULL,
    [InitialProjectionChargeDollars05] decimal NOT NULL,
    [InitialProjectionChargeDollars06] decimal NOT NULL,
    [InitialProjectionChargeDollars07] decimal NOT NULL,
    [InitialProjectionChargeDollars08] decimal NOT NULL,
    [InitialProjectionChargeDollars09] decimal NOT NULL,
    [InitialProjectionChargeDollars10] decimal NOT NULL,
    [InitialProjectionChargeDollars11] decimal NOT NULL,
    [InitialProjectionChargeDollars12] decimal NOT NULL,
    [InitialProjectionChargeDollarsTotal] decimal NOT NULL,
    [InitialProjectionChargeUnits01] decimal NOT NULL,
    [InitialProjectionChargeUnits02] decimal NOT NULL,
    [InitialProjectionChargeUnits03] decimal NOT NULL,
    [InitialProjectionChargeUnits04] decimal NOT NULL,
    [InitialProjectionChargeUnits05] decimal NOT NULL,
    [InitialProjectionChargeUnits06] decimal NOT NULL,
    [InitialProjectionChargeUnits07] decimal NOT NULL,
    [InitialProjectionChargeUnits08] decimal NOT NULL,
    [InitialProjectionChargeUnits09] decimal NOT NULL,
    [InitialProjectionChargeUnits10] decimal NOT NULL,
    [InitialProjectionChargeUnits11] decimal NOT NULL,
    [InitialProjectionChargeUnits12] decimal NOT NULL,
    [InitialProjectionChargeUnitsTotal] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge01] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge02] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge03] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge04] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge05] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge06] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge07] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge08] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge09] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge10] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge11] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge12] decimal NOT NULL,
    [InitialProjectionNetPerDiem01] decimal NOT NULL,
    [InitialProjectionNetPerDiem02] decimal NOT NULL,
    [InitialProjectionNetPerDiem03] decimal NOT NULL,
    [InitialProjectionNetPerDiem04] decimal NOT NULL,
    [InitialProjectionNetPerDiem05] decimal NOT NULL,
    [InitialProjectionNetPerDiem06] decimal NOT NULL,
    [InitialProjectionNetPerDiem07] decimal NOT NULL,
    [InitialProjectionNetPerDiem08] decimal NOT NULL,
    [InitialProjectionNetPerDiem09] decimal NOT NULL,
    [InitialProjectionNetPerDiem10] decimal NOT NULL,
    [InitialProjectionNetPerDiem11] decimal NOT NULL,
    [InitialProjectionNetPerDiem12] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    PRIMARY KEY ([ReimbursementChargesID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_CPT] FOREIGN KEY ([PrimaryCPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__00A9DD25] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__019E015E] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__02922597] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__038649D0] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__047A6E09] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__056E9242] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__0662B67B] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__IsNew__0756DAB4] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Budge__1D7B25FD] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Entit__1E6F4A36] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Entit__1F636E6F] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Patie__205792A8] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Servi__214BB6E1] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Servi__223FDB1A] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Medic__2333FF53] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Depar__2428238C] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Payor__251C47C5] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Payor__26106BFE] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__27049037] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Prima__27F8B470] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__UBRev__28ECD8A9] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__UnitT__29E0FCE2] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF_ArchiveReimbursementCharges_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2BC94554] DEFAULT ((0)) FOR [InitialBudgetChargeDollars01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2CBD698D] DEFAULT ((0)) FOR [InitialBudgetChargeDollars02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2DB18DC6] DEFAULT ((0)) FOR [InitialBudgetChargeDollars03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2EA5B1FF] DEFAULT ((0)) FOR [InitialBudgetChargeDollars04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2F99D638] DEFAULT ((0)) FOR [InitialBudgetChargeDollars05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__308DFA71] DEFAULT ((0)) FOR [InitialBudgetChargeDollars06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__31821EAA] DEFAULT ((0)) FOR [InitialBudgetChargeDollars07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__327642E3] DEFAULT ((0)) FOR [InitialBudgetChargeDollars08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__336A671C] DEFAULT ((0)) FOR [InitialBudgetChargeDollars09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__345E8B55] DEFAULT ((0)) FOR [InitialBudgetChargeDollars10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3552AF8E] DEFAULT ((0)) FOR [InitialBudgetChargeDollars11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3646D3C7] DEFAULT ((0)) FOR [InitialBudgetChargeDollars12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__373AF800] DEFAULT ((0)) FOR [InitialBudgetChargeUnits01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__382F1C39] DEFAULT ((0)) FOR [InitialBudgetChargeUnits02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__39234072] DEFAULT ((0)) FOR [InitialBudgetChargeUnits03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3A1764AB] DEFAULT ((0)) FOR [InitialBudgetChargeUnits04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3B0B88E4] DEFAULT ((0)) FOR [InitialBudgetChargeUnits05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3BFFAD1D] DEFAULT ((0)) FOR [InitialBudgetChargeUnits06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3CF3D156] DEFAULT ((0)) FOR [InitialBudgetChargeUnits07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3DE7F58F] DEFAULT ((0)) FOR [InitialBudgetChargeUnits08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3EDC19C8] DEFAULT ((0)) FOR [InitialBudgetChargeUnits09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3FD03E01] DEFAULT ((0)) FOR [InitialBudgetChargeUnits10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__40C4623A] DEFAULT ((0)) FOR [InitialBudgetChargeUnits11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__41B88673] DEFAULT ((0)) FOR [InitialBudgetChargeUnits12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__42ACAAAC] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__43A0CEE5] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4494F31E] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__45891757] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__467D3B90] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__47715FC9] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__48658402] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4959A83B] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4A4DCC74] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4B41F0AD] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4C3614E6] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4D2A391F] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4E1E5D58] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4F128191] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5006A5CA] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__50FACA03] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__51EEEE3C] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__52E31275] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__53D736AE] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__54CB5AE7] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__55BF7F20] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__56B3A359] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__57A7C792] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__589BEBCB] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__59901004] DEFAULT ((0)) FOR [InitialProjectionChargeDollars01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5A84343D] DEFAULT ((0)) FOR [InitialProjectionChargeDollars02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5B785876] DEFAULT ((0)) FOR [InitialProjectionChargeDollars03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5C6C7CAF] DEFAULT ((0)) FOR [InitialProjectionChargeDollars04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5D60A0E8] DEFAULT ((0)) FOR [InitialProjectionChargeDollars05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5E54C521] DEFAULT ((0)) FOR [InitialProjectionChargeDollars06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5F48E95A] DEFAULT ((0)) FOR [InitialProjectionChargeDollars07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__603D0D93] DEFAULT ((0)) FOR [InitialProjectionChargeDollars08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__613131CC] DEFAULT ((0)) FOR [InitialProjectionChargeDollars09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__62255605] DEFAULT ((0)) FOR [InitialProjectionChargeDollars10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__63197A3E] DEFAULT ((0)) FOR [InitialProjectionChargeDollars11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__640D9E77] DEFAULT ((0)) FOR [InitialProjectionChargeDollars12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6501C2B0] DEFAULT ((0)) FOR [InitialProjectionChargeUnits01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__65F5E6E9] DEFAULT ((0)) FOR [InitialProjectionChargeUnits02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__66EA0B22] DEFAULT ((0)) FOR [InitialProjectionChargeUnits03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__67DE2F5B] DEFAULT ((0)) FOR [InitialProjectionChargeUnits04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__68D25394] DEFAULT ((0)) FOR [InitialProjectionChargeUnits05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__69C677CD] DEFAULT ((0)) FOR [InitialProjectionChargeUnits06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6ABA9C06] DEFAULT ((0)) FOR [InitialProjectionChargeUnits07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6BAEC03F] DEFAULT ((0)) FOR [InitialProjectionChargeUnits08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6CA2E478] DEFAULT ((0)) FOR [InitialProjectionChargeUnits09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6D9708B1] DEFAULT ((0)) FOR [InitialProjectionChargeUnits10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6E8B2CEA] DEFAULT ((0)) FOR [InitialProjectionChargeUnits11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6F7F5123] DEFAULT ((0)) FOR [InitialProjectionChargeUnits12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7073755C] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__71679995] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__725BBDCE] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__734FE207] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__74440640] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__75382A79] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__762C4EB2] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__772072EB] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__78149724] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7908BB5D] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__79FCDF96] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7AF103CF] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7BE52808] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7CD94C41] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7DCD707A] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7EC194B3] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7FB5B8EC] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem05]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementChargesBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementChargesBudget] (
    [RowID] int NOT NULL,
    [ReimbursementChargesID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedChargeDollars01] decimal NOT NULL,
    [AdjustedChargeDollars02] decimal NOT NULL,
    [AdjustedChargeDollars03] decimal NOT NULL,
    [AdjustedChargeDollars04] decimal NOT NULL,
    [AdjustedChargeDollars05] decimal NOT NULL,
    [AdjustedChargeDollars06] decimal NOT NULL,
    [AdjustedChargeDollars07] decimal NOT NULL,
    [AdjustedChargeDollars08] decimal NOT NULL,
    [AdjustedChargeDollars09] decimal NOT NULL,
    [AdjustedChargeDollars10] decimal NOT NULL,
    [AdjustedChargeDollars11] decimal NOT NULL,
    [AdjustedChargeDollars12] decimal NOT NULL,
    [AdjustedChargeDollarsTotal] decimal NOT NULL,
    [AdjustedChargeUnits01] decimal NOT NULL,
    [AdjustedChargeUnits02] decimal NOT NULL,
    [AdjustedChargeUnits03] decimal NOT NULL,
    [AdjustedChargeUnits04] decimal NOT NULL,
    [AdjustedChargeUnits05] decimal NOT NULL,
    [AdjustedChargeUnits06] decimal NOT NULL,
    [AdjustedChargeUnits07] decimal NOT NULL,
    [AdjustedChargeUnits08] decimal NOT NULL,
    [AdjustedChargeUnits09] decimal NOT NULL,
    [AdjustedChargeUnits10] decimal NOT NULL,
    [AdjustedChargeUnits11] decimal NOT NULL,
    [AdjustedChargeUnits12] decimal NOT NULL,
    [AdjustedChargeUnitsTotal] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge01] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge02] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge03] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge04] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge05] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge06] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge07] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge08] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge09] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge10] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge11] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge12] decimal NOT NULL,
    [AdjustedNetPerDiem01] decimal NOT NULL,
    [AdjustedNetPerDiem02] decimal NOT NULL,
    [AdjustedNetPerDiem03] decimal NOT NULL,
    [AdjustedNetPerDiem04] decimal NOT NULL,
    [AdjustedNetPerDiem05] decimal NOT NULL,
    [AdjustedNetPerDiem06] decimal NOT NULL,
    [AdjustedNetPerDiem07] decimal NOT NULL,
    [AdjustedNetPerDiem08] decimal NOT NULL,
    [AdjustedNetPerDiem09] decimal NOT NULL,
    [AdjustedNetPerDiem10] decimal NOT NULL,
    [AdjustedNetPerDiem11] decimal NOT NULL,
    [AdjustedNetPerDiem12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [FK_ArchiveFactReimbursementChargesBudget_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__003FC8D1] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0133ED0A] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__02281143] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__031C357C] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__041059B5] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05047DEE] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05F8A227] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__06ECC660] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__07E0EA99] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__08D50ED2] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__09C9330B] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Reimb__5925FBB0] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__5A1A1FE9] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__5B0E4422] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__5C02685B] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5CF68C94] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5DEAB0CD] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5EDED506] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5FD2F93F] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60C71D78] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__61BB41B1] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__62AF65EA] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__63A38A23] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6497AE5C] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__658BD295] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__667FF6CE] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67741B07] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__68683F40] DEFAULT ((0)) FOR [AdjustedChargeUnits01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__695C6379] DEFAULT ((0)) FOR [AdjustedChargeUnits02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6A5087B2] DEFAULT ((0)) FOR [AdjustedChargeUnits03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6B44ABEB] DEFAULT ((0)) FOR [AdjustedChargeUnits04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6C38D024] DEFAULT ((0)) FOR [AdjustedChargeUnits05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6D2CF45D] DEFAULT ((0)) FOR [AdjustedChargeUnits06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6E211896] DEFAULT ((0)) FOR [AdjustedChargeUnits07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6F153CCF] DEFAULT ((0)) FOR [AdjustedChargeUnits08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__70096108] DEFAULT ((0)) FOR [AdjustedChargeUnits09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__70FD8541] DEFAULT ((0)) FOR [AdjustedChargeUnits10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__71F1A97A] DEFAULT ((0)) FOR [AdjustedChargeUnits11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__72E5CDB3] DEFAULT ((0)) FOR [AdjustedChargeUnits12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__73D9F1EC] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__74CE1625] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__75C23A5E] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__76B65E97] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__77AA82D0] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__789EA709] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7992CB42] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7A86EF7B] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7B7B13B4] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7C6F37ED] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7D635C26] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7E57805F] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7F4BA498] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementChargesHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementChargesHistory] (
    [RowID] int NOT NULL,
    [ReimbursementChargesID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [PriorYearActualChargeDollars01] decimal NOT NULL,
    [PriorYearActualChargeDollars02] decimal NOT NULL,
    [PriorYearActualChargeDollars03] decimal NOT NULL,
    [PriorYearActualChargeDollars04] decimal NOT NULL,
    [PriorYearActualChargeDollars05] decimal NOT NULL,
    [PriorYearActualChargeDollars06] decimal NOT NULL,
    [PriorYearActualChargeDollars07] decimal NOT NULL,
    [PriorYearActualChargeDollars08] decimal NOT NULL,
    [PriorYearActualChargeDollars09] decimal NOT NULL,
    [PriorYearActualChargeDollars10] decimal NOT NULL,
    [PriorYearActualChargeDollars11] decimal NOT NULL,
    [PriorYearActualChargeDollars12] decimal NOT NULL,
    [PriorYearActualChargeDollarsTotal] decimal NOT NULL,
    [ActualYTDChargeDollars01] decimal NOT NULL,
    [ActualYTDChargeDollars02] decimal NOT NULL,
    [ActualYTDChargeDollars03] decimal NOT NULL,
    [ActualYTDChargeDollars04] decimal NOT NULL,
    [ActualYTDChargeDollars05] decimal NOT NULL,
    [ActualYTDChargeDollars06] decimal NOT NULL,
    [ActualYTDChargeDollars07] decimal NOT NULL,
    [ActualYTDChargeDollars08] decimal NOT NULL,
    [ActualYTDChargeDollars09] decimal NOT NULL,
    [ActualYTDChargeDollars10] decimal NOT NULL,
    [ActualYTDChargeDollars11] decimal NOT NULL,
    [ActualYTDChargeDollars12] decimal NOT NULL,
    [ActualYTDChargeDollarsTotal] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars01] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars02] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars03] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars04] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars05] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars06] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars07] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars08] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars09] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars10] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars11] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars12] decimal NOT NULL,
    [CurrentYearBudgetChargeDollarsTotal] decimal NOT NULL,
    [PriorYearActualChargeUnits01] decimal NOT NULL,
    [PriorYearActualChargeUnits02] decimal NOT NULL,
    [PriorYearActualChargeUnits03] decimal NOT NULL,
    [PriorYearActualChargeUnits04] decimal NOT NULL,
    [PriorYearActualChargeUnits05] decimal NOT NULL,
    [PriorYearActualChargeUnits06] decimal NOT NULL,
    [PriorYearActualChargeUnits07] decimal NOT NULL,
    [PriorYearActualChargeUnits08] decimal NOT NULL,
    [PriorYearActualChargeUnits09] decimal NOT NULL,
    [PriorYearActualChargeUnits10] decimal NOT NULL,
    [PriorYearActualChargeUnits11] decimal NOT NULL,
    [PriorYearActualChargeUnits12] decimal NOT NULL,
    [PriorYearActualChargeUnitsTotal] decimal NOT NULL,
    [ActualYTDChargeUnits01] decimal NOT NULL,
    [ActualYTDChargeUnits02] decimal NOT NULL,
    [ActualYTDChargeUnits03] decimal NOT NULL,
    [ActualYTDChargeUnits04] decimal NOT NULL,
    [ActualYTDChargeUnits05] decimal NOT NULL,
    [ActualYTDChargeUnits06] decimal NOT NULL,
    [ActualYTDChargeUnits07] decimal NOT NULL,
    [ActualYTDChargeUnits08] decimal NOT NULL,
    [ActualYTDChargeUnits09] decimal NOT NULL,
    [ActualYTDChargeUnits10] decimal NOT NULL,
    [ActualYTDChargeUnits11] decimal NOT NULL,
    [ActualYTDChargeUnits12] decimal NOT NULL,
    [ActualYTDChargeUnitsTotal] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits01] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits02] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits03] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits04] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits05] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits06] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits07] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits08] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits09] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits10] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits11] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits12] decimal NOT NULL,
    [CurrentYearBudgetChargeUnitsTotal] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge01] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge02] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge03] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge04] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge05] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge06] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge07] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge08] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge09] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge10] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge11] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge12] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge01] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge02] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge03] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge04] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge05] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge06] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge07] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge08] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge09] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge10] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge11] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge12] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge01] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge02] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge03] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge04] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge05] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge06] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge07] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge08] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge09] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge10] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge11] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge12] decimal NOT NULL,
    [PriorYearActualNetPerDiem01] decimal NOT NULL,
    [PriorYearActualNetPerDiem02] decimal NOT NULL,
    [PriorYearActualNetPerDiem03] decimal NOT NULL,
    [PriorYearActualNetPerDiem04] decimal NOT NULL,
    [PriorYearActualNetPerDiem05] decimal NOT NULL,
    [PriorYearActualNetPerDiem06] decimal NOT NULL,
    [PriorYearActualNetPerDiem07] decimal NOT NULL,
    [PriorYearActualNetPerDiem08] decimal NOT NULL,
    [PriorYearActualNetPerDiem09] decimal NOT NULL,
    [PriorYearActualNetPerDiem10] decimal NOT NULL,
    [PriorYearActualNetPerDiem11] decimal NOT NULL,
    [PriorYearActualNetPerDiem12] decimal NOT NULL,
    [ActualYTDNetPerDiem01] decimal NOT NULL,
    [ActualYTDNetPerDiem02] decimal NOT NULL,
    [ActualYTDNetPerDiem03] decimal NOT NULL,
    [ActualYTDNetPerDiem04] decimal NOT NULL,
    [ActualYTDNetPerDiem05] decimal NOT NULL,
    [ActualYTDNetPerDiem06] decimal NOT NULL,
    [ActualYTDNetPerDiem07] decimal NOT NULL,
    [ActualYTDNetPerDiem08] decimal NOT NULL,
    [ActualYTDNetPerDiem09] decimal NOT NULL,
    [ActualYTDNetPerDiem10] decimal NOT NULL,
    [ActualYTDNetPerDiem11] decimal NOT NULL,
    [ActualYTDNetPerDiem12] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem01] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem02] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem03] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem04] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem05] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem06] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem07] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem08] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem09] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem10] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem11] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [FK_ArchiveFactReimbursementChargesHistory_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0094CE8C] DEFAULT ((0)) FOR [ActualYTDNetPerDiem05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0188F2C5] DEFAULT ((0)) FOR [ActualYTDNetPerDiem06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__027D16FE] DEFAULT ((0)) FOR [ActualYTDNetPerDiem07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__03713B37] DEFAULT ((0)) FOR [ActualYTDNetPerDiem08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__04655F70] DEFAULT ((0)) FOR [ActualYTDNetPerDiem09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__055983A9] DEFAULT ((0)) FOR [ActualYTDNetPerDiem10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__064DA7E2] DEFAULT ((0)) FOR [ActualYTDNetPerDiem11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Reimb__0682B20C] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0741CC1B] DEFAULT ((0)) FOR [ActualYTDNetPerDiem12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__LockT__0776D645] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0835F054] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__LockF__086AFA7E] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__092A148D] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Budge__095F1EB7] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0A1E38C6] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0A5342F0] DEFAULT ((0)) FOR [PriorYearActualChargeDollars01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0B125CFF] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0B476729] DEFAULT ((0)) FOR [PriorYearActualChargeDollars02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0C068138] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0C3B8B62] DEFAULT ((0)) FOR [PriorYearActualChargeDollars03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0CFAA571] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0D2FAF9B] DEFAULT ((0)) FOR [PriorYearActualChargeDollars04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0DEEC9AA] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0E23D3D4] DEFAULT ((0)) FOR [PriorYearActualChargeDollars05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0EE2EDE3] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0F17F80D] DEFAULT ((0)) FOR [PriorYearActualChargeDollars06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0FD7121C] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__100C1C46] DEFAULT ((0)) FOR [PriorYearActualChargeDollars07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__10CB3655] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1100407F] DEFAULT ((0)) FOR [PriorYearActualChargeDollars08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__11BF5A8E] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__11F464B8] DEFAULT ((0)) FOR [PriorYearActualChargeDollars09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__12B37EC7] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__12E888F1] DEFAULT ((0)) FOR [PriorYearActualChargeDollars10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__13DCAD2A] DEFAULT ((0)) FOR [PriorYearActualChargeDollars11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__14D0D163] DEFAULT ((0)) FOR [PriorYearActualChargeDollars12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__15C4F59C] DEFAULT ((0)) FOR [ActualYTDChargeDollars01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__16B919D5] DEFAULT ((0)) FOR [ActualYTDChargeDollars02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__17AD3E0E] DEFAULT ((0)) FOR [ActualYTDChargeDollars03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__18A16247] DEFAULT ((0)) FOR [ActualYTDChargeDollars04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__19958680] DEFAULT ((0)) FOR [ActualYTDChargeDollars05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1A89AAB9] DEFAULT ((0)) FOR [ActualYTDChargeDollars06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1B7DCEF2] DEFAULT ((0)) FOR [ActualYTDChargeDollars07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1C71F32B] DEFAULT ((0)) FOR [ActualYTDChargeDollars08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1D661764] DEFAULT ((0)) FOR [ActualYTDChargeDollars09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1E5A3B9D] DEFAULT ((0)) FOR [ActualYTDChargeDollars10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1F4E5FD6] DEFAULT ((0)) FOR [ActualYTDChargeDollars11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__2042840F] DEFAULT ((0)) FOR [ActualYTDChargeDollars12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2136A848] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__222ACC81] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__231EF0BA] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__241314F3] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2507392C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__25FB5D65] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__26EF819E] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__27E3A5D7] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__28D7CA10] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__29CBEE49] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2AC01282] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2BB436BB] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2CA85AF4] DEFAULT ((0)) FOR [PriorYearActualChargeUnits01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2D9C7F2D] DEFAULT ((0)) FOR [PriorYearActualChargeUnits02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2E90A366] DEFAULT ((0)) FOR [PriorYearActualChargeUnits03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2F84C79F] DEFAULT ((0)) FOR [PriorYearActualChargeUnits04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3078EBD8] DEFAULT ((0)) FOR [PriorYearActualChargeUnits05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__316D1011] DEFAULT ((0)) FOR [PriorYearActualChargeUnits06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3261344A] DEFAULT ((0)) FOR [PriorYearActualChargeUnits07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__33555883] DEFAULT ((0)) FOR [PriorYearActualChargeUnits08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__34497CBC] DEFAULT ((0)) FOR [PriorYearActualChargeUnits09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__353DA0F5] DEFAULT ((0)) FOR [PriorYearActualChargeUnits10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3631C52E] DEFAULT ((0)) FOR [PriorYearActualChargeUnits11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3725E967] DEFAULT ((0)) FOR [PriorYearActualChargeUnits12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__381A0DA0] DEFAULT ((0)) FOR [ActualYTDChargeUnits01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__390E31D9] DEFAULT ((0)) FOR [ActualYTDChargeUnits02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3A025612] DEFAULT ((0)) FOR [ActualYTDChargeUnits03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3AF67A4B] DEFAULT ((0)) FOR [ActualYTDChargeUnits04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3BEA9E84] DEFAULT ((0)) FOR [ActualYTDChargeUnits05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3CDEC2BD] DEFAULT ((0)) FOR [ActualYTDChargeUnits06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3DD2E6F6] DEFAULT ((0)) FOR [ActualYTDChargeUnits07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3EC70B2F] DEFAULT ((0)) FOR [ActualYTDChargeUnits08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3FBB2F68] DEFAULT ((0)) FOR [ActualYTDChargeUnits09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__40AF53A1] DEFAULT ((0)) FOR [ActualYTDChargeUnits10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__41A377DA] DEFAULT ((0)) FOR [ActualYTDChargeUnits11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__42979C13] DEFAULT ((0)) FOR [ActualYTDChargeUnits12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__438BC04C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__447FE485] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__457408BE] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__46682CF7] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__475C5130] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__48507569] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__494499A2] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4A38BDDB] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4B2CE214] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4C21064D] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4D152A86] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4E094EBF] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__4EFD72F8] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__4FF19731] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__50E5BB6A] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__51D9DFA3] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__52CE03DC] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__53C22815] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__54B64C4E] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__55AA7087] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__569E94C0] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5792B8F9] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5886DD32] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__597B016B] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5A6F25A4] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5B6349DD] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5C576E16] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5D4B924F] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5E3FB688] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5F33DAC1] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6027FEFA] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__611C2333] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6210476C] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__63046BA5] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__63F88FDE] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__64ECB417] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__65E0D850] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__66D4FC89] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__67C920C2] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__68BD44FB] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__69B16934] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6AA58D6D] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6B99B1A6] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6C8DD5DF] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6D81FA18] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6E761E51] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6F6A428A] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__705E66C3] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__71528AFC] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7246AF35] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__733AD36E] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__742EF7A7] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__75231BE0] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__76174019] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__770B6452] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__77FF888B] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__78F3ACC4] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__79E7D0FD] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7ADBF536] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7BD0196F] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7CC43DA8] DEFAULT ((0)) FOR [ActualYTDNetPerDiem01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7DB861E1] DEFAULT ((0)) FOR [ActualYTDNetPerDiem02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7EAC861A] DEFAULT ((0)) FOR [ActualYTDNetPerDiem03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7FA0AA53] DEFAULT ((0)) FOR [ActualYTDNetPerDiem04]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementChargesProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementChargesProjection] (
    [RowID] int NOT NULL,
    [ReimbursementChargesID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedChargeDollars01] decimal NOT NULL,
    [AdjustedChargeDollars02] decimal NOT NULL,
    [AdjustedChargeDollars03] decimal NOT NULL,
    [AdjustedChargeDollars04] decimal NOT NULL,
    [AdjustedChargeDollars05] decimal NOT NULL,
    [AdjustedChargeDollars06] decimal NOT NULL,
    [AdjustedChargeDollars07] decimal NOT NULL,
    [AdjustedChargeDollars08] decimal NOT NULL,
    [AdjustedChargeDollars09] decimal NOT NULL,
    [AdjustedChargeDollars10] decimal NOT NULL,
    [AdjustedChargeDollars11] decimal NOT NULL,
    [AdjustedChargeDollars12] decimal NOT NULL,
    [AdjustedChargeDollarsTotal] decimal NOT NULL,
    [AdjustedChargeUnits01] decimal NOT NULL,
    [AdjustedChargeUnits02] decimal NOT NULL,
    [AdjustedChargeUnits03] decimal NOT NULL,
    [AdjustedChargeUnits04] decimal NOT NULL,
    [AdjustedChargeUnits05] decimal NOT NULL,
    [AdjustedChargeUnits06] decimal NOT NULL,
    [AdjustedChargeUnits07] decimal NOT NULL,
    [AdjustedChargeUnits08] decimal NOT NULL,
    [AdjustedChargeUnits09] decimal NOT NULL,
    [AdjustedChargeUnits10] decimal NOT NULL,
    [AdjustedChargeUnits11] decimal NOT NULL,
    [AdjustedChargeUnits12] decimal NOT NULL,
    [AdjustedChargeUnitsTotal] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge01] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge02] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge03] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge04] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge05] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge06] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge07] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge08] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge09] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge10] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge11] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge12] decimal NOT NULL,
    [AdjustedNetPerDiem01] decimal NOT NULL,
    [AdjustedNetPerDiem02] decimal NOT NULL,
    [AdjustedNetPerDiem03] decimal NOT NULL,
    [AdjustedNetPerDiem04] decimal NOT NULL,
    [AdjustedNetPerDiem05] decimal NOT NULL,
    [AdjustedNetPerDiem06] decimal NOT NULL,
    [AdjustedNetPerDiem07] decimal NOT NULL,
    [AdjustedNetPerDiem08] decimal NOT NULL,
    [AdjustedNetPerDiem09] decimal NOT NULL,
    [AdjustedNetPerDiem10] decimal NOT NULL,
    [AdjustedNetPerDiem11] decimal NOT NULL,
    [AdjustedNetPerDiem12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [FK_ArchiveFactReimbursementChargesProjection_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Reimb__0D99C3EF] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__0E8DE828] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__0F820C61] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__1076309A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__116A54D3] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__125E790C] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__13529D45] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1446C17E] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__153AE5B7] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__162F09F0] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__17232E29] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__18175262] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__190B769B] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19FF9AD4] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1AF3BF0D] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1BE7E346] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1CDC077F] DEFAULT ((0)) FOR [AdjustedChargeUnits01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1DD02BB8] DEFAULT ((0)) FOR [AdjustedChargeUnits02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1EC44FF1] DEFAULT ((0)) FOR [AdjustedChargeUnits03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1FB8742A] DEFAULT ((0)) FOR [AdjustedChargeUnits04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__20AC9863] DEFAULT ((0)) FOR [AdjustedChargeUnits05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__21A0BC9C] DEFAULT ((0)) FOR [AdjustedChargeUnits06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2294E0D5] DEFAULT ((0)) FOR [AdjustedChargeUnits07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2389050E] DEFAULT ((0)) FOR [AdjustedChargeUnits08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__247D2947] DEFAULT ((0)) FOR [AdjustedChargeUnits09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__25714D80] DEFAULT ((0)) FOR [AdjustedChargeUnits10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__266571B9] DEFAULT ((0)) FOR [AdjustedChargeUnits11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__275995F2] DEFAULT ((0)) FOR [AdjustedChargeUnits12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__284DBA2B] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2941DE64] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2A36029D] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2B2A26D6] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2C1E4B0F] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2D126F48] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2E069381] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2EFAB7BA] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2FEEDBF3] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__30E3002C] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__31D72465] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__32CB489E] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__33BF6CD7] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__34B39110] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__35A7B549] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__369BD982] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__378FFDBB] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__388421F4] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3978462D] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3A6C6A66] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3B608E9F] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3C54B2D8] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3D48D711] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3E3CFB4A] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementEncounter ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementEncounter] (
    [ReimbursementEncounterID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetNetPerEncounter01] decimal NOT NULL,
    [InitialBudgetNetPerEncounter02] decimal NOT NULL,
    [InitialBudgetNetPerEncounter03] decimal NOT NULL,
    [InitialBudgetNetPerEncounter04] decimal NOT NULL,
    [InitialBudgetNetPerEncounter05] decimal NOT NULL,
    [InitialBudgetNetPerEncounter06] decimal NOT NULL,
    [InitialBudgetNetPerEncounter07] decimal NOT NULL,
    [InitialBudgetNetPerEncounter08] decimal NOT NULL,
    [InitialBudgetNetPerEncounter09] decimal NOT NULL,
    [InitialBudgetNetPerEncounter10] decimal NOT NULL,
    [InitialBudgetNetPerEncounter11] decimal NOT NULL,
    [InitialBudgetNetPerEncounter12] decimal NOT NULL,
    [InitialBudgetNetReimbursement01] decimal NULL,
    [InitialBudgetNetReimbursement02] decimal NULL,
    [InitialBudgetNetReimbursement03] decimal NULL,
    [InitialBudgetNetReimbursement04] decimal NULL,
    [InitialBudgetNetReimbursement05] decimal NULL,
    [InitialBudgetNetReimbursement06] decimal NULL,
    [InitialBudgetNetReimbursement07] decimal NULL,
    [InitialBudgetNetReimbursement08] decimal NULL,
    [InitialBudgetNetReimbursement09] decimal NULL,
    [InitialBudgetNetReimbursement10] decimal NULL,
    [InitialBudgetNetReimbursement11] decimal NULL,
    [InitialBudgetNetReimbursement12] decimal NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialProjectionNetPerEncounter01] decimal NOT NULL,
    [InitialProjectionNetPerEncounter02] decimal NOT NULL,
    [InitialProjectionNetPerEncounter03] decimal NOT NULL,
    [InitialProjectionNetPerEncounter04] decimal NOT NULL,
    [InitialProjectionNetPerEncounter05] decimal NOT NULL,
    [InitialProjectionNetPerEncounter06] decimal NOT NULL,
    [InitialProjectionNetPerEncounter07] decimal NOT NULL,
    [InitialProjectionNetPerEncounter08] decimal NOT NULL,
    [InitialProjectionNetPerEncounter09] decimal NOT NULL,
    [InitialProjectionNetPerEncounter10] decimal NOT NULL,
    [InitialProjectionNetPerEncounter11] decimal NOT NULL,
    [InitialProjectionNetPerEncounter12] decimal NOT NULL,
    [InitialProjectionNetReimbursement01] decimal NULL,
    [InitialProjectionNetReimbursement02] decimal NULL,
    [InitialProjectionNetReimbursement03] decimal NULL,
    [InitialProjectionNetReimbursement04] decimal NULL,
    [InitialProjectionNetReimbursement05] decimal NULL,
    [InitialProjectionNetReimbursement06] decimal NULL,
    [InitialProjectionNetReimbursement07] decimal NULL,
    [InitialProjectionNetReimbursement08] decimal NULL,
    [InitialProjectionNetReimbursement09] decimal NULL,
    [InitialProjectionNetReimbursement10] decimal NULL,
    [InitialProjectionNetReimbursement11] decimal NULL,
    [InitialProjectionNetReimbursement12] decimal NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    PRIMARY KEY ([ReimbursementEncounterID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0054D76A] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0148FBA3] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__023D1FDC] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__03314415] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0425684E] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__05198C87] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__060DB0C0] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0701D4F9] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__07F5F932] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__08EA1D6B] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__09DE41A4] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0AD265DD] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0BC68A16] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0CBAAE4F] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0DAED288] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0EA2F6C1] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0F971AFA] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__108B3F33] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__117F636C] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__127387A5] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1367ABDE] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__145BD017] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__154FF450] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__16441889] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__17383CC2] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__182C60FB] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__19208534] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1A14A96D] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1B08CDA6] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1BFCF1DF] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1CF11618] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1DE53A51] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1ED95E8A] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1FCD82C3] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__20C1A6FC] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__21B5CB35] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__22A9EF6E] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__239E13A7] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__IsNew__249237E0] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Budge__69717212] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__6A65964B] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__6B59BA84] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Patie__6C4DDEBD] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__6D4202F6] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__6E36272F] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Medic__6F2A4B68] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Depar__701E6FA1] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__711293DA] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__7206B813] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__72FADC4C] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__CPTID__73EF0085] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__UnitT__74E324BE] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF_ArchiveFactReimbursementEncounter_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__76CB6D30] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__77BF9169] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__78B3B5A2] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__79A7D9DB] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7A9BFE14] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7B90224D] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7C844686] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7D786ABF] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7E6C8EF8] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7F60B331] DEFAULT ((0)) FOR [InitialBudget10]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementEncounterBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementEncounterBudget] (
    [RowID] int NOT NULL,
    [ReimbursementEncounterID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [AdjustedNetPerEncounterValue01] decimal NOT NULL,
    [AdjustedNetPerEncounterValue02] decimal NOT NULL,
    [AdjustedNetPerEncounterValue03] decimal NOT NULL,
    [AdjustedNetPerEncounterValue04] decimal NOT NULL,
    [AdjustedNetPerEncounterValue05] decimal NOT NULL,
    [AdjustedNetPerEncounterValue06] decimal NOT NULL,
    [AdjustedNetPerEncounterValue07] decimal NOT NULL,
    [AdjustedNetPerEncounterValue08] decimal NOT NULL,
    [AdjustedNetPerEncounterValue09] decimal NOT NULL,
    [AdjustedNetPerEncounterValue10] decimal NOT NULL,
    [AdjustedNetPerEncounterValue11] decimal NOT NULL,
    [AdjustedNetPerEncounterValue12] decimal NOT NULL,
    [AdjustedNetReimbursementValue01] decimal NULL,
    [AdjustedNetReimbursementValue02] decimal NULL,
    [AdjustedNetReimbursementValue03] decimal NULL,
    [AdjustedNetReimbursementValue04] decimal NULL,
    [AdjustedNetReimbursementValue05] decimal NULL,
    [AdjustedNetReimbursementValue06] decimal NULL,
    [AdjustedNetReimbursementValue07] decimal NULL,
    [AdjustedNetReimbursementValue08] decimal NULL,
    [AdjustedNetReimbursementValue09] decimal NULL,
    [AdjustedNetReimbursementValue10] decimal NULL,
    [AdjustedNetReimbursementValue11] decimal NULL,
    [AdjustedNetReimbursementValue12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounterBudget_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[ArchiveFactReimbursementEncounter] ([ReimbursementEncounterID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Reimb__4E8871AC] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__4F7C95E5] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__5070BA1E] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__5164DE57] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__52590290] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__534D26C9] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__54414B02] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__55356F3B] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__56299374] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__571DB7AD] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5811DBE6] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5906001F] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__59FA2458] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5AEE4891] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5BE26CCA] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5CD69103] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5DCAB53C] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5EBED975] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5FB2FDAE] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60A721E7] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__619B4620] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__628F6A59] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__63838E92] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6477B2CB] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__656BD704] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__665FFB3D] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67541F76] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__684843AF] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementEncounterHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementEncounterHistory] (
    [RowID] int NOT NULL,
    [ReimbursementEncounterID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NULL,
    [PriorYearActualNetPerEncounterValue01] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue02] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue03] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue04] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue05] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue06] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue07] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue08] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue09] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue10] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue11] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue12] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue01] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue02] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue03] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue04] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue05] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue06] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue07] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue08] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue09] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue10] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue11] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue12] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget01] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget02] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget03] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget04] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget05] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget06] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget07] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget08] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget09] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget10] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget11] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget12] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue01] decimal NULL,
    [PriorYearActualNetReimbursementValue02] decimal NULL,
    [PriorYearActualNetReimbursementValue03] decimal NULL,
    [PriorYearActualNetReimbursementValue04] decimal NULL,
    [PriorYearActualNetReimbursementValue05] decimal NULL,
    [PriorYearActualNetReimbursementValue06] decimal NULL,
    [PriorYearActualNetReimbursementValue07] decimal NULL,
    [PriorYearActualNetReimbursementValue08] decimal NULL,
    [PriorYearActualNetReimbursementValue09] decimal NULL,
    [PriorYearActualNetReimbursementValue10] decimal NULL,
    [PriorYearActualNetReimbursementValue11] decimal NULL,
    [PriorYearActualNetReimbursementValue12] decimal NULL,
    [ActualYTDNetReimbursementValue01] decimal NULL,
    [ActualYTDNetReimbursementValue02] decimal NULL,
    [ActualYTDNetReimbursementValue03] decimal NULL,
    [ActualYTDNetReimbursementValue04] decimal NULL,
    [ActualYTDNetReimbursementValue05] decimal NULL,
    [ActualYTDNetReimbursementValue06] decimal NULL,
    [ActualYTDNetReimbursementValue07] decimal NULL,
    [ActualYTDNetReimbursementValue08] decimal NULL,
    [ActualYTDNetReimbursementValue09] decimal NULL,
    [ActualYTDNetReimbursementValue10] decimal NULL,
    [ActualYTDNetReimbursementValue11] decimal NULL,
    [ActualYTDNetReimbursementValue12] decimal NULL,
    [CurrentYearNetReimbursementBudget01] decimal NULL,
    [CurrentYearNetReimbursementBudget02] decimal NULL,
    [CurrentYearNetReimbursementBudget03] decimal NULL,
    [CurrentYearNetReimbursementBudget04] decimal NULL,
    [CurrentYearNetReimbursementBudget05] decimal NULL,
    [CurrentYearNetReimbursementBudget06] decimal NULL,
    [CurrentYearNetReimbursementBudget07] decimal NULL,
    [CurrentYearNetReimbursementBudget08] decimal NULL,
    [CurrentYearNetReimbursementBudget09] decimal NULL,
    [CurrentYearNetReimbursementBudget10] decimal NULL,
    [CurrentYearNetReimbursementBudget11] decimal NULL,
    [CurrentYearNetReimbursementBudget12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounterHistory_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[ArchiveFactReimbursementEncounter] ([ReimbursementEncounterID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0074D2FB] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0168F734] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__025D1B6D] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__03513FA6] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__044563DF] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__05398818] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__062DAC51] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0721D08A] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0815F4C3] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__090A18FC] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__09FE3D35] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0AF2616E] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0BE685A7] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0CDAA9E0] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0DCECE19] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0EC2F252] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0FB7168B] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__10AB3AC4] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__119F5EFD] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__12938336] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1387A76F] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__147BCBA8] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__156FEFE1] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1664141A] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__17583853] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__184C5C8C] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__194080C5] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1A34A4FE] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1B28C937] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1C1CED70] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1D1111A9] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1E0535E2] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1EF95A1B] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1FED7E54] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__20E1A28D] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Reimb__5C377285] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5D2B96BE] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5E1FBAF7] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5F13DF30] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__60080369] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__60FC27A2] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__61F04BDB] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__62E47014] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__63D8944D] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__64CCB886] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__65C0DCBF] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__66B500F8] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__67A92531] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__689D496A] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__69916DA3] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6A8591DC] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6B79B615] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6C6DDA4E] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6D61FE87] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6E5622C0] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6F4A46F9] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__703E6B32] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__71328F6B] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7226B3A4] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__731AD7DD] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__740EFC16] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7503204F] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__75F74488] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__76EB68C1] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__77DF8CFA] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__78D3B133] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__79C7D56C] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7ABBF9A5] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7BB01DDE] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7CA44217] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7D986650] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7E8C8A89] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7F80AEC2] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue01]; GO

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

---------------------------------------------
-- fp.ArchiveFactReimbursementEncounterProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactReimbursementEncounterProjection] (
    [RowID] int NOT NULL,
    [ReimbursementEncounterID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [AdjustedNetPerEncounterValue01] decimal NOT NULL,
    [AdjustedNetPerEncounterValue02] decimal NOT NULL,
    [AdjustedNetPerEncounterValue03] decimal NOT NULL,
    [AdjustedNetPerEncounterValue04] decimal NOT NULL,
    [AdjustedNetPerEncounterValue05] decimal NOT NULL,
    [AdjustedNetPerEncounterValue06] decimal NOT NULL,
    [AdjustedNetPerEncounterValue07] decimal NOT NULL,
    [AdjustedNetPerEncounterValue08] decimal NOT NULL,
    [AdjustedNetPerEncounterValue09] decimal NOT NULL,
    [AdjustedNetPerEncounterValue10] decimal NOT NULL,
    [AdjustedNetPerEncounterValue11] decimal NOT NULL,
    [AdjustedNetPerEncounterValue12] decimal NOT NULL,
    [AdjustedNetReimbursementValue01] decimal NULL,
    [AdjustedNetReimbursementValue02] decimal NULL,
    [AdjustedNetReimbursementValue03] decimal NULL,
    [AdjustedNetReimbursementValue04] decimal NULL,
    [AdjustedNetReimbursementValue05] decimal NULL,
    [AdjustedNetReimbursementValue06] decimal NULL,
    [AdjustedNetReimbursementValue07] decimal NULL,
    [AdjustedNetReimbursementValue08] decimal NULL,
    [AdjustedNetReimbursementValue09] decimal NULL,
    [AdjustedNetReimbursementValue10] decimal NULL,
    [AdjustedNetReimbursementValue11] decimal NULL,
    [AdjustedNetReimbursementValue12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounterProjection_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[ArchiveFactReimbursementEncounter] ([ReimbursementEncounterID]); GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__00DEE74F] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__01D30B88] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__02C72FC1] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__03BB53FA] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__04AF7833] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05A39C6C] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0697C0A5] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__078BE4DE] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__08800917] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__09742D50] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0A685189] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B5C75C2] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0C5099FB] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0D44BE34] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0E38E26D] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0F2D06A6] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__10212ADF] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__11154F18] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12097351] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12FD978A] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__13F1BBC3] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__14E5DFFC] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__15DA0435] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__16CE286E] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__17C24CA7] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__18B670E0] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19AA9519] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO
ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Reimb__7FEAC316] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO

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

---------------------------------------------
-- fp.ArchiveFactServiceLineEncounter ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactServiceLineEncounter] (
    [ServiceLineEncounterID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    PRIMARY KEY ([ServiceLineEncounterID])
);

CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_BudgetConfig] ON [fp].[ArchiveFactServiceLineEncounter] ([BudgetConfigID]) INCLUDE ([ServiceLineEncounterID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_Department] ON [fp].[ArchiveFactServiceLineEncounter] ([DepartmentID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_Entity] ON [fp].[ArchiveFactServiceLineEncounter] ([EntityID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_EntityGroupConfig] ON [fp].[ArchiveFactServiceLineEncounter] ([EntityGroupConfigID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_ServiceLine] ON [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounter] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_MSDRG] FOREIGN KEY ([MSDRGID]) REFERENCES [dss].[DimMSDRG] ([MSDRGID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_PhysicianSpecialty] FOREIGN KEY ([PhysicianSpecialtyID]) REFERENCES [fw].[DimPhysicianSpecialty] ([PhysicianSpecialtyID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Provider] FOREIGN KEY ([ProviderID]) REFERENCES [fw].[DimProvider] ([ProviderID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__006783FE] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__015BA837] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__024FCC70] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0343F0A9] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__043814E2] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__052C391B] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__06205D54] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0714818D] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0808A5C6] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__08FCC9FF] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__09F0EE38] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0AE51271] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0BD936AA] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0CCD5AE3] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0DC17F1C] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0EB5A355] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0FA9C78E] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__109DEBC7] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__11921000] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__12863439] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__137A5872] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__146E7CAB] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1562A0E4] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1656C51D] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__174AE956] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__183F0D8F] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__193331C8] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1A275601] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1B1B7A3A] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1C0F9E73] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1D03C2AC] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1DF7E6E5] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1EEC0B1E] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1FE02F57] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__20D45390] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__21C877C9] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__22BC9C02] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__IsNew__23B0C03B] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Budge__65B38DC2] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__66A7B1FB] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__679BD634] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Patie__688FFA6D] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__69841EA6] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__6A7842DF] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__AgeCo__6B6C6718] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Medic__6C608B51] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Depar__6D54AF8A] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__6E48D3C3] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__6F3CF7FC] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__70311C35] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__CPTID__7125406E] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Provi__721964A7] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Physi__730D88E0] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__UnitT__7401AD19] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF_ArchiveServiceLineEncounter_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__75E9F58B] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__76DE19C4] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__77D23DFD] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__78C66236] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__79BA866F] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7AAEAAA8] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7BA2CEE1] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7C96F31A] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7D8B1753] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7E7F3B8C] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7F735FC5] DEFAULT ((0)) FOR [SampledBudget11]; GO

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

---------------------------------------------
-- fp.ArchiveFactServiceLineEncounterBasis ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactServiceLineEncounterBasis] (
    [RowID] int NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ActualEncounters] decimal NOT NULL,
    [YTDEncounters] decimal NOT NULL,
    [BaseEncounters] decimal NOT NULL,
    [ValueMonth01] decimal NOT NULL,
    [ValueMonth02] decimal NOT NULL,
    [ValueMonth03] decimal NOT NULL,
    [ValueMonth04] decimal NOT NULL,
    [ValueMonth05] decimal NOT NULL,
    [ValueMonth06] decimal NOT NULL,
    [ValueMonth07] decimal NOT NULL,
    [ValueMonth08] decimal NOT NULL,
    [ValueMonth09] decimal NOT NULL,
    [ValueMonth10] decimal NOT NULL,
    [ValueMonth11] decimal NOT NULL,
    [ValueMonth12] decimal NOT NULL,
    [ValueAnnualOriginal] decimal NOT NULL,
    [ChangeHistoryGUID] uniqueidentifier NOT NULL,
    [ServiceLineCasesTotal] decimal NULL
);
GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimAgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimEntity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimMedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimPatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth07] DEFAULT ((0)) FOR [ValueMonth07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth08] DEFAULT ((0)) FOR [ValueMonth08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth09] DEFAULT ((0)) FOR [ValueMonth09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth10] DEFAULT ((0)) FOR [ValueMonth10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth11] DEFAULT ((0)) FOR [ValueMonth11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth12] DEFAULT ((0)) FOR [ValueMonth12]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueAnnualOriginal] DEFAULT ((0)) FOR [ValueAnnualOriginal]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ChangeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGUID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_BudgetConfigID] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_EntityID] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_PatientClassID] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ServiceLineID] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_AgeCohortID] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_MedicalSurgicalID] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ActualEncounters] DEFAULT ((0)) FOR [ActualEncounters]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_YTDEncounters] DEFAULT ((0)) FOR [YTDEncounters]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_BaseEncounters] DEFAULT ((0)) FOR [BaseEncounters]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth01] DEFAULT ((0)) FOR [ValueMonth01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth02] DEFAULT ((0)) FOR [ValueMonth02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth03] DEFAULT ((0)) FOR [ValueMonth03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth04] DEFAULT ((0)) FOR [ValueMonth04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth05] DEFAULT ((0)) FOR [ValueMonth05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth06] DEFAULT ((0)) FOR [ValueMonth06]; GO

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

---------------------------------------------
-- fp.ArchiveFactServiceLineEncounterBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactServiceLineEncounterBudget] (
    [RowID] int NOT NULL,
    [ServiceLineEncounterID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterBudget] ON [fp].[ArchiveFactServiceLineEncounterBudget] ([ServiceLineEncounterID], [BudgetPhaseID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterBudget_BudgetPhaseID] ON [fp].[ArchiveFactServiceLineEncounterBudget] ([BudgetPhaseID], [ServiceLineEncounterID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounterBudget] ([ServiceLineEncounterID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBudget_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Servi__33E72804] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__34DB4C3D] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__35CF7076] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__36C394AF] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__37B7B8E8] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__38ABDD21] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__39A0015A] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3A942593] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3B8849CC] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3C7C6E05] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3D70923E] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3E64B677] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3F58DAB0] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__404CFEE9] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__41412322] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4235475B] DEFAULT ((0)) FOR [AdjustedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactServiceLineEncounterHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactServiceLineEncounterHistory] (
    [RowID] int NOT NULL,
    [ServiceLineEncounterID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterHistory] ON [fp].[ArchiveFactServiceLineEncounterHistory] ([ServiceLineEncounterID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounterHistory] ([ServiceLineEncounterID]);
GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterHistory_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Servi__5824887A] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5918ACB3] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5A0CD0EC] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5B00F525] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5BF5195E] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5CE93D97] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5DDD61D0] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5ED18609] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5FC5AA42] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__60B9CE7B] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__61ADF2B4] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__62A216ED] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__63963B26] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__648A5F5F] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__657E8398] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6672A7D1] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6766CC0A] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__685AF043] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__694F147C] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6A4338B5] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6B375CEE] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6C2B8127] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6D1FA560] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6E13C999] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6F07EDD2] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6FFC120B] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__70F03644] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__71E45A7D] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__72D87EB6] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__73CCA2EF] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__74C0C728] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__75B4EB61] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__76A90F9A] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__779D33D3] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7891580C] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__79857C45] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7A79A07E] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.ArchiveFactServiceLineEncounterProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactServiceLineEncounterProjection] (
    [RowID] int NOT NULL,
    [ServiceLineEncounterID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterProjection] ON [fp].[ArchiveFactServiceLineEncounterProjection] ([ServiceLineEncounterID], [BudgetPhaseID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterProjection_BudgetPhaseID] ON [fp].[ArchiveFactServiceLineEncounterProjection] ([BudgetPhaseID], [ServiceLineEncounterID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounterProjection] ([ServiceLineEncounterID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterProjection_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Servi__4605D83F] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__46F9FC78] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__47EE20B1] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__48E244EA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__49D66923] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4ACA8D5C] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4BBEB195] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4CB2D5CE] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4DA6FA07] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4E9B1E40] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4F8F4279] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__508366B2] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__51778AEB] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__526BAF24] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__535FD35D] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5453F796] DEFAULT ((0)) FOR [AdjustedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactStaffing ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStaffing] (
    [StaffingID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [SubSectionID] int NOT NULL,
    PRIMARY KEY ([StaffingID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactStaffing] ON [fp].[ArchiveFactStaffing] ([StaffingID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_BudgetConfig] ON [fp].[ArchiveFactStaffing] ([BudgetConfigID]) INCLUDE ([StaffingID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_Department] ON [fp].[ArchiveFactStaffing] ([DepartmentID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_Entity] ON [fp].[ArchiveFactStaffing] ([EntityID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_EntityGroupConfig] ON [fp].[ArchiveFactStaffing] ([EntityGroupConfigID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_JobCode] ON [fp].[ArchiveFactStaffing] ([JobCodeID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_PayCodeGroup] ON [fp].[ArchiveFactStaffing] ([PayCodeGroupID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [ProductiveClassID], [VariabilityID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_ProductiveClass] ON [fp].[ArchiveFactStaffing] ([ProductiveClassID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [UnitTypeID]);
GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__225F0B54] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__23532F8D] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__244753C6] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Budge__24FF47C6] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__253B77FF] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Entit__25F36BFF] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__SubSe__262F9C38] DEFAULT ((0)) FOR [SubSectionID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Entit__26E79038] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Depar__27DBB471] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__JobCo__28CFD8AA] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__PayCo__29C3FCE3] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Produ__2AB8211C] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Varia__2BAC4555] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__UnitT__2CA0698E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__AddDa__2D948DC7] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2E88B200] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2F7CD639] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3070FA72] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__31651EAB] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__325942E4] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__334D671D] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__34418B56] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3535AF8F] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3629D3C8] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__371DF801] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__38121C3A] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__39064073] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__39FA64AC] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3AEE88E5] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3BE2AD1E] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3CD6D157] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3DCAF590] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3EBF19C9] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3FB33E02] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__40A7623B] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__419B8674] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__428FAAAD] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__4383CEE6] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__4477F31F] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__456C1758] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__46603B91] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__47545FCA] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__48488403] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__493CA83C] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4A30CC75] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4B24F0AE] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4C1914E7] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4D0D3920] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4E015D59] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4EF58192] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4FE9A5CB] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__50DDCA04] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__51D1EE3D] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__52C61276] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__53BA36AF] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__54AE5AE8] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__55A27F21] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__5696A35A] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__578AC793] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__587EEBCC] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__59731005] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__5A67343E] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__5B5B5877] DEFAULT ((0)) FOR [InitialProjection12]; GO

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

---------------------------------------------
-- fp.ArchiveFactStaffingBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStaffingBudget] (
    [RowID] int NOT NULL,
    [StaffingID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NOT NULL,
    [PercentAdjustmentFactor01] decimal NOT NULL,
    [PercentAdjustmentFactor02] decimal NOT NULL,
    [PercentAdjustmentFactor03] decimal NOT NULL,
    [PercentAdjustmentFactor04] decimal NOT NULL,
    [PercentAdjustmentFactor05] decimal NOT NULL,
    [PercentAdjustmentFactor06] decimal NOT NULL,
    [PercentAdjustmentFactor07] decimal NOT NULL,
    [PercentAdjustmentFactor08] decimal NOT NULL,
    [PercentAdjustmentFactor09] decimal NOT NULL,
    [PercentAdjustmentFactor10] decimal NOT NULL,
    [PercentAdjustmentFactor11] decimal NOT NULL,
    [PercentAdjustmentFactor12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactStaffingBudget] ON [fp].[ArchiveFactStaffingBudget] ([StaffingID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [FK_ArchiveFactStaffingBudget_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__008CDD26] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__0181015F] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__02752598] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__036949D1] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Staff__5E37C522] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__5F2BE95B] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__60200D94] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__611431CD] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__62085606] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__62FC7A3F] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__63F09E78] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__64E4C2B1] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__65D8E6EA] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__66CD0B23] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67C12F5C] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__68B55395] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__69A977CE] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6A9D9C07] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6B91C040] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6C85E479] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6D7A08B2] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6E6E2CEB] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6F625124] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7056755D] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__714A9996] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__723EBDCF] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7332E208] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__74270641] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__751B2A7A] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__760F4EB3] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__770372EC] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__77F79725] DEFAULT ((0)) FOR [FlexedValue12]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__78EBBB5E] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__79DFDF97] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7AD403D0] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7BC82809] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7CBC4C42] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7DB0707B] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7EA494B4] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7F98B8ED] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO

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

---------------------------------------------
-- fp.ArchiveFactStaffingHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStaffingHistory] (
    [RowID] int NOT NULL,
    [StaffingID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [FK_ArchiveFactStaffingHistory_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Staff__2A8ECF41] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2B82F37A] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2C7717B3] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2D6B3BEC] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2E5F6025] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2F53845E] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3047A897] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__313BCCD0] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__322FF109] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__33241542] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3418397B] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__350C5DB4] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__360081ED] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__36F4A626] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__37E8CA5F] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__38DCEE98] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__39D112D1] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3AC5370A] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3BB95B43] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3CAD7F7C] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3DA1A3B5] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3E95C7EE] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3F89EC27] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__407E1060] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__41723499] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__426658D2] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__435A7D0B] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__444EA144] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4542C57D] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4636E9B6] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__472B0DEF] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__481F3228] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__49135661] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4A077A9A] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4AFB9ED3] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4BEFC30C] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4CE3E745] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.ArchiveFactStaffingHistoryFTETotals ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] (
    [RowID] int NOT NULL,
    [StaffingID] int NOT NULL,
    [PriorYearActualTotal] decimal NOT NULL,
    [ActualYTDTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactStaffingHistoryFTETotals] ON [fp].[ArchiveFactStaffingHistoryFTETotals] ([StaffingID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactStaffingHistoryFTETotals] ([StaffingID]);
GO
ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Staff__16EC8D51] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Prior__17E0B18A] DEFAULT ((0)) FOR [PriorYearActualTotal]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Actua__18D4D5C3] DEFAULT ((0)) FOR [ActualYTDTotal]; GO
ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Curre__19C8F9FC] DEFAULT ((0)) FOR [CurrentYearBudgetTotal]; GO

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

---------------------------------------------
-- fp.ArchiveFactStaffingProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStaffingProjection] (
    [RowID] int NOT NULL,
    [StaffingID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NOT NULL,
    [PercentAdjustmentFactor01] decimal NOT NULL,
    [PercentAdjustmentFactor02] decimal NOT NULL,
    [PercentAdjustmentFactor03] decimal NOT NULL,
    [PercentAdjustmentFactor04] decimal NOT NULL,
    [PercentAdjustmentFactor05] decimal NOT NULL,
    [PercentAdjustmentFactor06] decimal NOT NULL,
    [PercentAdjustmentFactor07] decimal NOT NULL,
    [PercentAdjustmentFactor08] decimal NOT NULL,
    [PercentAdjustmentFactor09] decimal NOT NULL,
    [PercentAdjustmentFactor10] decimal NOT NULL,
    [PercentAdjustmentFactor11] decimal NOT NULL,
    [PercentAdjustmentFactor12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactStaffingProjection] ON [fp].[ArchiveFactStaffingProjection] ([StaffingID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [FK_ArchiveFactStaffingProjection_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Staff__0739DAB5] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__082DFEEE] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__09222327] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__0A164760] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B0A6B99] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0BFE8FD2] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0CF2B40B] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0DE6D844] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0EDAFC7D] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0FCF20B6] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__10C344EF] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__11B76928] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12AB8D61] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__139FB19A] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1493D5D3] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1587FA0C] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__167C1E45] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1770427E] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__186466B7] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__19588AF0] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1A4CAF29] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1B40D362] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1C34F79B] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1D291BD4] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1E1D400D] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1F116446] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2005887F] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__20F9ACB8] DEFAULT ((0)) FOR [FlexedValue12]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__21EDD0F1] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__22E1F52A] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__23D61963] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__24CA3D9C] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__25BE61D5] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__26B2860E] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__27A6AA47] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__289ACE80] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__298EF2B9] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2A8316F2] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2B773B2B] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2C6B5F64] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO

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

---------------------------------------------
-- fp.ArchiveFactStatistics ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStatistics] (
    [StatisticsID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [SampledProjectionTotal] decimal NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetTotal] decimal NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialProjectionTotal] decimal NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [SubSectionID] int NOT NULL,
    PRIMARY KEY ([StatisticsID])
);

CREATE CLUSTERED INDEX [IX_ArchiveFactStatistics] ON [fp].[ArchiveFactStatistics] ([StatisticsID]);
GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0037D76B] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__012BFBA4] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__02201FDD] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__03144416] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0408684F] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__04FC8C88] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__05F0B0C1] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__06E4D4FA] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__07D8F933] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__08CD1D6C] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__09C141A5] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0AB565DE] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0BA98A17] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__1D9A5637] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__1E8E7A70] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__1F829EA9] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__2076C2E2] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__SubSe__216AE71B] DEFAULT ((0)) FOR [SubSectionID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Budge__554D7966] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Entit__56419D9F] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Entit__5735C1D8] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Depar__5829E611] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Accou__591E0A4A] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Finan__5A122E83] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Payor__5B0652BC] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Patie__5BFA76F5] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__UnitT__5CEE9B2E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__AddDa__5DE2BF67] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5ED6E3A0] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5FCB07D9] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__60BF2C12] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__61B3504B] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__62A77484] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__639B98BD] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__648FBCF6] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6583E12F] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__66780568] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__676C29A1] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__68604DDA] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__69547213] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6A48964C] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6B3CBA85] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6C30DEBE] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6D2502F7] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6E192730] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6F0D4B69] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__70016FA2] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__70F593DB] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__71E9B814] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__72DDDC4D] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__73D20086] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__74C624BF] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__75BA48F8] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__76AE6D31] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__77A2916A] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7896B5A3] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__798AD9DC] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7A7EFE15] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7B73224E] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7C674687] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7D5B6AC0] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7E4F8EF9] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7F43B332] DEFAULT ((0)) FOR [InitialBudget11]; GO

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

---------------------------------------------
-- fp.ArchiveFactStatisticsBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStatisticsBudget] (
    [RowID] int NOT NULL,
    [StatisticsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [FK_ArchiveFactStatisticsBudget_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Stati__0E85F6C2] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__0F7A1AFB] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__106E3F34] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__1162636D] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__125687A6] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__134AABDF] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__143ED018] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1532F451] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1627188A] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__171B3CC3] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__180F60FC] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19038535] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19F7A96E] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1AEBCDA7] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1BDFF1E0] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1CD41619] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1DC83A52] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1EBC5E8B] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1FB082C4] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__20A4A6FD] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2198CB36] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__228CEF6F] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__238113A8] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__247537E1] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__25695C1A] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__265D8053] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2751A48C] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2845C8C5] DEFAULT ((0)) FOR [FlexedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveFactStatisticsHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStatisticsHistory] (
    [RowID] int NOT NULL,
    [StatisticsID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [FK_ArchiveFactStatisticsHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Stati__50B47829] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__51A89C62] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__529CC09B] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5390E4D4] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5485090D] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__55792D46] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__566D517F] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__576175B8] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__585599F1] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5949BE2A] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5A3DE263] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5B32069C] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5C262AD5] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5D1A4F0E] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5E0E7347] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5F029780] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5FF6BBB9] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__60EADFF2] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__61DF042B] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__62D32864] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__63C74C9D] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__64BB70D6] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__65AF950F] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__66A3B948] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6797DD81] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__688C01BA] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__698025F3] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6A744A2C] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6B686E65] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6C5C929E] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6D50B6D7] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6E44DB10] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6F38FF49] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__702D2382] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__712147BB] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__72156BF4] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7309902D] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.ArchiveFactStatisticsProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveFactStatisticsProjection] (
    [RowID] int NOT NULL,
    [StatisticsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [FK_ArchiveFactStatisticsProjection_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Stati__2B223570] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__2C1659A9] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__2D0A7DE2] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__2DFEA21B] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2EF2C654] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2FE6EA8D] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__30DB0EC6] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__31CF32FF] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__32C35738] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__33B77B71] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__34AB9FAA] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__359FC3E3] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3693E81C] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__37880C55] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__387C308E] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__397054C7] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3A647900] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3B589D39] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3C4CC172] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3D40E5AB] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3E3509E4] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3F292E1D] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__401D5256] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4111768F] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__42059AC8] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__42F9BF01] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__43EDE33A] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__44E20773] DEFAULT ((0)) FOR [FlexedValue12]; GO

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

---------------------------------------------
-- fp.ArchiveGeneralLedgerChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveGeneralLedgerChangeHistory] (
    [RowID] bigint NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [SortOrder] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [FK_ArchiveGeneralLedgerChangeHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Gener__2C420D89] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Adjus__2D3631C2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Group__2E2A55FB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Adjus__2F1E7A34] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__SortO__30129E6D] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Fisca__3106C2A6] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__UnitT__31FAE6DF] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__TimeC__32EF0B18] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Budge__33E32F51] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__OldVa__34D7538A] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__NewVa__35CB77C3] DEFAULT ((0)) FOR [NewValue]; GO

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

---------------------------------------------
-- fp.ArchiveServiceLineEncounterChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] (
    [RowID] bigint NOT NULL,
    [ServiceLineEncounterID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [SortOrder] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ArchiveServiceLineEncounterChangeHistory] ON [fp].[ArchiveServiceLineEncounterChangeHistory] ([ServiceLineEncounterID]);
CREATE NONCLUSTERED INDEX [IX_ArchiveServiceLineEncounterChangeHistory_AdjustmentGuid] ON [fp].[ArchiveServiceLineEncounterChangeHistory] ([AdjustmentGUID]) INCLUDE ([ServiceLineEncounterID], [SortOrder], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [FK_ArchiveServiceLineEncounterChangeHistory_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Servi__0BA42C80] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Adjus__0C9850B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Group__0D8C74F2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Adjus__0E80992B] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__SortO__0F74BD64] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Fisca__1068E19D] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__UnitT__115D05D6] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__TimeC__12512A0F] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Budge__13454E48] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__OldVa__14397281] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__NewVa__152D96BA] DEFAULT ((0)) FOR [NewValue]; GO

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

---------------------------------------------
-- fp.ArchiveStaffingChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveStaffingChangeHistory] (
    [RowID] bigint NOT NULL,
    [StaffingID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [SortOrder] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [FK_ArchiveStaffingChangeHistory_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Staff__38A7E46E] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__399C08A7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Group__3A902CE0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__3B845119] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__SortO__3C787552] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Fisca__3D6C998B] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__UnitT__3E60BDC4] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__TimeC__3F54E1FD] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Budge__40490636] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__OldVa__413D2A6F] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__NewVa__42314EA8] DEFAULT ((0)) FOR [NewValue]; GO

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

---------------------------------------------
-- fp.ArchiveStatisticsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ArchiveStatisticsChangeHistory] (
    [RowID] bigint NOT NULL,
    [StatisticsID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [SortOrder] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [FK_ArchiveStatisticsChangeHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Stati__450DBB53] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__4601DF8C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Group__46F603C5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__47EA27FE] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__SortO__48DE4C37] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Fisca__49D27070] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__UnitT__4AC694A9] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__TimeC__4BBAB8E2] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Budge__4CAEDD1B] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__OldVa__4DA30154] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__NewVa__4E97258D] DEFAULT ((0)) FOR [NewValue]; GO

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

---------------------------------------------
-- fp.BenefitsAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[BenefitsAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [AdjustmentID] int NOT NULL,
    [IsErrored] bit NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [FK__BenefitsA__Budge__3B5DFAD0] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__15DFFB59] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__16D41F92] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Value__17C843CB] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__18BC6804] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Group__19B08C3D] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__1AA4B076] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Comme__1B98D4AF] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Autho__1C8CF8E8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Autho__1D811D21] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Group__6F503E1D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__UnitTypeID] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__IsErr__4BED92D1] DEFAULT ((0)) FOR [IsErrored]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__Dimen__64D60ED0] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__DateC__6634475D] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__LastM__67286B96] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__IsRec__6CCB6AFC] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO

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

---------------------------------------------
-- fp.BenefitsAdjustmentImport ------------------
---------------------------------------------
CREATE TABLE [fp].[BenefitsAdjustmentImport] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [EntityID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [Version] timestamp NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [AdjustmentID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[BenefitsAdjustmentImport] ([AdjustmentID]);
GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__Adjus__22BE32B0] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__Adjus__3B7DF661] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__AccountID__2D57C830] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__FinancialReportingID__2D57C830] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF_INTBenefitsAdjImport_VALUE] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__Entit__431F1829] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF_BenefitsAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__IsRec__71902019] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.BenefitsAdjustment_backup ------------------
---------------------------------------------
CREATE TABLE [fp].[BenefitsAdjustment_backup] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [FK__BenefitsA__Budge__4D7CAB0B] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__4E70CF44] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__4F64F37D] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Value__505917B6] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__514D3BEF] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Group__52416028] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__53358461] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Comme__5429A89A] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Autho__551DCCD3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Autho__5611F10C] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__LastM__57061545] DEFAULT (getdate()) FOR [LastModifiedDate]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__DateC__57FA397E] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Group__58EE5DB7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__UnitT__59E281F0] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF_BenefitsAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

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

---------------------------------------------
-- fp.BenefitsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[BenefitsChangeHistory] (
    [RowID] bigint NOT NULL,
    [BenefitsID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_BenefitsChangeHistory] ON [fp].[BenefitsChangeHistory] ([BenefitsID]);
GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [FK_BenefitsChangeHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__DateC__05C2014F] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Group__07F2CBD6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Benef__40B24F33] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Adjus__41A6736C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Adjus__429A97A5] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Fisca__4482E017] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__UnitT__45770450] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__TimeC__466B2889] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Budge__475F4CC2] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__OldVa__485370FB] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__NewVa__49479534] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Budge__60FA90F4] DEFAULT ((0)) FOR [BudgetConfigID]; GO

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

---------------------------------------------
-- fp.BenefitsSpreadUnlockData ------------------
---------------------------------------------
CREATE TABLE [fp].[BenefitsSpreadUnlockData] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [Version] timestamp NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Budge__2E0E531D] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Entit__2FF69B8F] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Depar__30EABFC8] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Accou__31DEE401] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Finan__32D3083A] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__33C72C73] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__34BB50AC] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__35AF74E5] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__36A3991E] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3797BD57] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__388BE190] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__398005C9] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3A742A02] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3B684E3B] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3C5C7274] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3D5096AD] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3E44BAE6] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [df_BenefitsSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__IsRec__7FDE3F70] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.BenefitsSpreads ------------------
---------------------------------------------
CREATE TABLE [fp].[BenefitsSpreads] (
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [IsInactive] bit NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [GlobalSpreadID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [DepartmentID], [AccountID])
);
GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [FK_FpBenefitsSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [df_BenefitsSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Budge__36D8A348] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Depar__37CCC781] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Accou__38C0EBBA] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__IsIna__39B50FF3] DEFAULT ((0)) FOR [IsInactive]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3AA9342C] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3B9D5865] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3C917C9E] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3D85A0D7] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3E79C510] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3F6DE949] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__40620D82] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__415631BB] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__424A55F4] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__433E7A2D] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__44329E66] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__4526C29F] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Total__461AE6D8] DEFAULT ((0)) FOR [TotalImportedValue]; GO
ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Globa__48032F4A] DEFAULT ((1)) FOR [GlobalSpreadID]; GO

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

---------------------------------------------
-- fp.BudgetAction ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetAction] (
    [ActionID] int NOT NULL,
    [Name] nvarchar(max) NOT NULL,
    [IsActive] bit NOT NULL,
    [IsConfigurationAction] bit NOT NULL,
    [IsReportAction] bit NOT NULL,
    PRIMARY KEY ([ActionID])
);
GO
ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__Actio__68A901B9] DEFAULT ((0)) FOR [ActionID]; GO
ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetActi__Name__699D25F2] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__IsAct__6A914A2B] DEFAULT ((1)) FOR [IsActive]; GO
ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__IsCon__6B856E64] DEFAULT ((0)) FOR [IsConfigurationAction]; GO
ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__IsRep__6C79929D] DEFAULT ((0)) FOR [IsReportAction]; GO

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

---------------------------------------------
-- fp.BudgetConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetConfig] (
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [ChargeMasterConfigJson] varchar(max) NOT NULL,
    [DateModified] smalldatetime NOT NULL,
    [DatePublished] smalldatetime NOT NULL,
    [BudgetConfigName] nvarchar(100) NOT NULL,
    [IsActive] bit NOT NULL,
    [Comments] nvarchar(2000) NOT NULL,
    [IsOverUnderFundedUsed] bit NOT NULL,
    [IsFTEHidden] bit NOT NULL,
    [IsProjectionHidden] bit NOT NULL,
    [IsArchived] bit NOT NULL,
    [IsProjectCurrentYear] bit NOT NULL,
    [IsMRTracking] bit NOT NULL,
    [ParentBudgetConfigID] smallint NOT NULL,
    [MonthsLoaded] tinyint NOT NULL,
    [CurrentBudgetPhaseID] tinyint NOT NULL,
    [AdjustmentClassificationSetting] tinyint NOT NULL,
    [IsEngineDisabled] bit NOT NULL,
    [UseDSForSampling] bit NOT NULL,
    [IsGLBudgetHistoryAvailable] bit NOT NULL,
    [IsStaffingBudgetHistoryAvailable] bit NOT NULL,
    [IsTempoNonStaffingPageAvailable] bit NOT NULL,
    [IsAdjustmentClassificationEnabled] bit NOT NULL,
    [IsRestrictDepartmentAccess] bit NOT NULL,
    [IsChargeMasterRefreshedForDollarImpactReport] bit NOT NULL,
    [DefaultReimbursementProjectionMethodID] int NOT NULL,
    [IsProviderVolumesEnabled] bit NOT NULL,
    [IsTempoOtherRevenuePageAvailable] bit NOT NULL,
    [UseEmployeePlanning] bit NOT NULL,
    [IsUsingSystemGeneratedHistoricalStats] bit NOT NULL,
    [IsSubAccountCategoriesEnabled] bit NOT NULL,
    [AreStatisticsAccountsEnabled] bit NOT NULL,
    [IsProviderCompensationEnabled] bit NOT NULL,
    [DisplayCategoryInMyBudgets] bit NOT NULL,
    [IsLocalAdminReadOnly] bit NOT NULL,
    [IsTargetingEmailEnabled] bit NOT NULL,
    [AllowLocalAdminAddEmpAddFTEPlanEditor] bit NOT NULL,
    [AllowLocalAdminAddEmpAddJobCodeMyBudgets] bit NOT NULL,
    [AllowLocalAdminAddAccountPlanEditor] bit NOT NULL,
    [AllowLocalAdminAddAccountMyBudgets] bit NOT NULL,
    [IsBudgetClosed] bit NOT NULL,
    [IsStatisticsBudgetHistoryAvailable] bit NOT NULL,
    [IsImpactReportsEnabled] bit NOT NULL,
    [DefaultReimbursementNetRevenueModelID] int NOT NULL,
    [IsProviderPlanningEnabled] bit NOT NULL,
    [IsUsedForReportComparison] bit NOT NULL,
    [UseProviderSource] bit NOT NULL,
    [IsProjectionLockedOnMyBudget] bit NOT NULL,
    [IsBudgetLockedOnMyBudget] bit NOT NULL,
    [EnableExceptionActionItems] bit NOT NULL,
    [IsWorkWeekOverrideCheckIgnored] bit NOT NULL,
    PRIMARY KEY ([BudgetConfigGUID])
);

CREATE NONCLUSTERED INDEX [NCNU_BudgetConfig_BudgetConfigID] ON [fp].[BudgetConfig] ([BudgetConfigID]);
CREATE NONCLUSTERED INDEX [NCNU_BudgetConfig_FiscalYearID] ON [fp].[BudgetConfig] ([FiscalYearID]);
GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsMRT__07C7E34D] DEFAULT ((0)) FOR [IsMRTracking]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsUsingSystemGeneratedHistoricalStats] DEFAULT ((0)) FOR [IsUsingSystemGeneratedHistoricalStats]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Paren__08BC0786] DEFAULT ((0)) FOR [ParentBudgetConfigID]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Budge__09245362] DEFAULT (newid()) FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Fisca__0A18779B] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_IsAdjustmentClassificationEnabled] DEFAULT ((0)) FOR [IsAdjustmentClassificationEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfigComment] DEFAULT ('') FOR [Comments]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsPro__0FB02246] DEFAULT ((0)) FOR [IsProviderPlanningEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__100DB2F4] DEFAULT ((1)) FOR [AllowLocalAdminAddEmpAddFTEPlanEditor]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_IsRestrictDepartmentAccess] DEFAULT ((1)) FOR [IsRestrictDepartmentAccess]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSta__13C79E91] DEFAULT ((0)) FOR [IsProviderVolumesEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Defau__1F918454] DEFAULT ((0)) FOR [DefaultReimbursementNetRevenueModelID]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__DateM__1F9F3B14] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__DateP__20935F4D] DEFAULT (getdate()) FOR [DatePublished]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsGLB__20F51A78] DEFAULT ((1)) FOR [IsGLBudgetHistoryAvailable]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Budge__21878386] DEFAULT ('Default Budget') FOR [BudgetConfigName]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSta__21E93EB1] DEFAULT ((1)) FOR [IsStaffingBudgetHistoryAvailable]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsAct__227BA7BF] DEFAULT ((0)) FOR [IsActive]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Adjus__2563FE83] DEFAULT ((0)) FOR [AdjustmentClassificationSetting]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsBud__26A6FF89] DEFAULT ((0)) FOR [IsBudgetClosed]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Charg__2967D119] DEFAULT ('') FOR [ChargeMasterConfigJson]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSub__2B6AE94F] DEFAULT ((0)) FOR [IsSubAccountCategoriesEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsFTE__2B9BC8FC] DEFAULT ((0)) FOR [IsFTEHidden]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsPro__2C8FED35] DEFAULT ((0)) FOR [IsProjectionHidden]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsUse__334FFAEC] DEFAULT ((0)) FOR [IsUsedForReportComparison]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsProjectCurrentYear] DEFAULT ((0)) FOR [IsProjectCurrentYear]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsPro__3A55F6E9] DEFAULT ((0)) FOR [IsProjectionLockedOnMyBudget]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsBud__3B4A1B22] DEFAULT ((0)) FOR [IsBudgetLockedOnMyBudget]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__3CE0596B] DEFAULT ((1)) FOR [AllowLocalAdminAddEmpAddJobCodeMyBudgets]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSta__46DEC4F1] DEFAULT ((0)) FOR [IsStatisticsBudgetHistoryAvailable]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Defau__47274706] DEFAULT ((1)) FOR [DefaultReimbursementProjectionMethodID]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsTem__49B99AEE] DEFAULT ((0)) FOR [IsTempoOtherRevenuePageAvailable]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__UseDS__4D08A6E0] DEFAULT ((0)) FOR [UseDSForSampling]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__UsePr__4DB2E420] DEFAULT ((0)) FOR [UseProviderSource]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__UseEm__55962D45] DEFAULT ((0)) FOR [UseEmployeePlanning]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsTem__561EA67C] DEFAULT ((0)) FOR [IsTempoNonStaffingPageAvailable]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsCha__5826EA7F] DEFAULT ((1)) FOR [IsChargeMasterRefreshedForDollarImpactReport]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Enabl__5DF50438] DEFAULT ((0)) FOR [EnableExceptionActionItems]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Curre__5FDAB8DB] DEFAULT ((2)) FOR [CurrentBudgetPhaseID]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Month__64699877] DEFAULT ((0)) FOR [MonthsLoaded]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsOve__693908C2] DEFAULT ((1)) FOR [IsOverUnderFundedUsed]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsArchived] DEFAULT ((0)) FOR [IsArchived]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_AreStatisticsAccountsEnabled] DEFAULT ((0)) FOR [AreStatisticsAccountsEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__724845E3] DEFAULT ((1)) FOR [AllowLocalAdminAddAccountPlanEditor]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__733C6A1C] DEFAULT ((1)) FOR [AllowLocalAdminAddAccountMyBudgets]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsImp__74C58B32] DEFAULT ((0)) FOR [IsImpactReportsEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsTar__7559BCB8] DEFAULT ((1)) FOR [IsTargetingEmailEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsEng__773E0C77] DEFAULT ((0)) FOR [IsEngineDisabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsLocalAdminReadOnly] DEFAULT ((0)) FOR [IsLocalAdminReadOnly]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsProviderCompensationEnabled] DEFAULT ((0)) FOR [IsProviderCompensationEnabled]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsWor__7C798B58] DEFAULT ((0)) FOR [IsWorkWeekOverrideCheckIgnored]; GO
ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_DisplayCategoryInMyBudgets] DEFAULT ((0)) FOR [DisplayCategoryInMyBudgets]; GO

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

---------------------------------------------
-- fp.BudgetConfigDefaultHoursMix ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetConfigDefaultHoursMix] (
    [BudgetConfigHoursMixGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [HoursMix] decimal NOT NULL,
    PRIMARY KEY ([BudgetConfigHoursMixGUID])
);
GO
ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [FK__BudgetCon__Budge__774665A0] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [FK__BudgetCon__PayCo__783A89D9] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [DF__BudgetCon__Hours__35439819] DEFAULT ((0)) FOR [HoursMix]; GO
ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [DF__BudgetCon__Budge__76524167] DEFAULT (newid()) FOR [BudgetConfigHoursMixGUID]; GO

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

---------------------------------------------
-- fp.BudgetConfigDefaultSetting ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetConfigDefaultSetting] (
    [SettingID] int NOT NULL,
    [Name] nvarchar(max) NOT NULL,
    [Description] nvarchar(max) NOT NULL,
    [DefaultValue] bit NOT NULL,
    [DateCreated] date NOT NULL,
    PRIMARY KEY ([SettingID])
);
GO
ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetCon__DateC__027F7903] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetConf__Name__3626D836] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetCon__Descr__371AFC6F] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetCon__Defau__380F20A8] DEFAULT ((1)) FOR [DefaultValue]; GO

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

---------------------------------------------
-- fp.BudgetConfigSetting ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetConfigSetting] (
    [BudgetConfigID] int NOT NULL,
    [SettingID] int NOT NULL,
    [Value] bit NOT NULL
);
GO
ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [FK__BudgetCon__Setti__3CD3D5C5] FOREIGN KEY ([SettingID]) REFERENCES [fp].[BudgetConfigDefaultSetting] ([SettingID]); GO
ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [DF__BudgetCon__Budge__39F7691A] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [DF__BudgetCon__Setti__3AEB8D53] DEFAULT ((0)) FOR [SettingID]; GO
ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [DF__BudgetCon__Value__3BDFB18C] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.BudgetRefreshRequest ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetRefreshRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [UserName] nvarchar(64) NOT NULL,
    [SourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [DateStarted] datetime NOT NULL,
    [DateEnded] datetime NOT NULL,
    [Status] tinyint NOT NULL,
    [ErrorMessage] nvarchar(max) NOT NULL,
    [StackTrace] nvarchar(max) NOT NULL,
    [CurrentDataRefreshMethod] nvarchar(max) NOT NULL,
    [SourceActionID] smallint NOT NULL,
    [AffectedDepartments] nvarchar(max) NOT NULL,
    [IsIgnoreTargetingError] bit NOT NULL,
    [Source] nvarchar(100) NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [SamplingJSON] nvarchar(max) NOT NULL,
    [EmailAddress] nvarchar(2000) NOT NULL,
    [InitialSamplingJSON] nvarchar(max) NOT NULL,
    [InitialSourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [DateTimeStampUTC] datetime NOT NULL,
    [DateStartedUTC] datetime NOT NULL,
    [DateEndedUTC] datetime NOT NULL,
    [PlanSectionID] int NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateT__0CFC6DE9] DEFAULT (getutcdate()) FOR [DateTimeStampUTC]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateS__0DF09222] DEFAULT ('1900-01-01T00:00:00') FOR [DateStartedUTC]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Entit__0EC226FB] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateE__0EE4B65B] DEFAULT ('1900-01-01T00:00:00') FOR [DateEndedUTC]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Sampl__0FB64B34] DEFAULT ('') FOR [SamplingJSON]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__PlanS__1CA99124] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Affec__20E896D2] DEFAULT ('') FOR [AffectedDepartments]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Sourc__2A746311] DEFAULT ('') FOR [Source]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateS__33185CF3] DEFAULT ('1900-01-01T00:00:00') FOR [DateStarted]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateE__340C812C] DEFAULT ('1900-01-01T00:00:00') FOR [DateEnded]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Statu__3500A565] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Error__35F4C99E] DEFAULT ('') FOR [ErrorMessage]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Stack__36E8EDD7] DEFAULT ('') FOR [StackTrace]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Curre__37DD1210] DEFAULT ('') FOR [CurrentDataRefreshMethod]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Initi__489C24DA] DEFAULT ('') FOR [InitialSourceDimensionalityJSON]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_BudgetConfigID] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_UserName] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__IsIgn__56F203CD] DEFAULT ((0)) FOR [IsIgnoreTargetingError]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_SourceDimensionalityJSON] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Sourc__602AFA8C] DEFAULT ((0)) FOR [SourceActionID]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Email__6E61DB0F] DEFAULT ('') FOR [EmailAddress]; GO
ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Initi__7425A15D] DEFAULT ('') FOR [InitialSamplingJSON]; GO

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

---------------------------------------------
-- fp.BudgetRefreshRequestHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetRefreshRequestHistory] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [DateTimeStamp] datetime NOT NULL,
    [UserName] nvarchar(64) NOT NULL,
    [SourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [DateStarted] datetime NOT NULL,
    [DateEnded] datetime NOT NULL,
    [Status] tinyint NOT NULL,
    [ErrorMessage] nvarchar(max) NULL,
    [StackTrace] nvarchar(max) NULL,
    [SourceActionID] smallint NOT NULL,
    [AffectedDepartments] nvarchar(max) NOT NULL,
    [CollapsedRequestGUID] uniqueidentifier NOT NULL,
    [IsIgnoreTargetingError] bit NOT NULL,
    [Source] nvarchar(100) NOT NULL,
    [JazzVersion] nvarchar(100) NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [SamplingJSON] nvarchar(max) NOT NULL,
    [InitialSamplingJSON] nvarchar(max) NOT NULL,
    [InitialSourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [CanceledBy] nvarchar(max) NOT NULL,
    [DateTimeStampUTC] datetime NOT NULL,
    [DateStartedUTC] datetime NOT NULL,
    [DateEndedUTC] datetime NOT NULL,
    [AffectedDepartmentCount] int NOT NULL,
    [PlanSectionID] int NOT NULL
);
GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__DateT__0FD8DA94] DEFAULT (getutcdate()) FOR [DateTimeStampUTC]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Entit__10AA6F6D] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__DateS__10CCFECD] DEFAULT ('1900-01-01T00:00:00') FOR [DateStartedUTC]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Sampl__119E93A6] DEFAULT ('') FOR [SamplingJSON]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__DateE__11C12306] DEFAULT ('1900-01-01T00:00:00') FOR [DateEndedUTC]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__PlanS__1D9DB55D] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Affec__22D0DF44] DEFAULT ('') FOR [AffectedDepartments]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Sourc__2B68874A] DEFAULT ('') FOR [Source]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Initi__49904913] DEFAULT ('') FOR [InitialSourceDimensionalityJSON]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__JazzV__4DBD9F4E] DEFAULT ('') FOR [JazzVersion]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Affec__53AEE1F4] DEFAULT ((0)) FOR [AffectedDepartmentCount]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__IsIgn__57E62806] DEFAULT ((0)) FOR [IsIgnoreTargetingError]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Sourc__611F1EC5] DEFAULT ((0)) FOR [SourceActionID]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Cance__6EE294AA] DEFAULT ('') FOR [CanceledBy]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Initi__7519C596] DEFAULT ('') FOR [InitialSamplingJSON]; GO
ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Colla__7D2102FF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CollapsedRequestGUID]; GO

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

---------------------------------------------
-- fp.BudgetSnapshot ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetSnapshot] (
    [SnapshotID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [PlanSectionID] int NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorName] nvarchar(300) NOT NULL,
    [AdjustmentsStampedOff] int NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [DateProcessedUTC] datetime NOT NULL,
    [DateInvalidatedUTC] datetime NOT NULL,
    [IsValid] bit NOT NULL,
    [IsAutoDeleteEnabled] bit NOT NULL,
    [InvalidReason] nvarchar(1000) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [TransactionID] int NOT NULL,
    PRIMARY KEY ([SnapshotID])
);
GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSnap__Name__22626A7A] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Budge__23568EB3] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__PlanS__244AB2EC] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Autho__253ED725] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Autho__2632FB5E] DEFAULT ('') FOR [AuthorName]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Adjus__27271F97] DEFAULT ((0)) FOR [AdjustmentsStampedOff]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Comme__281B43D0] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__DateC__290F6809] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__DateP__2A038C42] DEFAULT ('1/1/2000') FOR [DateProcessedUTC]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__DateI__2AF7B07B] DEFAULT ('1/1/2000') FOR [DateInvalidatedUTC]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__IsVal__2BEBD4B4] DEFAULT ((1)) FOR [IsValid]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__IsAut__2CDFF8ED] DEFAULT ((1)) FOR [IsAutoDeleteEnabled]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Inval__2DD41D26] DEFAULT ('') FOR [InvalidReason]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Membe__2EC8415F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Histo__2FBC6598] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Trans__30B089D1] DEFAULT ((0)) FOR [TransactionID]; GO

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

---------------------------------------------
-- fp.BudgetSnapshotSchedule ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetSnapshotSchedule] (
    [BudgetConfigID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [Frequency] int NOT NULL,
    [Recurring] int NOT NULL,
    [StartOn] int NOT NULL,
    [DayOfWeek] int NOT NULL,
    [StartDate] datetime NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorName] nvarchar(300) NOT NULL
);
GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Budge__2F525144] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSnap__Name__3046757D] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Comme__313A99B6] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__DateC__322EBDEF] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Frequ__3322E228] DEFAULT ((0)) FOR [Frequency]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Recur__34170661] DEFAULT ((0)) FOR [Recurring]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Start__350B2A9A] DEFAULT ((0)) FOR [StartOn]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__DayOf__35FF4ED3] DEFAULT ((0)) FOR [DayOfWeek]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Start__36F3730C] DEFAULT (getutcdate()) FOR [StartDate]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Autho__37E79745] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Autho__38DBBB7E] DEFAULT ('') FOR [AuthorName]; GO

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

---------------------------------------------
-- fp.BudgetTimeClassSecurity ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetTimeClassSecurity] (
    [BudgetTimeClassSecurityGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [IsProjectionLocked] bit NOT NULL,
    [IsTargetLocked] bit NOT NULL,
    [IsBudgetLocked] bit NOT NULL,
    [PlanSectionID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    PRIMARY KEY ([BudgetTimeClassSecurityGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UC_BudgetTimeClassSecurity_SectionInfo] ON [fp].[BudgetTimeClassSecurity] ([BudgetConfigGUID], [PlanSectionID], [SubsectionID]);
GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [FK_BudgetTimeClassSecurity_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [FK_SectionId] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [FK_SubsectionId] FOREIGN KEY ([SubsectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF_SectionId] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF_SubsectionId] DEFAULT ((0)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__Budge__32FF8771] DEFAULT (newid()) FOR [BudgetTimeClassSecurityGUID]; GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__IsPro__34E7CFE3] DEFAULT ((0)) FOR [IsProjectionLocked]; GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__IsTar__35DBF41C] DEFAULT ((0)) FOR [IsTargetLocked]; GO
ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__IsBud__36D01855] DEFAULT ((0)) FOR [IsBudgetLocked]; GO

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

---------------------------------------------
-- fp.BudgetedCostPerRVU_Sampled ------------------
---------------------------------------------
CREATE TABLE [fp].[BudgetedCostPerRVU_Sampled] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [CostComponentID] int NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [VariableDirectUnitCostPerRVU] decimal NULL,
    [TotalVariableDirectCost] decimal NULL,
    [TotalCost] decimal NULL,
    [PayCodeID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [VariableDirectCost] decimal NOT NULL,
    [IsImportedFromFile] bit NOT NULL,
    [ChargeCodeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__IsImp__11ABE2A3] DEFAULT ((0)) FOR [IsImportedFromFile]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Depar__48C2178F] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Accou__49B63BC8] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__JobCo__4AAA6001] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__PayCo__4B9E843A] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Fisca__4C92A873] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__CostC__4D86CCAC] DEFAULT ((0)) FOR [CostComponentID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Budge__4E7AF0E5] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__UnitT__4F6F151E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Varia__50633957] DEFAULT ((0)) FOR [VariableDirectUnitCostPerRVU]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Total__51575D90] DEFAULT ((0)) FOR [TotalVariableDirectCost]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Total__524B81C9] DEFAULT ((0)) FOR [TotalCost]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF_BudgetedCostPerRVU_Sampled_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF_BudgetedCostPerRVU_Sampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Varia__7742052A] DEFAULT ((0)) FOR [VariableDirectCost]; GO
ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Charg__75991A4D] DEFAULT ((0)) FOR [ChargeCodeID]; GO

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

---------------------------------------------
-- fp.ChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ChangeHistory] (
    [RowID] int NOT NULL,
    [ChangeHistoryGUID] uniqueidentifier NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [SortOrder] int NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [AdjustedProperty] tinyint NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [IX_ChangeHistory] ON [fp].[ChangeHistory] ([ChangeHistoryGUID]);
CREATE NONCLUSTERED INDEX [NCNU_ChangeHistory] ON [fp].[ChangeHistory] ([AdjustedProperty]) INCLUDE ([ChangeHistoryGUID], [AdjustmentType]);
GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_AdjustmentGUID] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_ChangeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGUID]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_AdjustmentType] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_OldValue] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_NewValue] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_AdjustedProperty] DEFAULT ((0)) FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF__ChangeHis__Group__60489418] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO

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

---------------------------------------------
-- fp.ChargeToGeneralLedgerCrosswalkConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] (
    [RowID] int NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [AccountID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_fp_ChargeToGeneralLedgerCrosswalkConfiguration] ON [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ([EntityGroupConfigID], [DepartmentID]);
CREATE UNIQUE NONCLUSTERED INDEX [CORE_ChargeToGeneralLedgerCrosswalkConfiguration_Unique] ON [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [ChargeCodeID], [PatientClassID], [AccountID], [PayorGroupID]);
GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__IsRec__0D314649] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Budge__58FB1327] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Entit__59EF3760] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Depar__5AE35B99] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Charg__5BD77FD2] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Patie__5CCBA40B] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Payor__5DBFC844] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Accou__5EB3EC7D] DEFAULT ((0)) FOR [AccountID]; GO

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

---------------------------------------------
-- fp.ChargeToStatisticsCrosswalkConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] (
    [EntityGroupConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AccountID] int NOT NULL,
    [RVUWeight] decimal NOT NULL,
    PRIMARY KEY ([EntityGroupConfigID], [DepartmentID], [ChargeCodeID], [PatientClassID], [AccountID])
);
GO
ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Entit__246F0EF3] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Depar__2563332C] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Charg__26575765] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Patie__274B7B9E] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Accou__283F9FD7] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__RVUWe__2933C410] DEFAULT ((0)) FOR [RVUWeight]; GO

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

---------------------------------------------
-- fp.ChargeVolume ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeVolume] (
    [ChargeVolumeID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [VariableDirectUnitCost] decimal NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [BudgetAdjustedTotal] decimal NOT NULL,
    [TargetAdjustedTotal] decimal NOT NULL,
    [ProjectionAdjustedTotal] decimal NOT NULL,
    [InitialBudgetDollarsTotal] decimal NOT NULL,
    [InitialProjectionDollarsTotal] decimal NOT NULL,
    [BudgetDollarsAdjustedTotal] decimal NOT NULL,
    [TargetDollarsAdjustedTotal] decimal NOT NULL,
    [ProjectionDollarsAdjustedTotal] decimal NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter01] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter02] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter03] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter04] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter05] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter06] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter07] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter08] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter09] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter10] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter11] decimal NOT NULL,
    [InitialBudgetUnitsPerEncounter12] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter01] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter02] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter03] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter04] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter05] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter06] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter07] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter08] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter09] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter10] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter11] decimal NOT NULL,
    [InitialProjectionUnitsPerEncounter12] decimal NOT NULL,
    [TargetAdjusted01] decimal NOT NULL,
    [TargetAdjusted02] decimal NOT NULL,
    [TargetAdjusted03] decimal NOT NULL,
    [TargetAdjusted04] decimal NOT NULL,
    [TargetAdjusted05] decimal NOT NULL,
    [TargetAdjusted06] decimal NOT NULL,
    [TargetAdjusted07] decimal NOT NULL,
    [TargetAdjusted08] decimal NOT NULL,
    [TargetAdjusted09] decimal NOT NULL,
    [TargetAdjusted10] decimal NOT NULL,
    [TargetAdjusted11] decimal NOT NULL,
    [TargetAdjusted12] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted01] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted02] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted03] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted04] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted05] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted06] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted07] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted08] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted09] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted10] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted11] decimal NOT NULL,
    [TargetUnitsPerEncounterAdjusted12] decimal NOT NULL,
    [BudgetAdjusted01] decimal NOT NULL,
    [BudgetAdjusted02] decimal NOT NULL,
    [BudgetAdjusted03] decimal NOT NULL,
    [BudgetAdjusted04] decimal NOT NULL,
    [BudgetAdjusted05] decimal NOT NULL,
    [BudgetAdjusted06] decimal NOT NULL,
    [BudgetAdjusted07] decimal NOT NULL,
    [BudgetAdjusted08] decimal NOT NULL,
    [BudgetAdjusted09] decimal NOT NULL,
    [BudgetAdjusted10] decimal NOT NULL,
    [BudgetAdjusted11] decimal NOT NULL,
    [BudgetAdjusted12] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted01] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted02] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted03] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted04] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted05] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted06] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted07] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted08] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted09] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted10] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted11] decimal NOT NULL,
    [BudgetUnitsPerEncounterAdjusted12] decimal NOT NULL,
    [ProjectionAdjusted01] decimal NOT NULL,
    [ProjectionAdjusted02] decimal NOT NULL,
    [ProjectionAdjusted03] decimal NOT NULL,
    [ProjectionAdjusted04] decimal NOT NULL,
    [ProjectionAdjusted05] decimal NOT NULL,
    [ProjectionAdjusted06] decimal NOT NULL,
    [ProjectionAdjusted07] decimal NOT NULL,
    [ProjectionAdjusted08] decimal NOT NULL,
    [ProjectionAdjusted09] decimal NOT NULL,
    [ProjectionAdjusted10] decimal NOT NULL,
    [ProjectionAdjusted11] decimal NOT NULL,
    [ProjectionAdjusted12] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted01] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted02] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted03] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted04] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted05] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted06] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted07] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted08] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted09] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted10] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted11] decimal NOT NULL,
    [ProjectionUnitsPerEncounterAdjusted12] decimal NOT NULL,
    [InitialBudgetDollars01] decimal NOT NULL,
    [InitialBudgetDollars02] decimal NOT NULL,
    [InitialBudgetDollars03] decimal NOT NULL,
    [InitialBudgetDollars04] decimal NOT NULL,
    [InitialBudgetDollars05] decimal NOT NULL,
    [InitialBudgetDollars06] decimal NOT NULL,
    [InitialBudgetDollars07] decimal NOT NULL,
    [InitialBudgetDollars08] decimal NOT NULL,
    [InitialBudgetDollars09] decimal NOT NULL,
    [InitialBudgetDollars10] decimal NOT NULL,
    [InitialBudgetDollars11] decimal NOT NULL,
    [InitialBudgetDollars12] decimal NOT NULL,
    [InitialProjectionDollars01] decimal NOT NULL,
    [InitialProjectionDollars02] decimal NOT NULL,
    [InitialProjectionDollars03] decimal NOT NULL,
    [InitialProjectionDollars04] decimal NOT NULL,
    [InitialProjectionDollars05] decimal NOT NULL,
    [InitialProjectionDollars06] decimal NOT NULL,
    [InitialProjectionDollars07] decimal NOT NULL,
    [InitialProjectionDollars08] decimal NOT NULL,
    [InitialProjectionDollars09] decimal NOT NULL,
    [InitialProjectionDollars10] decimal NOT NULL,
    [InitialProjectionDollars11] decimal NOT NULL,
    [InitialProjectionDollars12] decimal NOT NULL,
    [TargetPrice01] decimal NOT NULL,
    [TargetPrice02] decimal NOT NULL,
    [TargetPrice03] decimal NOT NULL,
    [TargetPrice04] decimal NOT NULL,
    [TargetPrice05] decimal NOT NULL,
    [TargetPrice06] decimal NOT NULL,
    [TargetPrice07] decimal NOT NULL,
    [TargetPrice08] decimal NOT NULL,
    [TargetPrice09] decimal NOT NULL,
    [TargetPrice10] decimal NOT NULL,
    [TargetPrice11] decimal NOT NULL,
    [TargetPrice12] decimal NOT NULL,
    [BudgetPrice01] decimal NOT NULL,
    [BudgetPrice02] decimal NOT NULL,
    [BudgetPrice03] decimal NOT NULL,
    [BudgetPrice04] decimal NOT NULL,
    [BudgetPrice05] decimal NOT NULL,
    [BudgetPrice06] decimal NOT NULL,
    [BudgetPrice07] decimal NOT NULL,
    [BudgetPrice08] decimal NOT NULL,
    [BudgetPrice09] decimal NOT NULL,
    [BudgetPrice10] decimal NOT NULL,
    [BudgetPrice11] decimal NOT NULL,
    [BudgetPrice12] decimal NOT NULL,
    [ProjectionPrice01] decimal NOT NULL,
    [ProjectionPrice02] decimal NOT NULL,
    [ProjectionPrice03] decimal NOT NULL,
    [ProjectionPrice04] decimal NOT NULL,
    [ProjectionPrice05] decimal NOT NULL,
    [ProjectionPrice06] decimal NOT NULL,
    [ProjectionPrice07] decimal NOT NULL,
    [ProjectionPrice08] decimal NOT NULL,
    [ProjectionPrice09] decimal NOT NULL,
    [ProjectionPrice10] decimal NOT NULL,
    [ProjectionPrice11] decimal NOT NULL,
    [ProjectionPrice12] decimal NOT NULL,
    [TargetDollarsAdjusted01] decimal NOT NULL,
    [TargetDollarsAdjusted02] decimal NOT NULL,
    [TargetDollarsAdjusted03] decimal NOT NULL,
    [TargetDollarsAdjusted04] decimal NOT NULL,
    [TargetDollarsAdjusted05] decimal NOT NULL,
    [TargetDollarsAdjusted06] decimal NOT NULL,
    [TargetDollarsAdjusted07] decimal NOT NULL,
    [TargetDollarsAdjusted08] decimal NOT NULL,
    [TargetDollarsAdjusted09] decimal NOT NULL,
    [TargetDollarsAdjusted10] decimal NOT NULL,
    [TargetDollarsAdjusted11] decimal NOT NULL,
    [TargetDollarsAdjusted12] decimal NOT NULL,
    [BudgetDollarsAdjusted01] decimal NOT NULL,
    [BudgetDollarsAdjusted02] decimal NOT NULL,
    [BudgetDollarsAdjusted03] decimal NOT NULL,
    [BudgetDollarsAdjusted04] decimal NOT NULL,
    [BudgetDollarsAdjusted05] decimal NOT NULL,
    [BudgetDollarsAdjusted06] decimal NOT NULL,
    [BudgetDollarsAdjusted07] decimal NOT NULL,
    [BudgetDollarsAdjusted08] decimal NOT NULL,
    [BudgetDollarsAdjusted09] decimal NOT NULL,
    [BudgetDollarsAdjusted10] decimal NOT NULL,
    [BudgetDollarsAdjusted11] decimal NOT NULL,
    [BudgetDollarsAdjusted12] decimal NOT NULL,
    [ProjectionDollarsAdjusted01] decimal NOT NULL,
    [ProjectionDollarsAdjusted02] decimal NOT NULL,
    [ProjectionDollarsAdjusted03] decimal NOT NULL,
    [ProjectionDollarsAdjusted04] decimal NOT NULL,
    [ProjectionDollarsAdjusted05] decimal NOT NULL,
    [ProjectionDollarsAdjusted06] decimal NOT NULL,
    [ProjectionDollarsAdjusted07] decimal NOT NULL,
    [ProjectionDollarsAdjusted08] decimal NOT NULL,
    [ProjectionDollarsAdjusted09] decimal NOT NULL,
    [ProjectionDollarsAdjusted10] decimal NOT NULL,
    [ProjectionDollarsAdjusted11] decimal NOT NULL,
    [ProjectionDollarsAdjusted12] decimal NOT NULL,
    [AddDate] datetime NOT NULL,
    [IsNew] bit NOT NULL,
    [BudgetLockType] tinyint NOT NULL,
    [BudgetLockFlag] tinyint NOT NULL,
    [TargetLockType] tinyint NOT NULL,
    [TargetLockFlag] tinyint NOT NULL,
    [ProjectionLockType] tinyint NOT NULL,
    [ProjectionLockFlag] tinyint NOT NULL,
    [IsCVReportRefreshRequired] bit NOT NULL,
    PRIMARY KEY ([ChargeVolumeID])
);

CREATE CLUSTERED INDEX [IX_ChargeVolume] ON [fp].[ChargeVolume] ([BudgetConfigID], [EntityID], [DepartmentID], [ChargeCodeID]);
CREATE NONCLUSTERED INDEX [CORE_EntityGroupConfigID_inc] ON [fp].[ChargeVolume] ([EntityGroupConfigID], [BudgetConfigID], [UnitTypeID]) INCLUDE ([ChargeVolumeID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [IsNew]);
CREATE NONCLUSTERED INDEX [IX_ChargeVolume_BudgetConfig] ON [fp].[ChargeVolume] ([BudgetConfigID]) INCLUDE ([ChargeVolumeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ChargeVolume_Department] ON [fp].[ChargeVolume] ([DepartmentID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ChargeVolume_Entity] ON [fp].[ChargeVolume] ([EntityID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ChargeVolume] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [ServiceEntityID], [MSDRGID], [UBRevCodeID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [PerformingProviderID], [PerformingProviderSpecialtyID], [BillingCPTID], [UnitTypeID]) INCLUDE ([IsNew]);
CREATE NONCLUSTERED INDEX [NCNU_SleCvFlexing] ON [fp].[ChargeVolume] ([BudgetConfigID], [UnitTypeID]) INCLUDE ([ChargeVolumeID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ServiceEntityID], [MSDRGID], [PrimaryCPTID], [ServiceProviderID]);
GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_ChargeCode] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0017424D] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__00D65C5C] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__010B6686] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__01CA8095] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__01FF8ABF] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__02BEA4CE] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__02F3AEF8] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__03B2C907] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__03E7D331] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__04A6ED40] DEFAULT ((0)) FOR [InitialBudgetDollars01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__04DBF76A] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__059B1179] DEFAULT ((0)) FOR [InitialBudgetDollars02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__05D01BA3] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__068F35B2] DEFAULT ((0)) FOR [InitialBudgetDollars03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__06C43FDC] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__078359EB] DEFAULT ((0)) FOR [InitialBudgetDollars04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__07B86415] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__08777E24] DEFAULT ((0)) FOR [InitialBudgetDollars05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__08AC884E] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__096BA25D] DEFAULT ((0)) FOR [InitialBudgetDollars06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__09A0AC87] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0A5FC696] DEFAULT ((0)) FOR [InitialBudgetDollars07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0A94D0C0] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0B53EACF] DEFAULT ((0)) FOR [InitialBudgetDollars08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0B88F4F9] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0C480F08] DEFAULT ((0)) FOR [InitialBudgetDollars09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0C7D1932] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0D3C3341] DEFAULT ((0)) FOR [InitialBudgetDollars10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0D713D6B] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0E30577A] DEFAULT ((0)) FOR [InitialBudgetDollars11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0E6561A4] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0F247BB3] DEFAULT ((0)) FOR [InitialBudgetDollars12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0F5985DD] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__10189FEC] DEFAULT ((0)) FOR [InitialProjectionDollars01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__104DAA16] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__110CC425] DEFAULT ((0)) FOR [InitialProjectionDollars02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__1141CE4F] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1200E85E] DEFAULT ((0)) FOR [InitialProjectionDollars03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1235F288] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__12F50C97] DEFAULT ((0)) FOR [InitialProjectionDollars04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__132A16C1] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__13E930D0] DEFAULT ((0)) FOR [InitialProjectionDollars05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__141E3AFA] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__14DD5509] DEFAULT ((0)) FOR [InitialProjectionDollars06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__15125F33] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__15D17942] DEFAULT ((0)) FOR [InitialProjectionDollars07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1606836C] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__16C59D7B] DEFAULT ((0)) FOR [InitialProjectionDollars08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__16FAA7A5] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__17B9C1B4] DEFAULT ((0)) FOR [InitialProjectionDollars09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__17EECBDE] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__18ADE5ED] DEFAULT ((0)) FOR [InitialProjectionDollars10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__18E2F017] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__19A20A26] DEFAULT ((0)) FOR [InitialProjectionDollars11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__19D71450] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1A962E5F] DEFAULT ((0)) FOR [InitialProjectionDollars12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1ACB3889] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1B8A5298] DEFAULT ((0)) FOR [TargetPrice01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1BBF5CC2] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1C7E76D1] DEFAULT ((0)) FOR [TargetPrice02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1CB380FB] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1D729B0A] DEFAULT ((0)) FOR [TargetPrice03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1DA7A534] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1E66BF43] DEFAULT ((0)) FOR [TargetPrice04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1E9BC96D] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1F5AE37C] DEFAULT ((0)) FOR [TargetPrice05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1F8FEDA6] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__204F07B5] DEFAULT ((0)) FOR [TargetPrice06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__208411DF] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__21432BEE] DEFAULT ((0)) FOR [TargetPrice07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__21783618] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__22375027] DEFAULT ((0)) FOR [TargetPrice08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__226C5A51] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__232B7460] DEFAULT ((0)) FOR [TargetPrice09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__23607E8A] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__241F9899] DEFAULT ((0)) FOR [TargetPrice10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2454A2C3] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__2513BCD2] DEFAULT ((0)) FOR [TargetPrice11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2548C6FC] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__2607E10B] DEFAULT ((0)) FOR [TargetPrice12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__263CEB35] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__26FC0544] DEFAULT ((0)) FOR [BudgetPrice01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__27310F6E] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__27F0297D] DEFAULT ((0)) FOR [BudgetPrice02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__282533A7] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__28E44DB6] DEFAULT ((0)) FOR [BudgetPrice03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__291957E0] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__29D871EF] DEFAULT ((0)) FOR [BudgetPrice04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2A0D7C19] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2ACC9628] DEFAULT ((0)) FOR [BudgetPrice05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2B01A052] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2BC0BA61] DEFAULT ((0)) FOR [BudgetPrice06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2BF5C48B] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2CB4DE9A] DEFAULT ((0)) FOR [BudgetPrice07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2CE9E8C4] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2DA902D3] DEFAULT ((0)) FOR [BudgetPrice08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2DDE0CFD] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2E9D270C] DEFAULT ((0)) FOR [BudgetPrice09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2ED23136] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2F914B45] DEFAULT ((0)) FOR [BudgetPrice10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2FC6556F] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__30856F7E] DEFAULT ((0)) FOR [BudgetPrice11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__30BA79A8] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__317993B7] DEFAULT ((0)) FOR [BudgetPrice12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__31AE9DE1] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__326DB7F0] DEFAULT ((0)) FOR [ProjectionPrice01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__32A2C21A] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3361DC29] DEFAULT ((0)) FOR [ProjectionPrice02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3396E653] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__34560062] DEFAULT ((0)) FOR [ProjectionPrice03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__348B0A8C] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__354A249B] DEFAULT ((0)) FOR [ProjectionPrice04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__357F2EC5] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__363E48D4] DEFAULT ((0)) FOR [ProjectionPrice05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__367352FE] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__37326D0D] DEFAULT ((0)) FOR [ProjectionPrice06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__37677737] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__38269146] DEFAULT ((0)) FOR [ProjectionPrice07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__385B9B70] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__391AB57F] DEFAULT ((0)) FOR [ProjectionPrice08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__394FBFA9] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3A0ED9B8] DEFAULT ((0)) FOR [ProjectionPrice09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3A43E3E2] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3B02FDF1] DEFAULT ((0)) FOR [ProjectionPrice10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3B38081B] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3BF7222A] DEFAULT ((0)) FOR [ProjectionPrice11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3C2C2C54] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3CEB4663] DEFAULT ((0)) FOR [ProjectionPrice12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3D20508D] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__AddDa__3DDF6A9C] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3E1474C6] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__IsNew__3ED38ED5] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3F0898FF] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__3FC7B30E] DEFAULT ((0)) FOR [BudgetLockType]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__3FFCBD38] DEFAULT ((0)) FOR [TargetAdjusted01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__40BBD747] DEFAULT ((0)) FOR [BudgetLockFlag]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__40F0E171] DEFAULT ((0)) FOR [TargetAdjusted02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__41AFFB80] DEFAULT ((0)) FOR [TargetLockType]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__41E505AA] DEFAULT ((0)) FOR [TargetAdjusted03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__42A41FB9] DEFAULT ((0)) FOR [TargetLockFlag]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__42D929E3] DEFAULT ((0)) FOR [TargetAdjusted04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__439843F2] DEFAULT ((0)) FOR [ProjectionLockType]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__43CD4E1C] DEFAULT ((0)) FOR [TargetAdjusted05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__448C682B] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__44C17255] DEFAULT ((0)) FOR [TargetAdjusted06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__IsCVR__45808C64] DEFAULT ((0)) FOR [IsCVReportRefreshRequired]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__45B5968E] DEFAULT ((0)) FOR [TargetAdjusted07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__46A9BAC7] DEFAULT ((0)) FOR [TargetAdjusted08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__479DDF00] DEFAULT ((0)) FOR [TargetAdjusted09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__48920339] DEFAULT ((0)) FOR [TargetAdjusted10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__49862772] DEFAULT ((0)) FOR [TargetAdjusted11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4A7A4BAB] DEFAULT ((0)) FOR [TargetAdjusted12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4B6E6FE4] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4C62941D] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4D56B856] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4E4ADC8F] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4F3F00C8] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__50332501] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__5127493A] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__521B6D73] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__530F91AC] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__5403B5E5] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__54F7DA1E] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__55EBFE57] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__56E02290] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__57D446C9] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__58C86B02] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__59BC8F3B] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5AB0B374] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5BA4D7AD] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5C98FBE6] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5D8D201F] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5E814458] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5F756891] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__60698CCA] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__615DB103] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6251D53C] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6345F975] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__643A1DAE] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__652E41E7] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__66226620] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__67168A59] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__680AAE92] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__683FB8BC] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__68FED2CB] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Entit__6933DCF5] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__69F2F704] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Entit__6A28012E] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6AE71B3D] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Depar__6B1C2567] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6BDB3F76] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__6C1049A0] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6CCF63AF] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Patie__6D046DD9] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__6DC387E8] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__AgeCo__6DF89212] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__6EB7AC21] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Medic__6EECB64B] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__6FABD05A] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Charg__6FE0DA84] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__709FF493] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__70D4FEBD] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__719418CC] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__MSDRG__71C922F6] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__72883D05] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__UBRev__72BD472F] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__737C613E] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Prima__73B16B68] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__74708577] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__74A58FA1] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7564A9B0] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__7599B3DA] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7658CDE9] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Perfo__768DD813] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__774CF222] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Perfo__7781FC4C] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7841165B] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Billi__78762085] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__79353A94] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__UnitT__796A44BE] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7A295ECD] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Varia__7A5E68F7] DEFAULT ((0)) FOR [VariableDirectUnitCost]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7B1D8306] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7B528D30] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7C11A73F] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7C46B169] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7D05CB78] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7D3AD5A2] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7DF9EFB1] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted06]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7E2EF9DB] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7EEE13EA] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted07]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7F231E14] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7FE23823] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted08]; GO

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

---------------------------------------------
-- fp.ChargeVolumeAddProviderAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeVolumeAddProviderAdjustment] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [CLU_CVAddProvider] ON [fp].[ChargeVolumeAddProviderAdjustment] ([BudgetConfigID], [DepartmentID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ChargeVolumeAddProviderAdjustment] ([BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [ServiceEntityID], [MSDRGID], [UBRevCodeID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [PerformingProviderID], [PerformingProviderSpecialtyID], [BillingCPTID], [TimeClassID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Charg__009337DE] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__01875C17] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__MSDRG__027B8050] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__UBRev__036FA489] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Prima__0463C8C2] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Billi__0557ECFB] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__064C1134] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__0740356D] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Perfo__083459A6] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Perfo__09287DDF] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__TimeC__0C04EA8A] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Budge__0CF90EC3] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__IsRec__0DED32FC] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__0EE15735] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__0FD57B6E] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__10C99FA7] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__11BDC3E0] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__12B1E819] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__13A60C52] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__149A308B] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__158E54C4] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__168278FD] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__17769D36] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__186AC16F] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__195EE5A8] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Budge__78F21616] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Adjus__79E63A4F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Entit__7ADA5E88] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Depar__7BCE82C1] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__7CC2A6FA] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Patie__7DB6CB33] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__AgeCo__7EAAEF6C] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Medic__7F9F13A5] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO

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

---------------------------------------------
-- fp.ChargeVolumeAdjustmentRate ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeVolumeAdjustmentRate] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [EntityID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_Clustered_ChargeVolumeAdjustmentRate] ON [fp].[ChargeVolumeAdjustmentRate] ([BudgetConfigID]);
GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Adjus__3996AB10] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Budge__3A8ACF49] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Depar__3B7EF382] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__3C7317BB] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Patie__3D673BF4] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__AgeCo__3E5B602D] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Medic__3F4F8466] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Charg__4043A89F] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Entit__4137CCD8] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__422BF111] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__MSDRG__4320154A] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__UBRev__44143983] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Prima__45085DBC] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__45FC81F5] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__46F0A62E] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Perfo__47E4CA67] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Perfo__48D8EEA0] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Billi__4BB55B4B] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__TimeC__4CA97F84] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__4D9DA3BD] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__4E91C7F6] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__4F85EC2F] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__507A1068] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__516E34A1] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__526258DA] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__53567D13] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__544AA14C] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__553EC585] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__5632E9BE] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__57270DF7] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__581B3230] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.ChargeVolumeChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeVolumeChangeHistory] (
    [RowID] bigint NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    [ChargeVolumeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [CORE_ChargeVolumeID] ON [fp].[ChargeVolumeChangeHistory] ([ChargeVolumeID]);
CREATE NONCLUSTERED INDEX [CORE_ChargeVolumeChangeHistory_ImpactReportLoads] ON [fp].[ChargeVolumeChangeHistory] ([AdjustmentGUID], [FiscalMonthID], [TimeClassID]) INCLUDE ([ChargeVolumeID], [AdjustmentType], [UnitTypeID], [BudgetPhaseID], [OldValue], [NewValue], [BudgetConfigID]);
GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__DateC__02E594A4] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Adjus__188E83E9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Adjus__1982A822] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Fisca__1B6AF094] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__UnitT__1C5F14CD] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__TimeC__1D533906] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Budge__1E475D3F] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__OldVa__1F3B8178] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__NewVa__202FA5B1] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Budge__5E1E2449] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__NewCh__7A9E6019] DEFAULT ((0)) FOR [ChargeVolumeID]; GO

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

---------------------------------------------
-- fp.ChargeVolumeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeVolumeHistory] (
    [RowID] int NOT NULL,
    [ChargeVolumeID] int NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [ActualYTDDollarValue01] decimal NOT NULL,
    [ActualYTDDollarValue02] decimal NOT NULL,
    [ActualYTDDollarValue03] decimal NOT NULL,
    [ActualYTDDollarValue04] decimal NOT NULL,
    [ActualYTDDollarValue05] decimal NOT NULL,
    [ActualYTDDollarValue06] decimal NOT NULL,
    [ActualYTDDollarValue07] decimal NOT NULL,
    [ActualYTDDollarValue08] decimal NOT NULL,
    [ActualYTDDollarValue09] decimal NOT NULL,
    [ActualYTDDollarValue10] decimal NOT NULL,
    [ActualYTDDollarValue11] decimal NOT NULL,
    [ActualYTDDollarValue12] decimal NOT NULL,
    [PriorYearActualDollarValue01] decimal NOT NULL,
    [PriorYearActualDollarValue02] decimal NOT NULL,
    [PriorYearActualDollarValue03] decimal NOT NULL,
    [PriorYearActualDollarValue04] decimal NOT NULL,
    [PriorYearActualDollarValue05] decimal NOT NULL,
    [PriorYearActualDollarValue06] decimal NOT NULL,
    [PriorYearActualDollarValue07] decimal NOT NULL,
    [PriorYearActualDollarValue08] decimal NOT NULL,
    [PriorYearActualDollarValue09] decimal NOT NULL,
    [PriorYearActualDollarValue10] decimal NOT NULL,
    [PriorYearActualDollarValue11] decimal NOT NULL,
    [PriorYearActualDollarValue12] decimal NOT NULL,
    [CurrentYearBudgetDollar01] decimal NOT NULL,
    [CurrentYearBudgetDollar02] decimal NOT NULL,
    [CurrentYearBudgetDollar03] decimal NOT NULL,
    [CurrentYearBudgetDollar04] decimal NOT NULL,
    [CurrentYearBudgetDollar05] decimal NOT NULL,
    [CurrentYearBudgetDollar06] decimal NOT NULL,
    [CurrentYearBudgetDollar07] decimal NOT NULL,
    [CurrentYearBudgetDollar08] decimal NOT NULL,
    [CurrentYearBudgetDollar09] decimal NOT NULL,
    [CurrentYearBudgetDollar10] decimal NOT NULL,
    [CurrentYearBudgetDollar11] decimal NOT NULL,
    [CurrentYearBudgetDollar12] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    [ActualYTDDollarValueTotal] decimal NOT NULL,
    [PriorYearActualDollarValueTotal] decimal NOT NULL,
    [CurrentYearBudgetDollarTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ChargeVolumeHistory] ON [fp].[ChargeVolumeHistory] ([ChargeVolumeID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ChargeVolumeHistory] ([ChargeVolumeID]);
GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [FK_ChargeVolumeHistory_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ChargeVolume] ([ChargeVolumeID]); GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__006C4808] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__01606C41] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0254907A] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0348B4B3] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__043CD8EC] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0530FD25] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0625215E] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__07194597] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__080D69D0] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__09018E09] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__09F5B242] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0AE9D67B] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0BDDFAB4] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0CD21EED] DEFAULT ((0)) FOR [ActualYTDDollarValue01]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0DC64326] DEFAULT ((0)) FOR [ActualYTDDollarValue02]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0EBA675F] DEFAULT ((0)) FOR [ActualYTDDollarValue03]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0FAE8B98] DEFAULT ((0)) FOR [ActualYTDDollarValue04]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__10A2AFD1] DEFAULT ((0)) FOR [ActualYTDDollarValue05]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__1196D40A] DEFAULT ((0)) FOR [ActualYTDDollarValue06]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__128AF843] DEFAULT ((0)) FOR [ActualYTDDollarValue07]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__137F1C7C] DEFAULT ((0)) FOR [ActualYTDDollarValue08]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__147340B5] DEFAULT ((0)) FOR [ActualYTDDollarValue09]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__156764EE] DEFAULT ((0)) FOR [ActualYTDDollarValue10]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__165B8927] DEFAULT ((0)) FOR [ActualYTDDollarValue11]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__174FAD60] DEFAULT ((0)) FOR [ActualYTDDollarValue12]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1843D199] DEFAULT ((0)) FOR [PriorYearActualDollarValue01]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1937F5D2] DEFAULT ((0)) FOR [PriorYearActualDollarValue02]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1A2C1A0B] DEFAULT ((0)) FOR [PriorYearActualDollarValue03]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1B203E44] DEFAULT ((0)) FOR [PriorYearActualDollarValue04]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1C14627D] DEFAULT ((0)) FOR [PriorYearActualDollarValue05]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1D0886B6] DEFAULT ((0)) FOR [PriorYearActualDollarValue06]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1DFCAAEF] DEFAULT ((0)) FOR [PriorYearActualDollarValue07]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1EF0CF28] DEFAULT ((0)) FOR [PriorYearActualDollarValue08]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1FE4F361] DEFAULT ((0)) FOR [PriorYearActualDollarValue09]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__20D9179A] DEFAULT ((0)) FOR [PriorYearActualDollarValue10]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__21CD3BD3] DEFAULT ((0)) FOR [PriorYearActualDollarValue11]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__22C1600C] DEFAULT ((0)) FOR [PriorYearActualDollarValue12]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__23B58445] DEFAULT ((0)) FOR [CurrentYearBudgetDollar01]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__24A9A87E] DEFAULT ((0)) FOR [CurrentYearBudgetDollar02]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__259DCCB7] DEFAULT ((0)) FOR [CurrentYearBudgetDollar03]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2691F0F0] DEFAULT ((0)) FOR [CurrentYearBudgetDollar04]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__27861529] DEFAULT ((0)) FOR [CurrentYearBudgetDollar05]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__287A3962] DEFAULT ((0)) FOR [CurrentYearBudgetDollar06]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__296E5D9B] DEFAULT ((0)) FOR [CurrentYearBudgetDollar07]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2A6281D4] DEFAULT ((0)) FOR [CurrentYearBudgetDollar08]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2B56A60D] DEFAULT ((0)) FOR [CurrentYearBudgetDollar09]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2C4ACA46] DEFAULT ((0)) FOR [CurrentYearBudgetDollar10]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2D3EEE7F] DEFAULT ((0)) FOR [CurrentYearBudgetDollar11]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2E3312B8] DEFAULT ((0)) FOR [CurrentYearBudgetDollar12]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Charg__6988E2B0] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6A7D06E9] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6B712B22] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6C654F5B] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6D597394] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6E4D97CD] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6F41BC06] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__7035E03F] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__712A0478] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__721E28B1] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__73124CEA] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__74067123] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__74FA955C] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__75EEB995] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__76E2DDCE] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__77D70207] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__78CB2640] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__79BF4A79] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7AB36EB2] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7BA792EB] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7C9BB724] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7D8FDB5D] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7E83FF96] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7F7823CF] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO

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

---------------------------------------------
-- fp.ChargeVolumeSpreadUnlockData ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeVolumeSpreadUnlockData] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [Version] timestamp NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__IsRec__00D263A9] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Budge__0E95A7C4] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Entit__107DF036] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Depar__1172146F] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Patie__126638A8] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__135A5CE1] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__AgeCo__144E811A] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Medic__1542A553] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Charg__1636C98C] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__172AEDC5] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__181F11FE] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__19133637] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1A075A70] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1AFB7EA9] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1BEFA2E2] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1CE3C71B] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1DD7EB54] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1ECC0F8D] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1FC033C6] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__20B457FF] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__21A87C38] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__27C21398] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Prima__28B637D1] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Billi__29AA5C0A] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Perfo__2A9E8043] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Perfo__2B92A47C] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [df_ChargeVolumeSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__MSDRG__59838C5E] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__UBRev__5A77B097] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__5C5FF909] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__5D541D42] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO

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

---------------------------------------------
-- fp.ChargeVolumeSpreads ------------------
---------------------------------------------
CREATE TABLE [fp].[ChargeVolumeSpreads] (
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [IsInactive] bit NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [GlobalSpreadID] int NOT NULL,
    [ChargeEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [BillingProviderID] int NOT NULL,
    [BillingProviderSpecialtyID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [DepartmentID], [ServiceLineID], [ChargeCodeID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID])
);
GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_ChargeVolumeSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_ChargeCode] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Budge__0FBED627] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Depar__10B2FA60] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Servi__129B42D2] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Charg__14838B44] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Patie__166BD3B6] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__AgeCo__18541C28] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Medic__1A3C649A] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__IsIna__1C24AD0C] DEFAULT ((0)) FOR [IsInactive]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1D18D145] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1E0CF57E] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1F0119B7] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1FF53DF0] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__20E96229] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__21DD8662] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__22D1AA9B] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__23C5CED4] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__24B9F30D] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__25AE1746] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__26A23B7F] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__27965FB8] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Total__288A83F1] DEFAULT ((0)) FOR [TotalImportedValue]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Globa__3A5F1B69] DEFAULT ((1)) FOR [GlobalSpreadID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Charg__457C93B1] DEFAULT ((0)) FOR [ChargeEntityID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__MSDRG__4670B7EA] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__UBRev__4764DC23] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__CPTID__4859005C] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Servi__494D2495] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Servi__4A4148CE] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Billi__4B356D07] DEFAULT ((0)) FOR [BillingProviderID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Billi__4C299140] DEFAULT ((0)) FOR [BillingProviderSpecialtyID]; GO
ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [df_ChargeVolumeSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO

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

---------------------------------------------
-- fp.CustomReportLink ------------------
---------------------------------------------
CREATE TABLE [fp].[CustomReportLink] (
    [CustomReportLinkGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([CustomReportLinkGUID])
);
GO
ALTER TABLE [fp].[CustomReportLink] ADD CONSTRAINT [FK_FpCustomReportLink_Report] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [fp].[CustomReportLink] ADD CONSTRAINT [DF__CustomRep__Custo__207E827E] DEFAULT (newid()) FOR [CustomReportLinkGUID]; GO
ALTER TABLE [fp].[CustomReportLink] ADD CONSTRAINT [df_CustomReportLink_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO

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

---------------------------------------------
-- fp.DSSamplingMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[DSSamplingMapping] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [FiscalYearTable] nvarchar(128) NOT NULL,
    [FiscalYearColumn] nvarchar(128) NOT NULL,
    [ExtractFiscalYearFromDate] bit NOT NULL,
    [FiscalMonthTable] nvarchar(128) NOT NULL,
    [FiscalMonthColumn] nvarchar(128) NOT NULL,
    [ExtractFiscalMonthFromDate] bit NOT NULL,
    [ServiceEntityTable] nvarchar(128) NOT NULL,
    [ServiceEntityColumn] nvarchar(128) NOT NULL,
    [ServiceLineTable] nvarchar(128) NOT NULL,
    [ServiceLineColumn] nvarchar(128) NOT NULL,
    [AgeCohortTable] nvarchar(128) NOT NULL,
    [AgeCohortColumn] nvarchar(128) NOT NULL,
    [ServiceLineDepartmentTable] nvarchar(128) NOT NULL,
    [ServiceLineDepartmentColumn] nvarchar(128) NOT NULL,
    [DepartmentTable] nvarchar(128) NOT NULL,
    [DepartmentColumn] nvarchar(128) NOT NULL,
    [UBRevCodeTable] nvarchar(128) NOT NULL,
    [UBRevCodeColumn] nvarchar(128) NOT NULL,
    [PrimaryCPTIDTable] nvarchar(128) NOT NULL,
    [PrimaryCPTIDColumn] nvarchar(128) NOT NULL,
    [BillingCPTIDTable] nvarchar(128) NOT NULL,
    [BillingCPTIDColumn] nvarchar(128) NOT NULL,
    [PrimaryPhysicianTable] nvarchar(128) NOT NULL,
    [PrimaryPhysicianColumn] nvarchar(128) NOT NULL,
    [PerformingPhysicianTable] nvarchar(128) NOT NULL,
    [PerformingPhysicianColumn] nvarchar(128) NOT NULL,
    [VolumeTable] nvarchar(128) NOT NULL,
    [VolumeColumn] nvarchar(128) NOT NULL,
    [MSDRGTable] nvarchar(128) NOT NULL,
    [MSDRGColumn] nvarchar(128) NOT NULL,
    [ServiceEntityIdentifierGuid] uniqueidentifier NOT NULL,
    [ServiceLineIdentifierGuid] uniqueidentifier NOT NULL,
    [AgeCohortIdentifierGuid] uniqueidentifier NOT NULL,
    [ServiceLineDepartmentIdentifierGuid] uniqueidentifier NOT NULL,
    [DepartmentIdentifierGuid] uniqueidentifier NOT NULL,
    [UBRevCodeIdentifierGuid] uniqueidentifier NOT NULL,
    [PrimaryCPTIDIdentifierGuid] uniqueidentifier NOT NULL,
    [BillingCPTIDIdentifierGuid] uniqueidentifier NOT NULL,
    [PrimaryPhysicianIdentifierGuid] uniqueidentifier NOT NULL,
    [PerformingPhysicianIdentifierGuid] uniqueidentifier NOT NULL,
    [MSDRGIdentifierGuid] uniqueidentifier NOT NULL,
    [VolumeIdentifierGuid] uniqueidentifier NOT NULL,
    [DateIdentifierGuid] uniqueidentifier NOT NULL,
    [PatientClassTable] nvarchar(256) NOT NULL,
    [PatientClassColumn] nvarchar(256) NOT NULL,
    [PatientClassIdentifierGuid] uniqueidentifier NOT NULL,
    [IsPatientClassConfigured] bit NOT NULL,
    [MedSurgTable] nvarchar(256) NOT NULL,
    [MedSurgColumn] nvarchar(256) NOT NULL,
    [MedSurgIdentifierGuid] uniqueidentifier NOT NULL,
    [IsMedSurgConfigured] bit NOT NULL,
    [InsuranceTable] nvarchar(256) NOT NULL,
    [InsuranceColumn] nvarchar(256) NOT NULL,
    [InsuranceIdentifierGuid] uniqueidentifier NOT NULL,
    [ClinicalIndicatorID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[DSSamplingMapping] ([BudgetConfigID]);
GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF_DSSamplingMapping_ClinicalIndicatorID] DEFAULT ((0)) FOR [ClinicalIndicatorID]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__1DAF64D0] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [ServiceEntityIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__1EA38909] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [ServiceLineIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__AgeCo__1F97AD42] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [AgeCohortIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__208BD17B] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [ServiceLineDepartmentIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Depar__217FF5B4] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [DepartmentIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__UBRev__227419ED] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [UBRevCodeIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__23683E26] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PrimaryCPTIDIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Billi__245C625F] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [BillingCPTIDIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__25508698] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PrimaryPhysicianIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Perfo__2644AAD1] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PerformingPhysicianIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MSDRG__2738CF0A] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [MSDRGIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Volum__282CF343] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [VolumeIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__DateI__2921177C] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [DateIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__306C6832] DEFAULT ('') FOR [FiscalYearTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__31608C6B] DEFAULT ('') FOR [FiscalYearColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Extra__3254B0A4] DEFAULT ((0)) FOR [ExtractFiscalYearFromDate]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__3348D4DD] DEFAULT ('') FOR [FiscalMonthTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__343CF916] DEFAULT ('') FOR [FiscalMonthColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Extra__35311D4F] DEFAULT ((0)) FOR [ExtractFiscalMonthFromDate]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__36254188] DEFAULT ('') FOR [ServiceEntityTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__371965C1] DEFAULT ('') FOR [ServiceEntityColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__380D89FA] DEFAULT ('') FOR [ServiceLineTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__3901AE33] DEFAULT ('') FOR [ServiceLineColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__AgeCo__39F5D26C] DEFAULT ('') FOR [AgeCohortTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__AgeCo__3AE9F6A5] DEFAULT ('') FOR [AgeCohortColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__3BDE1ADE] DEFAULT ('') FOR [ServiceLineDepartmentTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__3CD23F17] DEFAULT ('') FOR [ServiceLineDepartmentColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Depar__3DC66350] DEFAULT ('') FOR [DepartmentTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Depar__3EBA8789] DEFAULT ('') FOR [DepartmentColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__UBRev__3FAEABC2] DEFAULT ('') FOR [UBRevCodeTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__UBRev__40A2CFFB] DEFAULT ('') FOR [UBRevCodeColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__4196F434] DEFAULT ('') FOR [PrimaryCPTIDTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__428B186D] DEFAULT ('') FOR [PrimaryCPTIDColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Billi__437F3CA6] DEFAULT ('') FOR [BillingCPTIDTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Billi__447360DF] DEFAULT ('') FOR [BillingCPTIDColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__45678518] DEFAULT ('') FOR [PrimaryPhysicianTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__465BA951] DEFAULT ('') FOR [PrimaryPhysicianColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Perfo__474FCD8A] DEFAULT ('') FOR [PerformingPhysicianTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Perfo__4843F1C3] DEFAULT ('') FOR [PerformingPhysicianColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Volum__493815FC] DEFAULT ('') FOR [VolumeTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Volum__4A2C3A35] DEFAULT ('') FOR [VolumeColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MSDRG__4B205E6E] DEFAULT ('') FOR [MSDRGTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MSDRG__4C1482A7] DEFAULT ('') FOR [MSDRGColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Patie__63F7C487] DEFAULT ('') FOR [PatientClassTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Patie__64EBE8C0] DEFAULT ('') FOR [PatientClassColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Patie__65E00CF9] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PatientClassIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__IsPat__66D43132] DEFAULT ((0)) FOR [IsPatientClassConfigured]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MedSu__67C8556B] DEFAULT ('') FOR [MedSurgTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MedSu__68BC79A4] DEFAULT ('') FOR [MedSurgColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MedSu__69B09DDD] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [MedSurgIdentifierGuid]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__IsMed__6AA4C216] DEFAULT ((0)) FOR [IsMedSurgConfigured]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Insur__6DA12A52] DEFAULT ('') FOR [InsuranceTable]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Insur__6E954E8B] DEFAULT ('') FOR [InsuranceColumn]; GO
ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Insur__6F8972C4] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [InsuranceIdentifierGuid]; GO

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

---------------------------------------------
-- fp.DataRefreshTargetThreshold ------------------
---------------------------------------------
CREATE TABLE [fp].[DataRefreshTargetThreshold] (
    [ClassName] nvarchar(300) NOT NULL,
    [Threshold] int NOT NULL
);
GO
ALTER TABLE [fp].[DataRefreshTargetThreshold] ADD CONSTRAINT [DF__DataRefre__Class__178AE078] DEFAULT ('') FOR [ClassName]; GO
ALTER TABLE [fp].[DataRefreshTargetThreshold] ADD CONSTRAINT [DF__DataRefre__Thres__187F04B1] DEFAULT ((0)) FOR [Threshold]; GO

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

---------------------------------------------
-- fp.DataTransferConversionRates ------------------
---------------------------------------------
CREATE TABLE [fp].[DataTransferConversionRates] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [FK_DataTransferConversionRates_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [FK_DataTransferConversionRates_FiscalMonthID] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO
ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [FK_DataTransferConversionRates_TimeClassID] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__Budge__544C37FA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__TimeC__55405C33] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__Fisca__5634806C] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__Value__5728A4A5] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.DataTransferErrorLog ------------------
---------------------------------------------
CREATE TABLE [fp].[DataTransferErrorLog] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityCode] nvarchar(200) NOT NULL,
    [DepartmentCode] nvarchar(100) NOT NULL,
    [AccountCode] nvarchar(40) NOT NULL,
    [PatientClassCode] nvarchar(100) NOT NULL,
    [PayorCode] nvarchar(100) NOT NULL,
    [FileTransferType] nvarchar(100) NOT NULL,
    [ExecutionDate] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Budge__78899870] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Entit__797DBCA9] DEFAULT ('') FOR [EntityCode]; GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Depar__7A71E0E2] DEFAULT ('') FOR [DepartmentCode]; GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Accou__7B66051B] DEFAULT ('') FOR [AccountCode]; GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Patie__7C5A2954] DEFAULT ('') FOR [PatientClassCode]; GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Payor__7D4E4D8D] DEFAULT ('') FOR [PayorCode]; GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__FileT__7E4271C6] DEFAULT ('') FOR [FileTransferType]; GO
ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Execu__7F3695FF] DEFAULT ('1900-01-01T00:00:00') FOR [ExecutionDate]; GO

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

---------------------------------------------
-- fp.DeductionsFlexingConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[DeductionsFlexingConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID])
);
GO
ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [FK__Deduction__Depar__3DE4C833] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [df_DeductionsFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [DF__Deduction__Depar__3A008D9A] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [DF__Deduction__FlexM__3AF4B1D3] DEFAULT ((0)) FOR [FlexMethodID]; GO

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

---------------------------------------------
-- fp.DepartmentChargeAdjustmentImport ------------------
---------------------------------------------
CREATE TABLE [fp].[DepartmentChargeAdjustmentImport] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [Value] decimal NOT NULL,
    [Version] timestamp NOT NULL,
    [EntityID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[DepartmentChargeAdjustmentImport] ([AdjustmentID]);
GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Servi__1D448525] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__MSDRG__1E38A95E] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__UBRev__1F2CCD97] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Prima__2020F1D0] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Servi__21151609] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Servi__22093A42] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Perfo__22FD5E7B] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Adjus__23B256E9] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Perfo__23F182B4] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Billi__26CDEF5F] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Adjus__2D04EE81] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__ServiceLineID] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__PatientClassID] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__AgeCohortID] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__MedicalSurgicalID] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__ChargeCodeID] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Entit__337CE1E6] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__BudgetChargeUnits] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport_FiscalMonth] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF_DepartmentChargeAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__IsRec__72844452] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.DepartmentChargeVolumeAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[DepartmentChargeVolumeAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [AffectedDataCount] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [IsErrored] bit NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [FK__Departmen__Budge__49A9B822] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__48B593E9] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__IsErr__4A054A5F] DEFAULT ((0)) FOR [IsErrored]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__4A9DDC5B] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Value__4B920094] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__4C8624CD] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Group__4D7A4906] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__4E6E6D3F] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Comme__4F629178] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Autho__5056B5B1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Group__5120BCB8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Autho__514AD9EA] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Dimen__61F9A225] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Affec__66BE5742] DEFAULT ((0)) FOR [AffectedDataCount]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__IsRec__6DBF8F35] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__DateC__6DD56925] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__LastM__6EC98D5E] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

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

---------------------------------------------
-- fp.DepartmentChargeVolumeAdjustment_backup ------------------
---------------------------------------------
CREATE TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [FK__Departmen__Budge__6E120121] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__62A04E75] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__639472AE] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Value__648896E7] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__657CBB20] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Group__6670DF59] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__67650392] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Comme__685927CB] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Autho__694D4C04] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Autho__6A41703D] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__LastM__6B359476] DEFAULT (getdate()) FOR [LastModifiedDate]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__DateC__6C29B8AF] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Group__6D1DDCE8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

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

---------------------------------------------
-- fp.DepartmentConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[DepartmentConfig] (
    [DepartmentConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [UpdatedDate] datetime NOT NULL,
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [HasStatistics] bit NOT NULL,
    [HasRevenueAndDeductions] bit NOT NULL,
    [HasOtherRevenue] bit NOT NULL,
    [HasRoster] bit NOT NULL,
    [HasStaffing] bit NOT NULL,
    [HasBenefits] bit NOT NULL,
    [HasNonStaffingExpenses] bit NOT NULL,
    [HasZeroBasedExpenses] bit NOT NULL,
    PRIMARY KEY ([DepartmentConfigGUID])
);

CREATE NONCLUSTERED INDEX [NCNU_DepartmentConfig_DepartmentID] ON [fp].[DepartmentConfig] ([DepartmentID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentConfig_EntityGroupConfigGUID] ON [fp].[DepartmentConfig] ([EntityGroupConfigGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [UC_FP_DepartmentConfig_DeptID_EGC] ON [fp].[DepartmentConfig] ([DepartmentID], [EntityGroupConfigGUID]);
GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [FK__Departmen__Depar__2393C03C] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [FK__Departmen__Entit__3983015B] FOREIGN KEY ([EntityGroupConfigGUID]) REFERENCES [fp].[EntityGroupConfig] ([EntityGroupConfigGUID]); GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasZe__1B47F971] DEFAULT ((0)) FOR [HasZeroBasedExpenses]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__Depar__229F9C03] DEFAULT (newid()) FOR [DepartmentConfigGUID]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__Updat__257C08AE] DEFAULT ('1900-01-01') FOR [UpdatedDate]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasSt__3A772594] DEFAULT ((0)) FOR [HasStatistics]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasRe__3B6B49CD] DEFAULT ((0)) FOR [HasRevenueAndDeductions]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasOt__3C5F6E06] DEFAULT ((0)) FOR [HasOtherRevenue]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasRo__3D53923F] DEFAULT ((0)) FOR [HasRoster]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasSt__3E47B678] DEFAULT ((0)) FOR [HasStaffing]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasBe__3F3BDAB1] DEFAULT ((0)) FOR [HasBenefits]; GO
ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasNo__402FFEEA] DEFAULT ((0)) FOR [HasNonStaffingExpenses]; GO

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

---------------------------------------------
-- fp.DepartmentLevelConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[DepartmentLevelConfiguration] (
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [IsUsingProviderStats] bit NOT NULL,
    [IsUsingProviderStaffing] bit NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [DepartmentID])
);
GO
ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [FK_DepartmentLevelConfiguration_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__Budge__7868D188] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__Depar__795CF5C1] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__IsUsi__7A5119FA] DEFAULT ((0)) FOR [IsUsingProviderStats]; GO
ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__IsUsi__7B453E33] DEFAULT ((0)) FOR [IsUsingProviderStaffing]; GO

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

---------------------------------------------
-- fp.DependentStatisticsAccount ------------------
---------------------------------------------
CREATE TABLE [fp].[DependentStatisticsAccount] (
    [BudgetConfigID] int NOT NULL,
    [DependentAccountID] int NOT NULL,
    [DriverAccountID] int NOT NULL,
    [DependentStatisticsAccountID] int NOT NULL,
    [SourceDepartmentID] int NOT NULL,
    [SourceDepartmentPath] nvarchar(max) NOT NULL,
    [IsNewRecord] bit NOT NULL,
    PRIMARY KEY ([DependentStatisticsAccountID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[DependentStatisticsAccount] ([BudgetConfigID], [DependentAccountID], [DriverAccountID], [SourceDepartmentID]);
GO
ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [df_SourceDepartmentID] DEFAULT ((-1)) FOR [SourceDepartmentID]; GO
ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Sourc__0FB97890] DEFAULT ('') FOR [SourceDepartmentPath]; GO
ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__IsNew__35DFECCF] DEFAULT ((0)) FOR [IsNewRecord]; GO
ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Budge__611B57DC] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Depen__620F7C15] DEFAULT ((0)) FOR [DependentAccountID]; GO
ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Drive__6303A04E] DEFAULT ((0)) FOR [DriverAccountID]; GO

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

---------------------------------------------
-- fp.DependentStatisticsAccountDepartment ------------------
---------------------------------------------
CREATE TABLE [fp].[DependentStatisticsAccountDepartment] (
    [RowID] int NOT NULL,
    [DependentStatisticsAccountID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[DependentStatisticsAccountDepartment] ADD CONSTRAINT [FK_DependentStatisticsAccountDepartment_DependentStatisticsAccountID] FOREIGN KEY ([DependentStatisticsAccountID]) REFERENCES [fp].[DependentStatisticsAccount] ([DependentStatisticsAccountID]); GO
ALTER TABLE [fp].[DependentStatisticsAccountDepartment] ADD CONSTRAINT [DF__Dependent__Depen__1295E53B] DEFAULT ((0)) FOR [DependentStatisticsAccountID]; GO
ALTER TABLE [fp].[DependentStatisticsAccountDepartment] ADD CONSTRAINT [DF__Dependent__Depar__138A0974] DEFAULT ((0)) FOR [DepartmentID]; GO

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

---------------------------------------------
-- fp.DependentStatisticsAccountScoreDepartment ------------------
---------------------------------------------
CREATE TABLE [fp].[DependentStatisticsAccountScoreDepartment] (
    [RowID] int NOT NULL,
    [DependentStatisticsAccountID] int NOT NULL,
    [ScoreValue] nvarchar(max) NOT NULL,
    [Name] nvarchar(1000) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [FK_DependentStatisticsAccountScoreDepartment_DependentStatisticsAccountID] FOREIGN KEY ([DependentStatisticsAccountID]) REFERENCES [fp].[DependentStatisticsAccount] ([DependentStatisticsAccountID]); GO
ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [DF__Dependent__Depen__1B2B2B3C] DEFAULT ((0)) FOR [DependentStatisticsAccountID]; GO
ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [DF__Dependent__Score__1C1F4F75] DEFAULT ('') FOR [ScoreValue]; GO
ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [DF__DependentS__Name__1D1373AE] DEFAULT ('') FOR [Name]; GO

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

---------------------------------------------
-- fp.DimCategory ------------------
---------------------------------------------
CREATE TABLE [fp].[DimCategory] (
    [CategoryID] int NOT NULL,
    [Category] varchar(50) NOT NULL
);
GO
ALTER TABLE [fp].[DimCategory] ADD CONSTRAINT [DF__DimCatego__Categ__62BB1E39] DEFAULT ('') FOR [Category]; GO

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

---------------------------------------------
-- fp.DimItemizationDataType ------------------
---------------------------------------------
CREATE TABLE [fp].[DimItemizationDataType] (
    [ItemizationDataTypeID] int NOT NULL,
    [Name] nvarchar(100) NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ItemizationDataTypeID])
);
GO
ALTER TABLE [fp].[DimItemizationDataType] ADD CONSTRAINT [DF__DimItemiza__Name__50BAD2E1] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[DimItemizationDataType] ADD CONSTRAINT [DF__DimItemiz__Membe__51AEF71A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO

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

---------------------------------------------
-- fp.DimSubAccountCategory ------------------
---------------------------------------------
CREATE TABLE [fp].[DimSubAccountCategory] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [SubAccountCategoryID] int NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [CategoryRollUp] nvarchar(200) NOT NULL,
    [FullDescription] nvarchar(400) NOT NULL,
    [TransactionID] int NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SubAccountCategoryID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ_DimSubAccountCategory_Description] ON [fp].[DimSubAccountCategory] ([Description]);
GO
ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Histo__302F9E6C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Descr__3217E6DE] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Categ__330C0B17] DEFAULT ('') FOR [CategoryRollUp]; GO
ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__FullD__34002F50] DEFAULT ('') FOR [FullDescription]; GO
ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Trans__34F45389] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Membe__35E877C2] DEFAULT (newid()) FOR [MemberGUID]; GO

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

---------------------------------------------
-- fp.EmployeeBudgetingNewEmployee ------------------
---------------------------------------------
CREATE TABLE [fp].[EmployeeBudgetingNewEmployee] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [EmployeeNumber] nvarchar(400) NOT NULL,
    [FiscalYearID] smallint NULL,
    [EmployeeID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [HireDateUTC] datetime NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Budge__3DF21730] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Fisca__3EE63B69] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Comme__3FDA5FA2] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Emplo__40CE83DB] DEFAULT ('') FOR [EmployeeNumber]; GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Fisca__41C2A814] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Emplo__42B6CC4D] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__JobCo__43AAF086] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__HireD__449F14BF] DEFAULT (getutcdate()) FOR [HireDateUTC]; GO

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

---------------------------------------------
-- fp.EngineLog ------------------
---------------------------------------------
CREATE TABLE [fp].[EngineLog] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [StepID] int NOT NULL,
    [AttemptID] int NOT NULL,
    [StepName] nvarchar(300) NOT NULL,
    [ClassName] nvarchar(300) NOT NULL,
    [SourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [OptionsJSON] nvarchar(max) NOT NULL,
    [DateStarted] datetime NOT NULL,
    [DateEnded] datetime NOT NULL,
    [Status] tinyint NOT NULL,
    [ErrorMessage] nvarchar(max) NOT NULL,
    [StackTrace] nvarchar(max) NOT NULL,
    [AffectedDepartments] nvarchar(max) NOT NULL,
    [AffectedDepartmentCount] int NOT NULL,
    PRIMARY KEY ([RequestGUID], [AttemptID], [StepID])
);
GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Affec__54A3062D] DEFAULT ((0)) FOR [AffectedDepartmentCount]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Reque__6F1DC7C2] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__StepI__7011EBFB] DEFAULT ((0)) FOR [StepID]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Attem__71061034] DEFAULT ((0)) FOR [AttemptID]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__StepN__71FA346D] DEFAULT ('') FOR [StepName]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Class__72EE58A6] DEFAULT ('') FOR [ClassName]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Sourc__73E27CDF] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Optio__74D6A118] DEFAULT ('') FOR [OptionsJSON]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__DateS__75CAC551] DEFAULT ('1900-01-01T00:00:00') FOR [DateStarted]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__DateE__76BEE98A] DEFAULT ('1900-01-01T00:00:00') FOR [DateEnded]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Statu__77B30DC3] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Error__78A731FC] DEFAULT ('') FOR [ErrorMessage]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Stack__799B5635] DEFAULT ('') FOR [StackTrace]; GO
ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Affec__7A8F7A6E] DEFAULT ('') FOR [AffectedDepartments]; GO

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

---------------------------------------------
-- fp.EntityGroupConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[EntityGroupConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [Name] nvarchar(100) NULL,
    [Comments] nvarchar(1000) NULL,
    [AccountTimeClassID] tinyint NOT NULL,
    [AccountFiscalYearID] smallint NOT NULL,
    [PayrollTimeClassID] tinyint NOT NULL,
    [PayrollFiscalYearID] smallint NOT NULL,
    [ServiceLineEncounterTimeClassID] tinyint NOT NULL,
    [ServiceLineEncounterFiscalYearID] smallint NOT NULL,
    [DepartmentChargeVolumeTimeClassID] tinyint NOT NULL,
    [DepartmentChargeVolumeFiscalYearID] smallint NOT NULL,
    [AccountLastSampled] datetime NOT NULL,
    [PayrollLastSampled] datetime NOT NULL,
    [ServiceLineEncounterLastSampled] datetime NOT NULL,
    [DepartmentChargeVolumeLastSampled] datetime NOT NULL,
    [CostingConfigGUID] uniqueidentifier NOT NULL,
    [CostingConfigTimeClassID] tinyint NOT NULL,
    [DateModified] smalldatetime NULL,
    [DatePublished] smalldatetime NULL,
    [BenefitsTimeClassID] tinyint NOT NULL,
    [BenefitsFiscalYearID] smallint NOT NULL,
    [BenefitsLastSampled] datetime NOT NULL,
    [IsMarkedForDeletion] bit NOT NULL,
    [StatisticsTimeClassID] tinyint NOT NULL,
    [StatisticsFiscalYearID] smallint NOT NULL,
    [StatisticsLastSampled] datetime NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [IsBudgetLockDown] bit NOT NULL,
    [IsRosterUsed] bit NOT NULL,
    [StatisticsModel] smallint NOT NULL,
    [RevenueAndDeductionsTimeClassID] tinyint NOT NULL,
    [RevenueAndDeductionsFiscalYearID] smallint NOT NULL,
    [RevenueAndDeductionsLastSampled] datetime NOT NULL,
    [IsPatientActivityFlexingForStaffing] bit NOT NULL,
    [IsPatientActivityFlexingForNonStaffing] bit NOT NULL,
    [ParentEntityGroupConfigGuid] uniqueidentifier NOT NULL,
    [IsPayorGroupUsedForCrosswalk] bit NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID])
);
GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsRos__05843A68] DEFAULT ((0)) FOR [IsRosterUsed]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsMar__302C3F46] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Stati__321487B8] DEFAULT ((0)) FOR [StatisticsTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Stati__3308ABF1] DEFAULT ((0)) FOR [StatisticsFiscalYearID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Stati__33FCD02A] DEFAULT ('1/1/2000') FOR [StatisticsLastSampled]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Entit__3530202E] DEFAULT (newid()) FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Benef__369945B3] DEFAULT ((0)) FOR [BenefitsTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGrou__Name__371868A0] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Benef__378D69EC] DEFAULT ((0)) FOR [BenefitsFiscalYearID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Comme__380C8CD9] DEFAULT ('') FOR [Comments]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Benef__38818E25] DEFAULT ('1/1/2000') FOR [BenefitsLastSampled]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Accou__3900B112] DEFAULT ((0)) FOR [AccountTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Accou__39F4D54B] DEFAULT ((0)) FOR [AccountFiscalYearID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Payro__3AE8F984] DEFAULT ((0)) FOR [PayrollTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Payro__3BDD1DBD] DEFAULT ((0)) FOR [PayrollFiscalYearID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Servi__3CD141F6] DEFAULT ((0)) FOR [ServiceLineEncounterTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [df_EntityGroupConfig_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Servi__3DC5662F] DEFAULT ((0)) FOR [ServiceLineEncounterFiscalYearID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [df_EntityGroupConfig_CostingConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CostingConfigGUID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Depar__3EB98A68] DEFAULT ((0)) FOR [DepartmentChargeVolumeTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [df_EntityGroupConfig_ParentEntityGroupConfigGuid] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentEntityGroupConfigGuid]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Depar__3FADAEA1] DEFAULT ((0)) FOR [DepartmentChargeVolumeFiscalYearID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Accou__40A1D2DA] DEFAULT ('1/1/2000') FOR [AccountLastSampled]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Payro__4195F713] DEFAULT ('1/1/2000') FOR [PayrollLastSampled]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Servi__428A1B4C] DEFAULT ('1/1/2000') FOR [ServiceLineEncounterLastSampled]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsBud__430C6B95] DEFAULT ((0)) FOR [IsBudgetLockDown]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Depar__437E3F85] DEFAULT ('1/1/2000') FOR [DepartmentChargeVolumeLastSampled]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Costi__465AAC30] DEFAULT ((0)) FOR [CostingConfigTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__DateM__474ED069] DEFAULT (getdate()) FOR [DateModified]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__DateP__4842F4A2] DEFAULT (getdate()) FOR [DatePublished]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_StatisticsModel] DEFAULT ((0)) FOR [StatisticsModel]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsPay__53430528] DEFAULT ((0)) FOR [IsPayorGroupUsedForCrosswalk]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_RevenueAndDeductionsTimeClassID] DEFAULT ((0)) FOR [RevenueAndDeductionsTimeClassID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_RevenueAndDeductionsFiscalYearID] DEFAULT ((0)) FOR [RevenueAndDeductionsFiscalYearID]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_RevenueAndDeductionsLastSampled] DEFAULT ('1/1/2000') FOR [RevenueAndDeductionsLastSampled]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsPat__68E03C1E] DEFAULT ((0)) FOR [IsPatientActivityFlexingForStaffing]; GO
ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsPat__69D46057] DEFAULT ((0)) FOR [IsPatientActivityFlexingForNonStaffing]; GO

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

---------------------------------------------
-- fp.EntityGroupConfigMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[EntityGroupConfigMapping] (
    [RowID] int NOT NULL,
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[EntityGroupConfigMapping] ADD CONSTRAINT [df_EntityGroupConfigMapping_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[EntityGroupConfigMapping] ADD CONSTRAINT [DF__EntityGro__Entit__4C138586] DEFAULT ((0)) FOR [EntityID]; GO

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

---------------------------------------------
-- fp.ExecutiveSummary ------------------
---------------------------------------------
CREATE TABLE [fp].[ExecutiveSummary] (
    [ExecutiveSummaryGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [SummaryType] smallint NOT NULL,
    [DateModified] smalldatetime NOT NULL,
    [LastAuthorGUID] uniqueidentifier NOT NULL,
    [LastAuthorName] nvarchar(130) NOT NULL,
    [Comments] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ExecutiveSummaryGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_ExecutiveSummary] ON [fp].[ExecutiveSummary] ([BudgetConfigGUID], [DepartmentID], [SummaryType]);
GO

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

---------------------------------------------
-- fp.ExportHelpInfo ------------------
---------------------------------------------
CREATE TABLE [fp].[ExportHelpInfo] (
    [ExportTypeID] smallint NOT NULL,
    [ExportTypeName] varchar(50) NOT NULL,
    [ColumnName] varchar(50) NOT NULL,
    [ColumnDescription] varchar(200) NOT NULL,
    [DataFormat] varchar(100) NOT NULL,
    PRIMARY KEY ([ExportTypeID])
);
GO

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

---------------------------------------------
-- fp.FTERequest ------------------
---------------------------------------------
CREATE TABLE [fp].[FTERequest] (
    [FTERequestGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [FTEAmount] decimal NOT NULL,
    [StartFiscalMonthID] tinyint NOT NULL,
    [WageRate] decimal NOT NULL,
    [Comment] nvarchar(2000) NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([FTERequestGUID])
);
GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK__FTEReques__Budge__7EE78768] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK__FTEReques__Start__02B8184C] FOREIGN KEY ([StartFiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK_FTERequest_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK_FTERequest_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__FTEAm__01C3F413] DEFAULT ((0)) FOR [FTEAmount]; GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__WageR__03AC3C85] DEFAULT ((0)) FOR [WageRate]; GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__Group__04364C6A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__Comme__04A060BE] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__DateC__059484F7] DEFAULT ('1/1/1900') FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__FTERe__7DF3632F] DEFAULT (newid()) FOR [FTERequestGUID]; GO

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

---------------------------------------------
-- fp.FTERequestDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[FTERequestDetail] (
    [FTERequestDetailGUID] uniqueidentifier NOT NULL,
    [FTERequestGUID] uniqueidentifier NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [HoursMix] decimal NOT NULL,
    PRIMARY KEY ([FTERequestDetailGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_UNIQUE] ON [fp].[FTERequestDetail] ([FTERequestGUID], [PayCodeGroupID]);
GO
ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [FK__FTEReques__FTERe__16BF10F9] FOREIGN KEY ([FTERequestGUID]) REFERENCES [fp].[FTERequest] ([FTERequestGUID]); GO
ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [FK__FTEReques__PayCo__17B33532] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [DF__FTEReques__FTERe__15CAECC0] DEFAULT (newid()) FOR [FTERequestDetailGUID]; GO
ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [DF__FTEReques__Hours__344F73E0] DEFAULT ((0)) FOR [HoursMix]; GO

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

---------------------------------------------
-- fp.FactAccountVariability ------------------
---------------------------------------------
CREATE TABLE [fp].[FactAccountVariability] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FixedPercentage] decimal NOT NULL,
    [RowID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_FactAccountVariability] ON [fp].[FactAccountVariability] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]);
GO
ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [FK_FactAccountVariability_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [FK_FactAccountVariability_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_AccountID] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_FixedPercentage] DEFAULT ((0.0)) FOR [FixedPercentage]; GO

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

---------------------------------------------
-- fp.FactBenefits ------------------
---------------------------------------------
CREATE TABLE [fp].[FactBenefits] (
    [BenefitsID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FlexMethodID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([BenefitsID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[FactBenefits] ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_Account] ON [fp].[FactBenefits] ([AccountID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_BudgetConfigID] ON [fp].[FactBenefits] ([BudgetConfigID]) INCLUDE ([EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_EntityGroupConfigID] ON [fp].[FactBenefits] ([EntityGroupConfigID]) INCLUDE ([BudgetConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_EntityID] ON [fp].[FactBenefits] ([EntityID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_DepartmentID] ON [fp].[FactBenefits] ([DepartmentID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_FinacialReportingID] ON [fp].[FactBenefits] ([FinancialReportingID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_AccountID] ON [fp].[FactBenefits] ([AccountID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_BudgetConfig] ON [fp].[FactBenefits] ([BudgetConfigID]) INCLUDE ([BenefitsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_Department] ON [fp].[FactBenefits] ([DepartmentID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_Entity] ON [fp].[FactBenefits] ([EntityID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_EntityGroupConfig] ON [fp].[FactBenefits] ([EntityGroupConfigID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefits_FinancialReporting] ON [fp].[FactBenefits] ([FinancialReportingID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [UnitTypeID]);
GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Budge__253F3EE8] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Entit__26336321] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Entit__2727875A] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Depar__281BAB93] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Accou__290FCFCC] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Finan__2A03F405] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__UnitT__2AF8183E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__FlexM__2BEC3C77] DEFAULT ((0)) FOR [FlexMethodID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__2DD484E9] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__2EC8A922] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__2FBCCD5B] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__30B0F194] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__IsNew__315AFD0A] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__31A515CD] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__32993A06] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__338D5E3F] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__34818278] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF_benefits_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3575A6B1] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3669CAEA] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__375DEF23] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3852135C] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__39463795] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3A3A5BCE] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3B2E8007] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3C22A440] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Chang__3D123639] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3D16C879] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3E0AECB2] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3EFF10EB] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3FF33524] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__40E7595D] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__41DB7D96] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__42CFA1CF] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__43C3C608] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__44B7EA41] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__45AC0E7A] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__46A032B3] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__479456EC] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__48887B25] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__497C9F5E] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4A70C397] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4B64E7D0] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4C590C09] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4D4D3042] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4E41547B] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4F3578B4] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__50299CED] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__511DC126] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__5211E55F] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__53060998] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__53FA2DD1] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__54EE520A] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__55E27643] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__56D69A7C] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__57CABEB5] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__58BEE2EE] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__59B30727] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__5AA72B60] DEFAULT ((0)) FOR [InitialProjection12]; GO

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

---------------------------------------------
-- fp.FactBenefitsBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[FactBenefitsBudget] (
    [RowID] int NOT NULL,
    [BenefitsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactBenefitsBudget] ON [fp].[FactBenefitsBudget] ([BenefitsID], [BudgetPhaseID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefitsBudget_BudgetPhaseID] ON [fp].[FactBenefitsBudget] ([BudgetPhaseID], [BenefitsID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactBenefitsBudget] ([BenefitsID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [FK_FactBenefitsBudget_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Benef__5D83980B] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__LockT__5E77BC44] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__LockF__5F6BE07D] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Budge__606004B6] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__615428EF] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__62484D28] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__633C7161] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6430959A] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6524B9D3] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6618DE0C] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__670D0245] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6801267E] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__68F54AB7] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__69E96EF0] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6ADD9329] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6BD1B762] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6CC5DB9B] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6DB9FFD4] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6EAE240D] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6FA24846] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__70966C7F] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__718A90B8] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__727EB4F1] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__7372D92A] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__7466FD63] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__755B219C] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__764F45D5] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__77436A0E] DEFAULT ((0)) FOR [FlexedValue12]; GO

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

---------------------------------------------
-- fp.FactBenefitsHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactBenefitsHistory] (
    [RowID] int NOT NULL,
    [BenefitsID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactBenefitsHistory] ON [fp].[FactBenefitsHistory] ([BenefitsID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactBenefitsHistory] ([BenefitsID]);
GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [FK_FactBenefitsHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Benef__1A8CA64B] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1B80CA84] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1C74EEBD] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1D6912F6] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1E5D372F] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1F515B68] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__20457FA1] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__2139A3DA] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__222DC813] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__2321EC4C] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__24161085] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__250A34BE] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__25FE58F7] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__26F27D30] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__27E6A169] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__28DAC5A2] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__29CEE9DB] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2AC30E14] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2BB7324D] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2CAB5686] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2D9F7ABF] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2E939EF8] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2F87C331] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__307BE76A] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__31700BA3] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__32642FDC] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__33585415] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__344C784E] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__35409C87] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3634C0C0] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3728E4F9] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__381D0932] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__39112D6B] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3A0551A4] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3AF975DD] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3BED9A16] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3CE1BE4F] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.FactBenefitsProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[FactBenefitsProjection] (
    [RowID] int NOT NULL,
    [BenefitsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [FlexedValue01] decimal NOT NULL,
    [FlexedValue02] decimal NOT NULL,
    [FlexedValue03] decimal NOT NULL,
    [FlexedValue04] decimal NOT NULL,
    [FlexedValue05] decimal NOT NULL,
    [FlexedValue06] decimal NOT NULL,
    [FlexedValue07] decimal NOT NULL,
    [FlexedValue08] decimal NOT NULL,
    [FlexedValue09] decimal NOT NULL,
    [FlexedValue10] decimal NOT NULL,
    [FlexedValue11] decimal NOT NULL,
    [FlexedValue12] decimal NOT NULL,
    [FlexedValueTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactBenefitsProjection] ON [fp].[FactBenefitsProjection] ([BenefitsID], [BudgetPhaseID]);
CREATE NONCLUSTERED INDEX [IX_FactBenefitsBudget_BudgetPhaseID] ON [fp].[FactBenefitsProjection] ([BudgetPhaseID], [BenefitsID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactBenefitsProjection] ([BenefitsID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [FK_FactBenefitsProjection_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__00CCD448] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__01C0F881] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__02B51CBA] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__03A940F3] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__049D652C] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__05918965] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__0685AD9E] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__0779D1D7] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__086DF610] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__09621A49] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0A563E82] DEFAULT ((0)) FOR [FlexedValue01]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0B4A62BB] DEFAULT ((0)) FOR [FlexedValue02]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0C3E86F4] DEFAULT ((0)) FOR [FlexedValue03]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0D32AB2D] DEFAULT ((0)) FOR [FlexedValue04]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0E26CF66] DEFAULT ((0)) FOR [FlexedValue05]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0F1AF39F] DEFAULT ((0)) FOR [FlexedValue06]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__100F17D8] DEFAULT ((0)) FOR [FlexedValue07]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__11033C11] DEFAULT ((0)) FOR [FlexedValue08]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__11F7604A] DEFAULT ((0)) FOR [FlexedValue09]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__12EB8483] DEFAULT ((0)) FOR [FlexedValue10]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__13DFA8BC] DEFAULT ((0)) FOR [FlexedValue11]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__14D3CCF5] DEFAULT ((0)) FOR [FlexedValue12]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Benef__7B13FAF2] DEFAULT ((0)) FOR [BenefitsID]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__LockT__7C081F2B] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__LockF__7CFC4364] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Budge__7DF0679D] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__7EE48BD6] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__7FD8B00F] DEFAULT ((0)) FOR [AdjustedValue02]; GO

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

---------------------------------------------
-- fp.FactChargeMaster ------------------
---------------------------------------------
CREATE TABLE [fp].[FactChargeMaster] (
    [RowID] int NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ChargeRate1] decimal NOT NULL,
    [ChargeRate2] decimal NOT NULL,
    [ChargeRate3] decimal NOT NULL,
    [ChargeRate4] decimal NOT NULL,
    [BaselineChargeRate] decimal NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [IX_FactChargeMaster_BudgetConfigID] ON [fp].[FactChargeMaster] ([BudgetConfigID]) INCLUDE ([ChargeCodeID], [ChargeRate1]);
CREATE NONCLUSTERED INDEX [IX_FactChargeMaster_BudgetConfigIDChargeCodeID] ON [fp].[FactChargeMaster] ([BudgetConfigID], [ChargeCodeID]) INCLUDE ([ChargeRate1]);
GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [FK_ChargeMaster_ChargeCode] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [FK_ChargeMaster_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [FK_ChargeMaster_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Basel__07EA0F19] DEFAULT ((0)) FOR [BaselineChargeRate]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Budge__1EEA42A6] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [df_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Entit__1FDE66DF] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Patie__21C6AF51] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__23AEF7C3] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__25974035] DEFAULT ((0)) FOR [ChargeRate1]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__268B646E] DEFAULT ((0)) FOR [ChargeRate2]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__277F88A7] DEFAULT ((0)) FOR [ChargeRate3]; GO
ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__2873ACE0] DEFAULT ((0)) FOR [ChargeRate4]; GO

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

---------------------------------------------
-- fp.FactGeneralLedgerInitiative ------------------
---------------------------------------------
CREATE TABLE [fp].[FactGeneralLedgerInitiative] (
    [RowID] int NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [InitiativeForecast01] decimal NOT NULL,
    [InitiativeForecast02] decimal NOT NULL,
    [InitiativeForecast03] decimal NOT NULL,
    [InitiativeForecast04] decimal NOT NULL,
    [InitiativeForecast05] decimal NOT NULL,
    [InitiativeForecast06] decimal NOT NULL,
    [InitiativeForecast07] decimal NOT NULL,
    [InitiativeForecast08] decimal NOT NULL,
    [InitiativeForecast09] decimal NOT NULL,
    [InitiativeForecast10] decimal NOT NULL,
    [InitiativeForecast11] decimal NOT NULL,
    [InitiativeForecast12] decimal NOT NULL,
    [InitiativeForecastTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_FactGeneralLedgerInitiative_GeneralLedgerID] ON [fp].[FactGeneralLedgerInitiative] ([GeneralLedgerID]);
GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [FK_FactGeneralLedgerInitiative_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[GeneralLedger] ([GeneralLedgerID]); GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Gener__15FC61CB] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__16F08604] DEFAULT ((0)) FOR [InitiativeForecast01]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__17E4AA3D] DEFAULT ((0)) FOR [InitiativeForecast02]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__18D8CE76] DEFAULT ((0)) FOR [InitiativeForecast03]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__19CCF2AF] DEFAULT ((0)) FOR [InitiativeForecast04]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1AC116E8] DEFAULT ((0)) FOR [InitiativeForecast05]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1BB53B21] DEFAULT ((0)) FOR [InitiativeForecast06]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1CA95F5A] DEFAULT ((0)) FOR [InitiativeForecast07]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1D9D8393] DEFAULT ((0)) FOR [InitiativeForecast08]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1E91A7CC] DEFAULT ((0)) FOR [InitiativeForecast09]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1F85CC05] DEFAULT ((0)) FOR [InitiativeForecast10]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__2079F03E] DEFAULT ((0)) FOR [InitiativeForecast11]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__216E1477] DEFAULT ((0)) FOR [InitiativeForecast12]; GO

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

---------------------------------------------
-- fp.FactGeneralLedgerInitiative_OLD ------------------
---------------------------------------------
CREATE TABLE [fp].[FactGeneralLedgerInitiative_OLD] (
    [RowID] int NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [InitiativeForecast01] decimal NOT NULL,
    [InitiativeForecast02] decimal NOT NULL,
    [InitiativeForecast03] decimal NOT NULL,
    [InitiativeForecast04] decimal NOT NULL,
    [InitiativeForecast05] decimal NOT NULL,
    [InitiativeForecast06] decimal NOT NULL,
    [InitiativeForecast07] decimal NOT NULL,
    [InitiativeForecast08] decimal NOT NULL,
    [InitiativeForecast09] decimal NOT NULL,
    [InitiativeForecast10] decimal NOT NULL,
    [InitiativeForecast11] decimal NOT NULL,
    [InitiativeForecast12] decimal NOT NULL,
    [InitiativeForecastTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_GeneralLedgerID] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast01] DEFAULT ((0)) FOR [InitiativeForecast01]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast02] DEFAULT ((0)) FOR [InitiativeForecast02]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast03] DEFAULT ((0)) FOR [InitiativeForecast03]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast04] DEFAULT ((0)) FOR [InitiativeForecast04]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast05] DEFAULT ((0)) FOR [InitiativeForecast05]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast06] DEFAULT ((0)) FOR [InitiativeForecast06]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast07] DEFAULT ((0)) FOR [InitiativeForecast07]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast08] DEFAULT ((0)) FOR [InitiativeForecast08]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast09] DEFAULT ((0)) FOR [InitiativeForecast09]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast10] DEFAULT ((0)) FOR [InitiativeForecast10]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast11] DEFAULT ((0)) FOR [InitiativeForecast11]; GO
ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast12] DEFAULT ((0)) FOR [InitiativeForecast12]; GO

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

---------------------------------------------
-- fp.FactISReportStatistics ------------------
---------------------------------------------
CREATE TABLE [fp].[FactISReportStatistics] (
    [BudgetConfigID] int NULL,
    [DepartmentID] int NULL,
    [AccountID] int NULL,
    [FinancialReportingID] int NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] int NULL,
    [TimeClassID] int NULL,
    [Amount] decimal NULL,
    [YTD] decimal NULL,
    [Yearly] decimal NULL,
    [Total] decimal NULL
);

CREATE CLUSTERED INDEX [idx_FactISReportStatistics] ON [fp].[FactISReportStatistics] ([FiscalYearID], [BudgetConfigID], [FiscalMonthID], [DepartmentID], [AccountID], [TimeClassID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactISReportStatistics] ([DepartmentID]);
GO

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

---------------------------------------------
-- fp.FactReimbursementCharges ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementCharges] (
    [ReimbursementChargesID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [AddDate] datetime NOT NULL,
    [InitialBudgetChargeDollars01] decimal NOT NULL,
    [InitialBudgetChargeDollars02] decimal NOT NULL,
    [InitialBudgetChargeDollars03] decimal NOT NULL,
    [InitialBudgetChargeDollars04] decimal NOT NULL,
    [InitialBudgetChargeDollars05] decimal NOT NULL,
    [InitialBudgetChargeDollars06] decimal NOT NULL,
    [InitialBudgetChargeDollars07] decimal NOT NULL,
    [InitialBudgetChargeDollars08] decimal NOT NULL,
    [InitialBudgetChargeDollars09] decimal NOT NULL,
    [InitialBudgetChargeDollars10] decimal NOT NULL,
    [InitialBudgetChargeDollars11] decimal NOT NULL,
    [InitialBudgetChargeDollars12] decimal NOT NULL,
    [InitialBudgetChargeDollarsTotal] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge01] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge02] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge03] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge04] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge05] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge06] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge07] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge08] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge09] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge10] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge11] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge12] decimal NOT NULL,
    [InitialBudgetNetPerDiem01] decimal NOT NULL,
    [InitialBudgetNetPerDiem02] decimal NOT NULL,
    [InitialBudgetNetPerDiem03] decimal NOT NULL,
    [InitialBudgetNetPerDiem04] decimal NOT NULL,
    [InitialBudgetNetPerDiem05] decimal NOT NULL,
    [InitialBudgetNetPerDiem06] decimal NOT NULL,
    [InitialBudgetNetPerDiem07] decimal NOT NULL,
    [InitialBudgetNetPerDiem08] decimal NOT NULL,
    [InitialBudgetNetPerDiem09] decimal NOT NULL,
    [InitialBudgetNetPerDiem10] decimal NOT NULL,
    [InitialBudgetNetPerDiem11] decimal NOT NULL,
    [InitialBudgetNetPerDiem12] decimal NOT NULL,
    [InitialProjectionChargeDollars01] decimal NOT NULL,
    [InitialProjectionChargeDollars02] decimal NOT NULL,
    [InitialProjectionChargeDollars03] decimal NOT NULL,
    [InitialProjectionChargeDollars04] decimal NOT NULL,
    [InitialProjectionChargeDollars05] decimal NOT NULL,
    [InitialProjectionChargeDollars06] decimal NOT NULL,
    [InitialProjectionChargeDollars07] decimal NOT NULL,
    [InitialProjectionChargeDollars08] decimal NOT NULL,
    [InitialProjectionChargeDollars09] decimal NOT NULL,
    [InitialProjectionChargeDollars10] decimal NOT NULL,
    [InitialProjectionChargeDollars11] decimal NOT NULL,
    [InitialProjectionChargeDollars12] decimal NOT NULL,
    [InitialProjectionChargeDollarsTotal] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge01] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge02] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge03] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge04] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge05] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge06] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge07] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge08] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge09] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge10] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge11] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge12] decimal NOT NULL,
    [InitialProjectionNetPerDiem01] decimal NOT NULL,
    [InitialProjectionNetPerDiem02] decimal NOT NULL,
    [InitialProjectionNetPerDiem03] decimal NOT NULL,
    [InitialProjectionNetPerDiem04] decimal NOT NULL,
    [InitialProjectionNetPerDiem05] decimal NOT NULL,
    [InitialProjectionNetPerDiem06] decimal NOT NULL,
    [InitialProjectionNetPerDiem07] decimal NOT NULL,
    [InitialProjectionNetPerDiem08] decimal NOT NULL,
    [InitialProjectionNetPerDiem09] decimal NOT NULL,
    [InitialProjectionNetPerDiem10] decimal NOT NULL,
    [InitialProjectionNetPerDiem11] decimal NOT NULL,
    [InitialProjectionNetPerDiem12] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    [InitialBudgetNetReimbursement01] decimal NOT NULL,
    [InitialBudgetNetReimbursement02] decimal NOT NULL,
    [InitialBudgetNetReimbursement03] decimal NOT NULL,
    [InitialBudgetNetReimbursement04] decimal NOT NULL,
    [InitialBudgetNetReimbursement05] decimal NOT NULL,
    [InitialBudgetNetReimbursement06] decimal NOT NULL,
    [InitialBudgetNetReimbursement07] decimal NOT NULL,
    [InitialBudgetNetReimbursement08] decimal NOT NULL,
    [InitialBudgetNetReimbursement09] decimal NOT NULL,
    [InitialBudgetNetReimbursement10] decimal NOT NULL,
    [InitialBudgetNetReimbursement11] decimal NOT NULL,
    [InitialBudgetNetReimbursement12] decimal NOT NULL,
    [InitialProjectionNetReimbursement01] decimal NOT NULL,
    [InitialProjectionNetReimbursement02] decimal NOT NULL,
    [InitialProjectionNetReimbursement03] decimal NOT NULL,
    [InitialProjectionNetReimbursement04] decimal NOT NULL,
    [InitialProjectionNetReimbursement05] decimal NOT NULL,
    [InitialProjectionNetReimbursement06] decimal NOT NULL,
    [InitialProjectionNetReimbursement07] decimal NOT NULL,
    [InitialProjectionNetReimbursement08] decimal NOT NULL,
    [InitialProjectionNetReimbursement09] decimal NOT NULL,
    [InitialProjectionNetReimbursement10] decimal NOT NULL,
    [InitialProjectionNetReimbursement11] decimal NOT NULL,
    [InitialProjectionNetReimbursement12] decimal NOT NULL,
    PRIMARY KEY ([ReimbursementChargesID])
);

CREATE UNIQUE NONCLUSTERED INDEX [CORE_FactReimbursementChargesUnique] ON [fp].[FactReimbursementCharges] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID]);
GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_CPT] FOREIGN KEY ([PrimaryCPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Budge__09A9377A] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Entit__0A9D5BB3] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Entit__0B917FEC] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Patie__0C85A425] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Servi__0D79C85E] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Servi__0E6DEC97] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Medic__0F6210D0] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Payor__114A5942] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Payor__123E7D7B] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__MSDRG__1332A1B4] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Prima__1426C5ED] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__UBRev__151AEA26] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF_ReimbursementCharges_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__17F756D1] DEFAULT ((0)) FOR [InitialBudgetChargeDollars01]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__18EB7B0A] DEFAULT ((0)) FOR [InitialBudgetChargeDollars02]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__19DF9F43] DEFAULT ((0)) FOR [InitialBudgetChargeDollars03]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1AD3C37C] DEFAULT ((0)) FOR [InitialBudgetChargeDollars04]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1BC7E7B5] DEFAULT ((0)) FOR [InitialBudgetChargeDollars05]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1CBC0BEE] DEFAULT ((0)) FOR [InitialBudgetChargeDollars06]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1DB03027] DEFAULT ((0)) FOR [InitialBudgetChargeDollars07]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1EA45460] DEFAULT ((0)) FOR [InitialBudgetChargeDollars08]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1F987899] DEFAULT ((0)) FOR [InitialBudgetChargeDollars09]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__208C9CD2] DEFAULT ((0)) FOR [InitialBudgetChargeDollars10]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2180C10B] DEFAULT ((0)) FOR [InitialBudgetChargeDollars11]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2274E544] DEFAULT ((0)) FOR [InitialBudgetChargeDollars12]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2EDABC29] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2FCEE062] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__30C3049B] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__31B728D4] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__32AB4D0D] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__339F7146] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3493957F] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3587B9B8] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__367BDDF1] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3770022A] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__38642663] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__39584A9C] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3A4C6ED5] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem01]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3B40930E] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem02]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3C34B747] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem03]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3D28DB80] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem04]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3E1CFFB9] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem05]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3F1123F2] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem06]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4005482B] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem07]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__40F96C64] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem08]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__41ED909D] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem09]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__42E1B4D6] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem10]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__43D5D90F] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem11]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__44C9FD48] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem12]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__45BE2181] DEFAULT ((0)) FOR [InitialProjectionChargeDollars01]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__46B245BA] DEFAULT ((0)) FOR [InitialProjectionChargeDollars02]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__47A669F3] DEFAULT ((0)) FOR [InitialProjectionChargeDollars03]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__489A8E2C] DEFAULT ((0)) FOR [InitialProjectionChargeDollars04]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__498EB265] DEFAULT ((0)) FOR [InitialProjectionChargeDollars05]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4A82D69E] DEFAULT ((0)) FOR [InitialProjectionChargeDollars06]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4B76FAD7] DEFAULT ((0)) FOR [InitialProjectionChargeDollars07]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4C6B1F10] DEFAULT ((0)) FOR [InitialProjectionChargeDollars08]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4D5F4349] DEFAULT ((0)) FOR [InitialProjectionChargeDollars09]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4E536782] DEFAULT ((0)) FOR [InitialProjectionChargeDollars10]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4F478BBB] DEFAULT ((0)) FOR [InitialProjectionChargeDollars11]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__503BAFF4] DEFAULT ((0)) FOR [InitialProjectionChargeDollars12]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5CA186D9] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5D95AB12] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5E89CF4B] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5F7DF384] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__607217BD] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__61663BF6] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__625A602F] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__634E8468] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6442A8A1] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6536CCDA] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__662AF113] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__671F154C] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__68133985] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem01]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__69075DBE] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem02]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__69FB81F7] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem03]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6AEFA630] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem04]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6BE3CA69] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem05]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6CD7EEA2] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem06]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6DCC12DB] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem07]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6EC03714] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem08]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6FB45B4D] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem09]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__70A87F86] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem10]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__719CA3BF] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem11]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__7290C7F8] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem12]; GO
ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__IsNew__7384EC31] DEFAULT ((0)) FOR [IsNew]; GO

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

---------------------------------------------
-- fp.FactReimbursementChargesBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementChargesBudget] (
    [RowID] int NOT NULL,
    [ReimbursementChargesID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedChargeDollars01] decimal NOT NULL,
    [AdjustedChargeDollars02] decimal NOT NULL,
    [AdjustedChargeDollars03] decimal NOT NULL,
    [AdjustedChargeDollars04] decimal NOT NULL,
    [AdjustedChargeDollars05] decimal NOT NULL,
    [AdjustedChargeDollars06] decimal NOT NULL,
    [AdjustedChargeDollars07] decimal NOT NULL,
    [AdjustedChargeDollars08] decimal NOT NULL,
    [AdjustedChargeDollars09] decimal NOT NULL,
    [AdjustedChargeDollars10] decimal NOT NULL,
    [AdjustedChargeDollars11] decimal NOT NULL,
    [AdjustedChargeDollars12] decimal NOT NULL,
    [AdjustedChargeDollarsTotal] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge01] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge02] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge03] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge04] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge05] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge06] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge07] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge08] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge09] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge10] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge11] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge12] decimal NOT NULL,
    [AdjustedNetPerDiem01] decimal NOT NULL,
    [AdjustedNetPerDiem02] decimal NOT NULL,
    [AdjustedNetPerDiem03] decimal NOT NULL,
    [AdjustedNetPerDiem04] decimal NOT NULL,
    [AdjustedNetPerDiem05] decimal NOT NULL,
    [AdjustedNetPerDiem06] decimal NOT NULL,
    [AdjustedNetPerDiem07] decimal NOT NULL,
    [AdjustedNetPerDiem08] decimal NOT NULL,
    [AdjustedNetPerDiem09] decimal NOT NULL,
    [AdjustedNetPerDiem10] decimal NOT NULL,
    [AdjustedNetPerDiem11] decimal NOT NULL,
    [AdjustedNetPerDiem12] decimal NOT NULL,
    [AdjustedNetReimbursementValue01] decimal NOT NULL,
    [AdjustedNetReimbursementValue02] decimal NOT NULL,
    [AdjustedNetReimbursementValue03] decimal NOT NULL,
    [AdjustedNetReimbursementValue04] decimal NOT NULL,
    [AdjustedNetReimbursementValue05] decimal NOT NULL,
    [AdjustedNetReimbursementValue06] decimal NOT NULL,
    [AdjustedNetReimbursementValue07] decimal NOT NULL,
    [AdjustedNetReimbursementValue08] decimal NOT NULL,
    [AdjustedNetReimbursementValue09] decimal NOT NULL,
    [AdjustedNetReimbursementValue10] decimal NOT NULL,
    [AdjustedNetReimbursementValue11] decimal NOT NULL,
    [AdjustedNetReimbursementValue12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [FK_FactReimbursementChargesBudget_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Reimb__24B23371] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__LockT__25A657AA] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__LockF__269A7BE3] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Budge__278EA01C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2882C455] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2976E88E] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2A6B0CC7] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2B5F3100] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2C535539] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2D477972] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2E3B9DAB] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2F2FC1E4] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3023E61D] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__31180A56] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__320C2E8F] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__330052C8] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3F6629AD] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__405A4DE6] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__414E721F] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__42429658] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4336BA91] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__442ADECA] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__451F0303] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4613273C] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__47074B75] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__47FB6FAE] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__48EF93E7] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__49E3B820] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4AD7DC59] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4BCC0092] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4CC024CB] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4DB44904] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4EA86D3D] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4F9C9176] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__5090B5AF] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__5184D9E8] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__5278FE21] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__536D225A] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__54614693] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO
ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__55556ACC] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO

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

---------------------------------------------
-- fp.FactReimbursementChargesHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementChargesHistory] (
    [RowID] int NOT NULL,
    [ReimbursementChargesID] int NOT NULL,
    [PriorYearActualChargeDollars01] decimal NOT NULL,
    [PriorYearActualChargeDollars02] decimal NOT NULL,
    [PriorYearActualChargeDollars03] decimal NOT NULL,
    [PriorYearActualChargeDollars04] decimal NOT NULL,
    [PriorYearActualChargeDollars05] decimal NOT NULL,
    [PriorYearActualChargeDollars06] decimal NOT NULL,
    [PriorYearActualChargeDollars07] decimal NOT NULL,
    [PriorYearActualChargeDollars08] decimal NOT NULL,
    [PriorYearActualChargeDollars09] decimal NOT NULL,
    [PriorYearActualChargeDollars10] decimal NOT NULL,
    [PriorYearActualChargeDollars11] decimal NOT NULL,
    [PriorYearActualChargeDollars12] decimal NOT NULL,
    [PriorYearActualChargeDollarsTotal] decimal NOT NULL,
    [ActualYTDChargeDollars01] decimal NOT NULL,
    [ActualYTDChargeDollars02] decimal NOT NULL,
    [ActualYTDChargeDollars03] decimal NOT NULL,
    [ActualYTDChargeDollars04] decimal NOT NULL,
    [ActualYTDChargeDollars05] decimal NOT NULL,
    [ActualYTDChargeDollars06] decimal NOT NULL,
    [ActualYTDChargeDollars07] decimal NOT NULL,
    [ActualYTDChargeDollars08] decimal NOT NULL,
    [ActualYTDChargeDollars09] decimal NOT NULL,
    [ActualYTDChargeDollars10] decimal NOT NULL,
    [ActualYTDChargeDollars11] decimal NOT NULL,
    [ActualYTDChargeDollars12] decimal NOT NULL,
    [ActualYTDChargeDollarsTotal] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars01] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars02] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars03] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars04] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars05] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars06] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars07] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars08] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars09] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars10] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars11] decimal NOT NULL,
    [CurrentYearBudgetChargeDollars12] decimal NOT NULL,
    [CurrentYearBudgetChargeDollarsTotal] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits01] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits02] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits03] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits04] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits05] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits06] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits07] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits08] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits09] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits10] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits11] decimal NOT NULL,
    [CurrentYearBudgetChargeUnits12] decimal NOT NULL,
    [CurrentYearBudgetChargeUnitsTotal] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge01] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge02] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge03] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge04] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge05] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge06] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge07] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge08] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge09] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge10] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge11] decimal NOT NULL,
    [PriorYearActualNetAsPercentOfCharge12] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge01] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge02] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge03] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge04] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge05] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge06] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge07] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge08] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge09] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge10] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge11] decimal NOT NULL,
    [ActualYTDNetAsPercentOfCharge12] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge01] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge02] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge03] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge04] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge05] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge06] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge07] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge08] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge09] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge10] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge11] decimal NOT NULL,
    [CurrentYearBudgetNetAsPercentOfCharge12] decimal NOT NULL,
    [PriorYearActualNetPerDiem01] decimal NOT NULL,
    [PriorYearActualNetPerDiem02] decimal NOT NULL,
    [PriorYearActualNetPerDiem03] decimal NOT NULL,
    [PriorYearActualNetPerDiem04] decimal NOT NULL,
    [PriorYearActualNetPerDiem05] decimal NOT NULL,
    [PriorYearActualNetPerDiem06] decimal NOT NULL,
    [PriorYearActualNetPerDiem07] decimal NOT NULL,
    [PriorYearActualNetPerDiem08] decimal NOT NULL,
    [PriorYearActualNetPerDiem09] decimal NOT NULL,
    [PriorYearActualNetPerDiem10] decimal NOT NULL,
    [PriorYearActualNetPerDiem11] decimal NOT NULL,
    [PriorYearActualNetPerDiem12] decimal NOT NULL,
    [ActualYTDNetPerDiem01] decimal NOT NULL,
    [ActualYTDNetPerDiem02] decimal NOT NULL,
    [ActualYTDNetPerDiem03] decimal NOT NULL,
    [ActualYTDNetPerDiem04] decimal NOT NULL,
    [ActualYTDNetPerDiem05] decimal NOT NULL,
    [ActualYTDNetPerDiem06] decimal NOT NULL,
    [ActualYTDNetPerDiem07] decimal NOT NULL,
    [ActualYTDNetPerDiem08] decimal NOT NULL,
    [ActualYTDNetPerDiem09] decimal NOT NULL,
    [ActualYTDNetPerDiem10] decimal NOT NULL,
    [ActualYTDNetPerDiem11] decimal NOT NULL,
    [ActualYTDNetPerDiem12] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem01] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem02] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem03] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem04] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem05] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem06] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem07] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem08] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem09] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem10] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem11] decimal NOT NULL,
    [CurrentYearBudgetNetPerDiem12] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue01] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue02] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue03] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue04] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue05] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue06] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue07] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue08] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue09] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue10] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue11] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue12] decimal NOT NULL,
    [ActualYTDNetReimbursementValue01] decimal NOT NULL,
    [ActualYTDNetReimbursementValue02] decimal NOT NULL,
    [ActualYTDNetReimbursementValue03] decimal NOT NULL,
    [ActualYTDNetReimbursementValue04] decimal NOT NULL,
    [ActualYTDNetReimbursementValue05] decimal NOT NULL,
    [ActualYTDNetReimbursementValue06] decimal NOT NULL,
    [ActualYTDNetReimbursementValue07] decimal NOT NULL,
    [ActualYTDNetReimbursementValue08] decimal NOT NULL,
    [ActualYTDNetReimbursementValue09] decimal NOT NULL,
    [ActualYTDNetReimbursementValue10] decimal NOT NULL,
    [ActualYTDNetReimbursementValue11] decimal NOT NULL,
    [ActualYTDNetReimbursementValue12] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget01] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget02] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget03] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget04] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget05] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget06] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget07] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget08] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget09] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget10] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget11] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [FK_FactReimbursementChargesHistory_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__000ABEA7] DEFAULT ((0)) FOR [PriorYearActualChargeDollars07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__00C9D8B6] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__00FEE2E0] DEFAULT ((0)) FOR [PriorYearActualChargeDollars08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__01BDFCEF] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__01F30719] DEFAULT ((0)) FOR [PriorYearActualChargeDollars09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__02B22128] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__02E72B52] DEFAULT ((0)) FOR [PriorYearActualChargeDollars10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__03DB4F8B] DEFAULT ((0)) FOR [PriorYearActualChargeDollars11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__04CF73C4] DEFAULT ((0)) FOR [PriorYearActualChargeDollars12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__05C397FD] DEFAULT ((0)) FOR [ActualYTDChargeDollars01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__06B7BC36] DEFAULT ((0)) FOR [ActualYTDChargeDollars02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__07ABE06F] DEFAULT ((0)) FOR [ActualYTDChargeDollars03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__08A004A8] DEFAULT ((0)) FOR [ActualYTDChargeDollars04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__099428E1] DEFAULT ((0)) FOR [ActualYTDChargeDollars05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0A884D1A] DEFAULT ((0)) FOR [ActualYTDChargeDollars06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0B7C7153] DEFAULT ((0)) FOR [ActualYTDChargeDollars07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0C70958C] DEFAULT ((0)) FOR [ActualYTDChargeDollars08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0D64B9C5] DEFAULT ((0)) FOR [ActualYTDChargeDollars09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0E58DDFE] DEFAULT ((0)) FOR [ActualYTDChargeDollars10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0F4D0237] DEFAULT ((0)) FOR [ActualYTDChargeDollars11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__10412670] DEFAULT ((0)) FOR [ActualYTDChargeDollars12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__11354AA9] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__12296EE2] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__131D931B] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1411B754] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1505DB8D] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__15F9FFC6] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__16EE23FF] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__17E24838] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__18D66C71] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__19CA90AA] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1ABEB4E3] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1BB2D91C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__338A62AD] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__347E86E6] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3572AB1F] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3666CF58] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__375AF391] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__384F17CA] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__39433C03] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3A37603C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3B2B8475] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3C1FA8AE] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3D13CCE7] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3E07F120] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3EFC1559] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3FF03992] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__40E45DCB] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__41D88204] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__42CCA63D] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__43C0CA76] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__44B4EEAF] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__45A912E8] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__469D3721] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__47915B5A] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__48857F93] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__4979A3CC] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4A6DC805] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4B61EC3E] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4C561077] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4D4A34B0] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4E3E58E9] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4F327D22] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__5026A15B] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__511AC594] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__520EE9CD] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__53030E06] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__53F7323F] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__54EB5678] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__55DF7AB1] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__56D39EEA] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__57C7C323] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__58BBE75C] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__59B00B95] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5AA42FCE] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5B985407] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5C8C7840] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5D809C79] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5E74C0B2] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5F68E4EB] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__605D0924] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__61512D5D] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__62455196] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__633975CF] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__642D9A08] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6521BE41] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6615E27A] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__670A06B3] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__67FE2AEC] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__68F24F25] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__69E6735E] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6ADA9797] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6BCEBBD0] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6CC2E009] DEFAULT ((0)) FOR [ActualYTDNetPerDiem01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6DB70442] DEFAULT ((0)) FOR [ActualYTDNetPerDiem02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6EAB287B] DEFAULT ((0)) FOR [ActualYTDNetPerDiem03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6F9F4CB4] DEFAULT ((0)) FOR [ActualYTDNetPerDiem04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__709370ED] DEFAULT ((0)) FOR [ActualYTDNetPerDiem05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__71879526] DEFAULT ((0)) FOR [ActualYTDNetPerDiem06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__727BB95F] DEFAULT ((0)) FOR [ActualYTDNetPerDiem07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__736FDD98] DEFAULT ((0)) FOR [ActualYTDNetPerDiem08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__746401D1] DEFAULT ((0)) FOR [ActualYTDNetPerDiem09]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__7558260A] DEFAULT ((0)) FOR [ActualYTDNetPerDiem10]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__764C4A43] DEFAULT ((0)) FOR [ActualYTDNetPerDiem11]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Reimb__7681546D] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__77406E7C] DEFAULT ((0)) FOR [ActualYTDNetPerDiem12]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__783492B5] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7928B6EE] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7A1CDB27] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7A51E551] DEFAULT ((0)) FOR [PriorYearActualChargeDollars01]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7B10FF60] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7B46098A] DEFAULT ((0)) FOR [PriorYearActualChargeDollars02]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7C052399] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7C3A2DC3] DEFAULT ((0)) FOR [PriorYearActualChargeDollars03]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7CF947D2] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7D2E51FC] DEFAULT ((0)) FOR [PriorYearActualChargeDollars04]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7DED6C0B] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem07]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7E227635] DEFAULT ((0)) FOR [PriorYearActualChargeDollars05]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7EE19044] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem08]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7F169A6E] DEFAULT ((0)) FOR [PriorYearActualChargeDollars06]; GO
ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7FD5B47D] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem09]; GO

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

---------------------------------------------
-- fp.FactReimbursementChargesProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementChargesProjection] (
    [RowID] int NOT NULL,
    [ReimbursementChargesID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedChargeDollars01] decimal NOT NULL,
    [AdjustedChargeDollars02] decimal NOT NULL,
    [AdjustedChargeDollars03] decimal NOT NULL,
    [AdjustedChargeDollars04] decimal NOT NULL,
    [AdjustedChargeDollars05] decimal NOT NULL,
    [AdjustedChargeDollars06] decimal NOT NULL,
    [AdjustedChargeDollars07] decimal NOT NULL,
    [AdjustedChargeDollars08] decimal NOT NULL,
    [AdjustedChargeDollars09] decimal NOT NULL,
    [AdjustedChargeDollars10] decimal NOT NULL,
    [AdjustedChargeDollars11] decimal NOT NULL,
    [AdjustedChargeDollars12] decimal NOT NULL,
    [AdjustedChargeDollarsTotal] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge01] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge02] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge03] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge04] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge05] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge06] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge07] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge08] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge09] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge10] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge11] decimal NOT NULL,
    [AdjustedNetAsPercentOfCharge12] decimal NOT NULL,
    [AdjustedNetPerDiem01] decimal NOT NULL,
    [AdjustedNetPerDiem02] decimal NOT NULL,
    [AdjustedNetPerDiem03] decimal NOT NULL,
    [AdjustedNetPerDiem04] decimal NOT NULL,
    [AdjustedNetPerDiem05] decimal NOT NULL,
    [AdjustedNetPerDiem06] decimal NOT NULL,
    [AdjustedNetPerDiem07] decimal NOT NULL,
    [AdjustedNetPerDiem08] decimal NOT NULL,
    [AdjustedNetPerDiem09] decimal NOT NULL,
    [AdjustedNetPerDiem10] decimal NOT NULL,
    [AdjustedNetPerDiem11] decimal NOT NULL,
    [AdjustedNetPerDiem12] decimal NOT NULL,
    [AdjustedNetReimbursementValue01] decimal NOT NULL,
    [AdjustedNetReimbursementValue02] decimal NOT NULL,
    [AdjustedNetReimbursementValue03] decimal NOT NULL,
    [AdjustedNetReimbursementValue04] decimal NOT NULL,
    [AdjustedNetReimbursementValue05] decimal NOT NULL,
    [AdjustedNetReimbursementValue06] decimal NOT NULL,
    [AdjustedNetReimbursementValue07] decimal NOT NULL,
    [AdjustedNetReimbursementValue08] decimal NOT NULL,
    [AdjustedNetReimbursementValue09] decimal NOT NULL,
    [AdjustedNetReimbursementValue10] decimal NOT NULL,
    [AdjustedNetReimbursementValue11] decimal NOT NULL,
    [AdjustedNetReimbursementValue12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [FK_FactReimbursementChargesProjection_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Reimb__420D8C2E] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__LockT__4301B067] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__LockF__43F5D4A0] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Budge__44E9F8D9] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__45DE1D12] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__46D2414B] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__47C66584] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__48BA89BD] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__49AEADF6] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4AA2D22F] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4B96F668] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4C8B1AA1] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4D7F3EDA] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4E736313] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4F67874C] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__505BAB85] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5CC1826A] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5DB5A6A3] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5EA9CADC] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5F9DEF15] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6092134E] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__61863787] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__627A5BC0] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__636E7FF9] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6462A432] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6556C86B] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__664AECA4] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__673F10DD] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__68333516] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6927594F] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6A1B7D88] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6B0FA1C1] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6C03C5FA] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6CF7EA33] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6DEC0E6C] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6EE032A5] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6FD456DE] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__70C87B17] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__71BC9F50] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO
ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__72B0C389] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO

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

---------------------------------------------
-- fp.FactReimbursementEncounter ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementEncounter] (
    [ReimbursementEncounterID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [AddDate] datetime NOT NULL,
    [InitialBudgetEncounters01] decimal NOT NULL,
    [InitialBudgetEncounters02] decimal NOT NULL,
    [InitialBudgetEncounters03] decimal NOT NULL,
    [InitialBudgetEncounters04] decimal NOT NULL,
    [InitialBudgetEncounters05] decimal NOT NULL,
    [InitialBudgetEncounters06] decimal NOT NULL,
    [InitialBudgetEncounters07] decimal NOT NULL,
    [InitialBudgetEncounters08] decimal NOT NULL,
    [InitialBudgetEncounters09] decimal NOT NULL,
    [InitialBudgetEncounters10] decimal NOT NULL,
    [InitialBudgetEncounters11] decimal NOT NULL,
    [InitialBudgetEncounters12] decimal NOT NULL,
    [InitialBudgetNetPerEncounter01] decimal NOT NULL,
    [InitialBudgetNetPerEncounter02] decimal NOT NULL,
    [InitialBudgetNetPerEncounter03] decimal NOT NULL,
    [InitialBudgetNetPerEncounter04] decimal NOT NULL,
    [InitialBudgetNetPerEncounter05] decimal NOT NULL,
    [InitialBudgetNetPerEncounter06] decimal NOT NULL,
    [InitialBudgetNetPerEncounter07] decimal NOT NULL,
    [InitialBudgetNetPerEncounter08] decimal NOT NULL,
    [InitialBudgetNetPerEncounter09] decimal NOT NULL,
    [InitialBudgetNetPerEncounter10] decimal NOT NULL,
    [InitialBudgetNetPerEncounter11] decimal NOT NULL,
    [InitialBudgetNetPerEncounter12] decimal NOT NULL,
    [InitialProjectionEncounters01] decimal NOT NULL,
    [InitialProjectionEncounters02] decimal NOT NULL,
    [InitialProjectionEncounters03] decimal NOT NULL,
    [InitialProjectionEncounters04] decimal NOT NULL,
    [InitialProjectionEncounters05] decimal NOT NULL,
    [InitialProjectionEncounters06] decimal NOT NULL,
    [InitialProjectionEncounters07] decimal NOT NULL,
    [InitialProjectionEncounters08] decimal NOT NULL,
    [InitialProjectionEncounters09] decimal NOT NULL,
    [InitialProjectionEncounters10] decimal NOT NULL,
    [InitialProjectionEncounters11] decimal NOT NULL,
    [InitialProjectionEncounters12] decimal NOT NULL,
    [InitialProjectionNetPerEncounter01] decimal NOT NULL,
    [InitialProjectionNetPerEncounter02] decimal NOT NULL,
    [InitialProjectionNetPerEncounter03] decimal NOT NULL,
    [InitialProjectionNetPerEncounter04] decimal NOT NULL,
    [InitialProjectionNetPerEncounter05] decimal NOT NULL,
    [InitialProjectionNetPerEncounter06] decimal NOT NULL,
    [InitialProjectionNetPerEncounter07] decimal NOT NULL,
    [InitialProjectionNetPerEncounter08] decimal NOT NULL,
    [InitialProjectionNetPerEncounter09] decimal NOT NULL,
    [InitialProjectionNetPerEncounter10] decimal NOT NULL,
    [InitialProjectionNetPerEncounter11] decimal NOT NULL,
    [InitialProjectionNetPerEncounter12] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    [InitialBudgetEncountersTotal] decimal NOT NULL,
    [InitialProjectionEncountersTotal] decimal NOT NULL,
    [InitialBudgetNetReimbursement01] decimal NOT NULL,
    [InitialBudgetNetReimbursement02] decimal NOT NULL,
    [InitialBudgetNetReimbursement03] decimal NOT NULL,
    [InitialBudgetNetReimbursement04] decimal NOT NULL,
    [InitialBudgetNetReimbursement05] decimal NOT NULL,
    [InitialBudgetNetReimbursement06] decimal NOT NULL,
    [InitialBudgetNetReimbursement07] decimal NOT NULL,
    [InitialBudgetNetReimbursement08] decimal NOT NULL,
    [InitialBudgetNetReimbursement09] decimal NOT NULL,
    [InitialBudgetNetReimbursement10] decimal NOT NULL,
    [InitialBudgetNetReimbursement11] decimal NOT NULL,
    [InitialBudgetNetReimbursement12] decimal NOT NULL,
    [InitialProjectionNetReimbursement01] decimal NOT NULL,
    [InitialProjectionNetReimbursement02] decimal NOT NULL,
    [InitialProjectionNetReimbursement03] decimal NOT NULL,
    [InitialProjectionNetReimbursement04] decimal NOT NULL,
    [InitialProjectionNetReimbursement05] decimal NOT NULL,
    [InitialProjectionNetReimbursement06] decimal NOT NULL,
    [InitialProjectionNetReimbursement07] decimal NOT NULL,
    [InitialProjectionNetReimbursement08] decimal NOT NULL,
    [InitialProjectionNetReimbursement09] decimal NOT NULL,
    [InitialProjectionNetReimbursement10] decimal NOT NULL,
    [InitialProjectionNetReimbursement11] decimal NOT NULL,
    [InitialProjectionNetReimbursement12] decimal NOT NULL,
    PRIMARY KEY ([ReimbursementEncounterID])
);

CREATE UNIQUE NONCLUSTERED INDEX [CORE_FactReimbursementEncounterUnique] ON [fp].[FactReimbursementEncounter] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID]);
GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Budge__017E05CD] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Entit__02722A06] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Entit__03664E3F] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Patie__045A7278] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Servi__054E96B1] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Servi__0642BAEA] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Medic__0736DF23] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Payor__091F2795] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Payor__0A134BCE] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__MSDRG__0B077007] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__CPTID__0BFB9440] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF_ReimbursementEncounter_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__0ED800EB] DEFAULT ((0)) FOR [InitialBudgetEncounters01]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__0FCC2524] DEFAULT ((0)) FOR [InitialBudgetEncounters02]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__10C0495D] DEFAULT ((0)) FOR [InitialBudgetEncounters03]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__11B46D96] DEFAULT ((0)) FOR [InitialBudgetEncounters04]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__12A891CF] DEFAULT ((0)) FOR [InitialBudgetEncounters05]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__139CB608] DEFAULT ((0)) FOR [InitialBudgetEncounters06]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1490DA41] DEFAULT ((0)) FOR [InitialBudgetEncounters07]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1584FE7A] DEFAULT ((0)) FOR [InitialBudgetEncounters08]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__167922B3] DEFAULT ((0)) FOR [InitialBudgetEncounters09]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__176D46EC] DEFAULT ((0)) FOR [InitialBudgetEncounters10]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__18616B25] DEFAULT ((0)) FOR [InitialBudgetEncounters11]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__19558F5E] DEFAULT ((0)) FOR [InitialBudgetEncounters12]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1A49B397] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter01]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1B3DD7D0] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter02]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1C31FC09] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter03]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1D262042] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter04]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1E1A447B] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter05]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1F0E68B4] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter06]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__20028CED] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter07]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__20F6B126] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter08]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__21EAD55F] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter09]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__22DEF998] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter10]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__23D31DD1] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter11]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__24C7420A] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter12]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__25BB6643] DEFAULT ((0)) FOR [InitialProjectionEncounters01]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__26AF8A7C] DEFAULT ((0)) FOR [InitialProjectionEncounters02]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__27A3AEB5] DEFAULT ((0)) FOR [InitialProjectionEncounters03]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2897D2EE] DEFAULT ((0)) FOR [InitialProjectionEncounters04]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__298BF727] DEFAULT ((0)) FOR [InitialProjectionEncounters05]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2A801B60] DEFAULT ((0)) FOR [InitialProjectionEncounters06]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2B743F99] DEFAULT ((0)) FOR [InitialProjectionEncounters07]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2C6863D2] DEFAULT ((0)) FOR [InitialProjectionEncounters08]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2D5C880B] DEFAULT ((0)) FOR [InitialProjectionEncounters09]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2E50AC44] DEFAULT ((0)) FOR [InitialProjectionEncounters10]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2F44D07D] DEFAULT ((0)) FOR [InitialProjectionEncounters11]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3038F4B6] DEFAULT ((0)) FOR [InitialProjectionEncounters12]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__312D18EF] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter01]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__32213D28] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter02]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__33156161] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter03]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3409859A] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter04]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__34FDA9D3] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter05]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__35F1CE0C] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter06]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__36E5F245] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter07]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__37DA167E] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter08]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__38CE3AB7] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter09]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__39C25EF0] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter10]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3AB68329] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter11]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3BAAA762] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter12]; GO
ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__IsNew__3C9ECB9B] DEFAULT ((0)) FOR [IsNew]; GO

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

---------------------------------------------
-- fp.FactReimbursementEncounterBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementEncounterBudget] (
    [RowID] int NOT NULL,
    [ReimbursementEncounterID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedEncounters01] decimal NOT NULL,
    [AdjustedEncounters02] decimal NOT NULL,
    [AdjustedEncounters03] decimal NOT NULL,
    [AdjustedEncounters04] decimal NOT NULL,
    [AdjustedEncounters05] decimal NOT NULL,
    [AdjustedEncounters06] decimal NOT NULL,
    [AdjustedEncounters07] decimal NOT NULL,
    [AdjustedEncounters08] decimal NOT NULL,
    [AdjustedEncounters09] decimal NOT NULL,
    [AdjustedEncounters10] decimal NOT NULL,
    [AdjustedEncounters11] decimal NOT NULL,
    [AdjustedEncounters12] decimal NOT NULL,
    [AdjustedNetPerEncounterValue01] decimal NOT NULL,
    [AdjustedNetPerEncounterValue02] decimal NOT NULL,
    [AdjustedNetPerEncounterValue03] decimal NOT NULL,
    [AdjustedNetPerEncounterValue04] decimal NOT NULL,
    [AdjustedNetPerEncounterValue05] decimal NOT NULL,
    [AdjustedNetPerEncounterValue06] decimal NOT NULL,
    [AdjustedNetPerEncounterValue07] decimal NOT NULL,
    [AdjustedNetPerEncounterValue08] decimal NOT NULL,
    [AdjustedNetPerEncounterValue09] decimal NOT NULL,
    [AdjustedNetPerEncounterValue10] decimal NOT NULL,
    [AdjustedNetPerEncounterValue11] decimal NOT NULL,
    [AdjustedNetPerEncounterValue12] decimal NOT NULL,
    [AdjustedEncountersTotal] decimal NOT NULL,
    [AdjustedNetReimbursementValue01] decimal NOT NULL,
    [AdjustedNetReimbursementValue02] decimal NOT NULL,
    [AdjustedNetReimbursementValue03] decimal NOT NULL,
    [AdjustedNetReimbursementValue04] decimal NOT NULL,
    [AdjustedNetReimbursementValue05] decimal NOT NULL,
    [AdjustedNetReimbursementValue06] decimal NOT NULL,
    [AdjustedNetReimbursementValue07] decimal NOT NULL,
    [AdjustedNetReimbursementValue08] decimal NOT NULL,
    [AdjustedNetReimbursementValue09] decimal NOT NULL,
    [AdjustedNetReimbursementValue10] decimal NOT NULL,
    [AdjustedNetReimbursementValue11] decimal NOT NULL,
    [AdjustedNetReimbursementValue12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [FK_FactReimbursementEncounterBudget_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[FactReimbursementEncounter] ([ReimbursementEncounterID]); GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Reimb__30F80EC5] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__LockT__31EC32FE] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__LockF__32E05737] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Budge__33D47B70] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__34C89FA9] DEFAULT ((0)) FOR [AdjustedEncounters01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__35BCC3E2] DEFAULT ((0)) FOR [AdjustedEncounters02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__36B0E81B] DEFAULT ((0)) FOR [AdjustedEncounters03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__37A50C54] DEFAULT ((0)) FOR [AdjustedEncounters04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3899308D] DEFAULT ((0)) FOR [AdjustedEncounters05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__398D54C6] DEFAULT ((0)) FOR [AdjustedEncounters06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3A8178FF] DEFAULT ((0)) FOR [AdjustedEncounters07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3B759D38] DEFAULT ((0)) FOR [AdjustedEncounters08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3C69C171] DEFAULT ((0)) FOR [AdjustedEncounters09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3D5DE5AA] DEFAULT ((0)) FOR [AdjustedEncounters10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3E5209E3] DEFAULT ((0)) FOR [AdjustedEncounters11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3F462E1C] DEFAULT ((0)) FOR [AdjustedEncounters12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__403A5255] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__412E768E] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__42229AC7] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4316BF00] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__440AE339] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__44FF0772] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__45F32BAB] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__46E74FE4] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__47DB741D] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__48CF9856] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__49C3BC8F] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4AB7E0C8] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO

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

---------------------------------------------
-- fp.FactReimbursementEncounterHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementEncounterHistory] (
    [RowID] int NOT NULL,
    [ReimbursementEncounterID] int NOT NULL,
    [PriorYearActualEncounters01] decimal NOT NULL,
    [PriorYearActualEncounters02] decimal NOT NULL,
    [PriorYearActualEncounters03] decimal NOT NULL,
    [PriorYearActualEncounters04] decimal NOT NULL,
    [PriorYearActualEncounters05] decimal NOT NULL,
    [PriorYearActualEncounters06] decimal NOT NULL,
    [PriorYearActualEncounters07] decimal NOT NULL,
    [PriorYearActualEncounters08] decimal NOT NULL,
    [PriorYearActualEncounters09] decimal NOT NULL,
    [PriorYearActualEncounters10] decimal NOT NULL,
    [PriorYearActualEncounters11] decimal NOT NULL,
    [PriorYearActualEncounters12] decimal NOT NULL,
    [ActualYTDEncounters01] decimal NOT NULL,
    [ActualYTDEncounters02] decimal NOT NULL,
    [ActualYTDEncounters03] decimal NOT NULL,
    [ActualYTDEncounters04] decimal NOT NULL,
    [ActualYTDEncounters05] decimal NOT NULL,
    [ActualYTDEncounters06] decimal NOT NULL,
    [ActualYTDEncounters07] decimal NOT NULL,
    [ActualYTDEncounters08] decimal NOT NULL,
    [ActualYTDEncounters09] decimal NOT NULL,
    [ActualYTDEncounters10] decimal NOT NULL,
    [ActualYTDEncounters11] decimal NOT NULL,
    [ActualYTDEncounters12] decimal NOT NULL,
    [CurrentYearBudgetEncounters01] decimal NOT NULL,
    [CurrentYearBudgetEncounters02] decimal NOT NULL,
    [CurrentYearBudgetEncounters03] decimal NOT NULL,
    [CurrentYearBudgetEncounters04] decimal NOT NULL,
    [CurrentYearBudgetEncounters05] decimal NOT NULL,
    [CurrentYearBudgetEncounters06] decimal NOT NULL,
    [CurrentYearBudgetEncounters07] decimal NOT NULL,
    [CurrentYearBudgetEncounters08] decimal NOT NULL,
    [CurrentYearBudgetEncounters09] decimal NOT NULL,
    [CurrentYearBudgetEncounters10] decimal NOT NULL,
    [CurrentYearBudgetEncounters11] decimal NOT NULL,
    [CurrentYearBudgetEncounters12] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue01] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue02] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue03] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue04] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue05] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue06] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue07] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue08] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue09] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue10] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue11] decimal NOT NULL,
    [PriorYearActualNetPerEncounterValue12] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue01] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue02] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue03] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue04] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue05] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue06] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue07] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue08] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue09] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue10] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue11] decimal NOT NULL,
    [ActualYTDNetPerEncounterValue12] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget01] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget02] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget03] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget04] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget05] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget06] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget07] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget08] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget09] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget10] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget11] decimal NOT NULL,
    [CurrentYearNetPerEncounterBudget12] decimal NOT NULL,
    [PriorYearActualEncountersTotal] decimal NOT NULL,
    [ActualYTDEncountersTotal] decimal NOT NULL,
    [CurrentYearBudgetEncountersTotal] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue01] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue02] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue03] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue04] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue05] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue06] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue07] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue08] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue09] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue10] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue11] decimal NOT NULL,
    [PriorYearActualNetReimbursementValue12] decimal NOT NULL,
    [ActualYTDNetReimbursementValue01] decimal NOT NULL,
    [ActualYTDNetReimbursementValue02] decimal NOT NULL,
    [ActualYTDNetReimbursementValue03] decimal NOT NULL,
    [ActualYTDNetReimbursementValue04] decimal NOT NULL,
    [ActualYTDNetReimbursementValue05] decimal NOT NULL,
    [ActualYTDNetReimbursementValue06] decimal NOT NULL,
    [ActualYTDNetReimbursementValue07] decimal NOT NULL,
    [ActualYTDNetReimbursementValue08] decimal NOT NULL,
    [ActualYTDNetReimbursementValue09] decimal NOT NULL,
    [ActualYTDNetReimbursementValue10] decimal NOT NULL,
    [ActualYTDNetReimbursementValue11] decimal NOT NULL,
    [ActualYTDNetReimbursementValue12] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget01] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget02] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget03] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget04] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget05] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget06] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget07] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget08] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget09] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget10] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget11] decimal NOT NULL,
    [CurrentYearNetReimbursementBudget12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [FK_FactReimbursementEncounterHistory_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[FactReimbursementEncounter] ([ReimbursementEncounterID]); GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Reimb__13BCB199] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__14B0D5D2] DEFAULT ((0)) FOR [PriorYearActualEncounters01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__15A4FA0B] DEFAULT ((0)) FOR [PriorYearActualEncounters02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__16991E44] DEFAULT ((0)) FOR [PriorYearActualEncounters03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__178D427D] DEFAULT ((0)) FOR [PriorYearActualEncounters04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__188166B6] DEFAULT ((0)) FOR [PriorYearActualEncounters05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__19758AEF] DEFAULT ((0)) FOR [PriorYearActualEncounters06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1A69AF28] DEFAULT ((0)) FOR [PriorYearActualEncounters07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1B5DD361] DEFAULT ((0)) FOR [PriorYearActualEncounters08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1C51F79A] DEFAULT ((0)) FOR [PriorYearActualEncounters09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1D461BD3] DEFAULT ((0)) FOR [PriorYearActualEncounters10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1E3A400C] DEFAULT ((0)) FOR [PriorYearActualEncounters11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1F2E6445] DEFAULT ((0)) FOR [PriorYearActualEncounters12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__2022887E] DEFAULT ((0)) FOR [ActualYTDEncounters01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__2116ACB7] DEFAULT ((0)) FOR [ActualYTDEncounters02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__220AD0F0] DEFAULT ((0)) FOR [ActualYTDEncounters03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__22FEF529] DEFAULT ((0)) FOR [ActualYTDEncounters04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__23F31962] DEFAULT ((0)) FOR [ActualYTDEncounters05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__24E73D9B] DEFAULT ((0)) FOR [ActualYTDEncounters06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__25DB61D4] DEFAULT ((0)) FOR [ActualYTDEncounters07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__26CF860D] DEFAULT ((0)) FOR [ActualYTDEncounters08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__27C3AA46] DEFAULT ((0)) FOR [ActualYTDEncounters09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__28B7CE7F] DEFAULT ((0)) FOR [ActualYTDEncounters10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__29ABF2B8] DEFAULT ((0)) FOR [ActualYTDEncounters11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__2AA016F1] DEFAULT ((0)) FOR [ActualYTDEncounters12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2B943B2A] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2C885F63] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2D7C839C] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2E70A7D5] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2F64CC0E] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3058F047] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__314D1480] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__324138B9] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__33355CF2] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3429812B] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__351DA564] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3611C99D] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3705EDD6] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__37FA120F] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__38EE3648] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__39E25A81] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3AD67EBA] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3BCAA2F3] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3CBEC72C] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3DB2EB65] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3EA70F9E] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3F9B33D7] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__408F5810] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__41837C49] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4277A082] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__436BC4BB] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__445FE8F4] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__45540D2D] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__46483166] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__473C559F] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__483079D8] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__49249E11] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4A18C24A] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4B0CE683] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4C010ABC] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4CF52EF5] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__4DE9532E] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__4EDD7767] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__4FD19BA0] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__50C5BFD9] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__51B9E412] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__52AE084B] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__53A22C84] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__549650BD] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__558A74F6] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__567E992F] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5772BD68] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5866E1A1] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget12]; GO

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

---------------------------------------------
-- fp.FactReimbursementEncounterProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReimbursementEncounterProjection] (
    [RowID] int NOT NULL,
    [ReimbursementEncounterID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedEncounters01] decimal NOT NULL,
    [AdjustedEncounters02] decimal NOT NULL,
    [AdjustedEncounters03] decimal NOT NULL,
    [AdjustedEncounters04] decimal NOT NULL,
    [AdjustedEncounters05] decimal NOT NULL,
    [AdjustedEncounters06] decimal NOT NULL,
    [AdjustedEncounters07] decimal NOT NULL,
    [AdjustedEncounters08] decimal NOT NULL,
    [AdjustedEncounters09] decimal NOT NULL,
    [AdjustedEncounters10] decimal NOT NULL,
    [AdjustedEncounters11] decimal NOT NULL,
    [AdjustedEncounters12] decimal NOT NULL,
    [AdjustedNetPerEncounterValue01] decimal NOT NULL,
    [AdjustedNetPerEncounterValue02] decimal NOT NULL,
    [AdjustedNetPerEncounterValue03] decimal NOT NULL,
    [AdjustedNetPerEncounterValue04] decimal NOT NULL,
    [AdjustedNetPerEncounterValue05] decimal NOT NULL,
    [AdjustedNetPerEncounterValue06] decimal NOT NULL,
    [AdjustedNetPerEncounterValue07] decimal NOT NULL,
    [AdjustedNetPerEncounterValue08] decimal NOT NULL,
    [AdjustedNetPerEncounterValue09] decimal NOT NULL,
    [AdjustedNetPerEncounterValue10] decimal NOT NULL,
    [AdjustedNetPerEncounterValue11] decimal NOT NULL,
    [AdjustedNetPerEncounterValue12] decimal NOT NULL,
    [AdjustedEncountersTotal] decimal NOT NULL,
    [AdjustedNetReimbursementValue01] decimal NOT NULL,
    [AdjustedNetReimbursementValue02] decimal NOT NULL,
    [AdjustedNetReimbursementValue03] decimal NOT NULL,
    [AdjustedNetReimbursementValue04] decimal NOT NULL,
    [AdjustedNetReimbursementValue05] decimal NOT NULL,
    [AdjustedNetReimbursementValue06] decimal NOT NULL,
    [AdjustedNetReimbursementValue07] decimal NOT NULL,
    [AdjustedNetReimbursementValue08] decimal NOT NULL,
    [AdjustedNetReimbursementValue09] decimal NOT NULL,
    [AdjustedNetReimbursementValue10] decimal NOT NULL,
    [AdjustedNetReimbursementValue11] decimal NOT NULL,
    [AdjustedNetReimbursementValue12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [FK_FactReimbursementEncounterProjection_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[FactReimbursementEncounter] ([ReimbursementEncounterID]); GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__001FCD40] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__0113F179] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__020815B2] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__02FC39EB] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__03F05E24] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__04E4825D] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__05D8A696] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Reimb__6C18D493] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__LockT__6D0CF8CC] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__LockF__6E011D05] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Budge__6EF5413E] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6FE96577] DEFAULT ((0)) FOR [AdjustedEncounters01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__70DD89B0] DEFAULT ((0)) FOR [AdjustedEncounters02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__71D1ADE9] DEFAULT ((0)) FOR [AdjustedEncounters03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__72C5D222] DEFAULT ((0)) FOR [AdjustedEncounters04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__73B9F65B] DEFAULT ((0)) FOR [AdjustedEncounters05]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__74AE1A94] DEFAULT ((0)) FOR [AdjustedEncounters06]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__75A23ECD] DEFAULT ((0)) FOR [AdjustedEncounters07]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__76966306] DEFAULT ((0)) FOR [AdjustedEncounters08]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__778A873F] DEFAULT ((0)) FOR [AdjustedEncounters09]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__787EAB78] DEFAULT ((0)) FOR [AdjustedEncounters10]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7972CFB1] DEFAULT ((0)) FOR [AdjustedEncounters11]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7A66F3EA] DEFAULT ((0)) FOR [AdjustedEncounters12]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7B5B1823] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7C4F3C5C] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7D436095] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7E3784CE] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO
ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7F2BA907] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO

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

---------------------------------------------
-- fp.FactReportAdjustmentHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportAdjustmentHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [SectionID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [AdjustmentType] int NOT NULL,
    [Months] nvarchar(50) NOT NULL,
    [AdjustmentValue] nvarchar(max) NOT NULL,
    [AdjustedLevel] nvarchar(max) NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsSetValue] bit NOT NULL,
    [IsErrored] bit NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [IX_FactReportAdjustmentHistory_BudgetConfigID] ON [fp].[FactReportAdjustmentHistory] ([BudgetConfigID], [SectionID], [AdjustmentID]);
GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Budge__3B5900CD] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Secti__3C4D2506] DEFAULT ((0)) FOR [SectionID]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__3D41493F] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__3E356D78] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Month__3F2991B1] DEFAULT ('') FOR [Months]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__401DB5EA] DEFAULT ('') FOR [AdjustmentValue]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__4111DA23] DEFAULT ('') FOR [AdjustedLevel]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__UnitT__4205FE5C] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__TimeC__42FA2295] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__LastM__43EE46CE] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__DateC__44E26B07] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Comme__45D68F40] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Autho__46CAB379] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Class__47BED7B2] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Class__48B2FBEB] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__IsSet__49A72024] DEFAULT ((0)) FOR [IsSetValue]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__IsErr__4A9B445D] DEFAULT ((0)) FOR [IsErrored]; GO
ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__IsRec__4B8F6896] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.FactReportChargeToStatisticsCrosswalk ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalk] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] smallint NOT NULL,
    [RVUWeight] decimal NOT NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL,
    [AccountID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportChargeToStatisticsCrosswalk] ON [fp].[FactReportChargeToStatisticsCrosswalk] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [EntityID], [DepartmentID], [ChargeCodeID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [PatientClassID], [UnitTypeID], [FiscalMonthID], [AccountID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportChargeToStatisticsCrosswalk] ([DepartmentID]);
GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Accou__1C538E48] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Budge__6D213C0E] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Entit__6E156047] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Depar__6F098480] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Charg__6FFDA8B9] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Servi__70F1CCF2] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__AgeCo__71E5F12B] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Medic__72DA1564] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Patie__73CE399D] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__UnitT__75B6820F] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__TimeC__76AAA648] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Fisca__779ECA81] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__RVUWe__798712F3] DEFAULT ((0)) FOR [RVUWeight]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Origi__7A7B372C] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Value__7B6F5B65] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Manag__7C637F9E] DEFAULT ((0)) FOR [ManagerValue]; GO

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

---------------------------------------------
-- fp.FactReportChargeToStatisticsCrosswalkHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] (
    [ChargeVolumeID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [RVUWeight] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [AccountID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportChargeToStatisticsCrosswalkHistory] ON [fp].[FactReportChargeToStatisticsCrosswalkHistory] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [ChargeVolumeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ChargeCodeID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [PatientClassID], [FiscalMonthID], [AccountID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportChargeToStatisticsCrosswalkHistory] ([DepartmentID]);
GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Charg__0F765412] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Budge__106A784B] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Entit__115E9C84] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Entit__1252C0BD] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Depar__1346E4F6] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Charg__143B092F] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Servi__152F2D68] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__AgeCo__162351A1] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Medic__171775DA] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Patie__18FFBE4C] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__UnitT__19F3E285] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__TimeC__1AE806BE] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__RVUWe__1CD04F30] DEFAULT ((0)) FOR [RVUWeight]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Value__1DC47369] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Accou__1E3BD6BA] DEFAULT ((0)) FOR [AccountID]; GO

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

---------------------------------------------
-- fp.FactReportChargeToStatisticsCrosswalkHistory_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] (
    [ChargeVolumeID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [RVUWeight] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [AccountID] int NOT NULL
);
GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Accou__1F2FFAF3] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Charg__1FACBBDB] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Budge__20A0E014] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__2195044D] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__22892886] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Depar__237D4CBF] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Charg__247170F8] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__25659531] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__2659B96A] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Medic__274DDDA3] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Payor__284201DC] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Patie__29362615] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__2A2A4A4E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__2B1E6E87] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__RVUWe__2D06B6F9] DEFAULT ((0)) FOR [RVUWeight]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Value__2DFADB32] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.FactReportChargeToStatisticsCrosswalk_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] smallint NOT NULL,
    [RVUWeight] decimal NOT NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL,
    [AccountID] int NOT NULL
);
GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Depar__00341082] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Charg__012834BB] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Servi__021C58F4] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__03107D2D] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Medic__0404A166] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Patie__04F8C59F] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Payor__05ECE9D8] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__06E10E11] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__07D5324A] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__08C95683] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__RVUWe__0AB19EF5] DEFAULT ((0)) FOR [RVUWeight]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Origi__0BA5C32E] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Value__0C99E767] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Manag__0D8E0BA0] DEFAULT ((0)) FOR [ManagerValue]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Accou__1D47B281] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Budge__7E4BC810] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Entit__7F3FEC49] DEFAULT ((0)) FOR [EntityID]; GO

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

---------------------------------------------
-- fp.FactReportChargeVolume ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportChargeVolume] (
    [ChargeVolumeID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [Target01] decimal NOT NULL,
    [Target02] decimal NOT NULL,
    [Target03] decimal NOT NULL,
    [Target04] decimal NOT NULL,
    [Target05] decimal NOT NULL,
    [Target06] decimal NOT NULL,
    [Target07] decimal NOT NULL,
    [Target08] decimal NOT NULL,
    [Target09] decimal NOT NULL,
    [Target10] decimal NOT NULL,
    [Target11] decimal NOT NULL,
    [Target12] decimal NOT NULL,
    [TargetTotal] decimal NOT NULL,
    [Budget01] decimal NOT NULL,
    [Budget02] decimal NOT NULL,
    [Budget03] decimal NOT NULL,
    [Budget04] decimal NOT NULL,
    [Budget05] decimal NOT NULL,
    [Budget06] decimal NOT NULL,
    [Budget07] decimal NOT NULL,
    [Budget08] decimal NOT NULL,
    [Budget09] decimal NOT NULL,
    [Budget10] decimal NOT NULL,
    [Budget11] decimal NOT NULL,
    [Budget12] decimal NOT NULL,
    [BudgetTotal] decimal NOT NULL,
    [Projection01] decimal NOT NULL,
    [Projection02] decimal NOT NULL,
    [Projection03] decimal NOT NULL,
    [Projection04] decimal NOT NULL,
    [Projection05] decimal NOT NULL,
    [Projection06] decimal NOT NULL,
    [Projection07] decimal NOT NULL,
    [Projection08] decimal NOT NULL,
    [Projection09] decimal NOT NULL,
    [Projection10] decimal NOT NULL,
    [Projection11] decimal NOT NULL,
    [Projection12] decimal NOT NULL,
    [ProjectionTotal] decimal NOT NULL
);
GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__0049EA72] DEFAULT ((0)) FOR [Target08]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__013E0EAB] DEFAULT ((0)) FOR [Target09]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__023232E4] DEFAULT ((0)) FOR [Target10]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__0326571D] DEFAULT ((0)) FOR [Target11]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__041A7B56] DEFAULT ((0)) FOR [Target12]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__047CD00E] DEFAULT ((0)) FOR [Projection01]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__050E9F8F] DEFAULT ((0)) FOR [TargetTotal]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0570F447] DEFAULT ((0)) FOR [Projection02]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0602C3C8] DEFAULT ((0)) FOR [Budget01]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__06651880] DEFAULT ((0)) FOR [Projection03]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__06F6E801] DEFAULT ((0)) FOR [Budget02]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__07593CB9] DEFAULT ((0)) FOR [Projection04]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__07EB0C3A] DEFAULT ((0)) FOR [Budget03]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__084D60F2] DEFAULT ((0)) FOR [Projection05]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__08DF3073] DEFAULT ((0)) FOR [Budget04]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0941852B] DEFAULT ((0)) FOR [Projection06]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__09D354AC] DEFAULT ((0)) FOR [Budget05]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0A35A964] DEFAULT ((0)) FOR [Projection07]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0AC778E5] DEFAULT ((0)) FOR [Budget06]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0B29CD9D] DEFAULT ((0)) FOR [Projection08]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0BBB9D1E] DEFAULT ((0)) FOR [Budget07]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0C1DF1D6] DEFAULT ((0)) FOR [Projection09]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0CAFC157] DEFAULT ((0)) FOR [Budget08]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0D12160F] DEFAULT ((0)) FOR [Projection10]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0DA3E590] DEFAULT ((0)) FOR [Budget09]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0E063A48] DEFAULT ((0)) FOR [Projection11]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0E9809C9] DEFAULT ((0)) FOR [Budget10]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0EFA5E81] DEFAULT ((0)) FOR [Projection12]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0F8C2E02] DEFAULT ((0)) FOR [Budget11]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0FEE82BA] DEFAULT ((0)) FOR [ProjectionTotal]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__1080523B] DEFAULT ((0)) FOR [Budget12]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__11747674] DEFAULT ((0)) FOR [BudgetTotal]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Charg__59301D51] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Budge__5A24418A] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Entit__5B1865C3] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Depar__5C0C89FC] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__5D00AE35] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Patie__5DF4D26E] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__AgeCo__5EE8F6A7] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Medic__5FDD1AE0] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Charg__60D13F19] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__61C56352] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__MSDRG__62B9878B] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__UBRev__63ADABC4] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Prima__64A1CFFD] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__6595F436] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__668A186F] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Perfo__677E3CA8] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Perfo__687260E1] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Billi__6966851A] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__UnitT__6A5AA953] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__6D3715FE] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__6E2B3A37] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__6F1F5E70] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__701382A9] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__7107A6E2] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__71FBCB1B] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__72EFEF54] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__73E4138D] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__74D837C6] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__75CC5BFF] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__76C08038] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__77B4A471] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__78A8C8AA] DEFAULT ((0)) FOR [InitialBudgetTotal]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__799CECE3] DEFAULT ((0)) FOR [Target01]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7A91111C] DEFAULT ((0)) FOR [Target02]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7B853555] DEFAULT ((0)) FOR [Target03]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7C79598E] DEFAULT ((0)) FOR [Target04]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7D6D7DC7] DEFAULT ((0)) FOR [Target05]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7E61A200] DEFAULT ((0)) FOR [Target06]; GO
ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7F55C639] DEFAULT ((0)) FOR [Target07]; GO

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

---------------------------------------------
-- fp.FactReportChargeVolume_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportChargeVolume_archive] (
    [ChargeVolumeID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingProviderSpecialtyID] int NOT NULL,
    [BillingCPTID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OriginalValue01] decimal NOT NULL,
    [OriginalValue02] decimal NOT NULL,
    [OriginalValue03] decimal NOT NULL,
    [OriginalValue04] decimal NOT NULL,
    [OriginalValue05] decimal NOT NULL,
    [OriginalValue06] decimal NOT NULL,
    [OriginalValue07] decimal NOT NULL,
    [OriginalValue08] decimal NOT NULL,
    [OriginalValue09] decimal NOT NULL,
    [OriginalValue10] decimal NOT NULL,
    [OriginalValue11] decimal NOT NULL,
    [OriginalValue12] decimal NOT NULL,
    [OriginalValueTotal] decimal NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [ValueTotal] decimal NOT NULL,
    [ManagerValue01] decimal NOT NULL,
    [ManagerValue02] decimal NOT NULL,
    [ManagerValue03] decimal NOT NULL,
    [ManagerValue04] decimal NOT NULL,
    [ManagerValue05] decimal NOT NULL,
    [ManagerValue06] decimal NOT NULL,
    [ManagerValue07] decimal NOT NULL,
    [ManagerValue08] decimal NOT NULL,
    [ManagerValue09] decimal NOT NULL,
    [ManagerValue10] decimal NOT NULL,
    [ManagerValue11] decimal NOT NULL,
    [ManagerValue12] decimal NOT NULL,
    [ManagerValueTotal] decimal NOT NULL,
    PRIMARY KEY ([ChargeVolumeID], [TimeClassID], [UnitTypeID])
);
GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Charg__1450E31F] DEFAULT ((0)) FOR [ChargeVolumeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Budge__15450758] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Entit__16392B91] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Depar__172D4FCA] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__18217403] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Patie__1915983C] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__1A09BC75] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Medic__1AFDE0AE] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Charg__1BF204E7] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__1CE62920] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__MSDRG__1DDA4D59] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__UBRev__1ECE7192] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Prima__1FC295CB] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__20B6BA04] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__21AADE3D] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Perfo__229F0276] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Perfo__239326AF] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Billi__24874AE8] DEFAULT ((0)) FOR [BillingCPTID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__257B6F21] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__266F935A] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__2763B793] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2857DBCC] DEFAULT ((0)) FOR [OriginalValue01]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__294C0005] DEFAULT ((0)) FOR [OriginalValue02]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2A40243E] DEFAULT ((0)) FOR [OriginalValue03]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2B344877] DEFAULT ((0)) FOR [OriginalValue04]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2C286CB0] DEFAULT ((0)) FOR [OriginalValue05]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2D1C90E9] DEFAULT ((0)) FOR [OriginalValue06]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2E10B522] DEFAULT ((0)) FOR [OriginalValue07]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2F04D95B] DEFAULT ((0)) FOR [OriginalValue08]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2FF8FD94] DEFAULT ((0)) FOR [OriginalValue09]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__30ED21CD] DEFAULT ((0)) FOR [OriginalValue10]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__31E14606] DEFAULT ((0)) FOR [OriginalValue11]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__32D56A3F] DEFAULT ((0)) FOR [OriginalValue12]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__33C98E78] DEFAULT ((0)) FOR [OriginalValueTotal]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__34BDB2B1] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__35B1D6EA] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__36A5FB23] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__379A1F5C] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__388E4395] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__398267CE] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3A768C07] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3B6AB040] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3C5ED479] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3D52F8B2] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3E471CEB] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3F3B4124] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__402F655D] DEFAULT ((0)) FOR [ValueTotal]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__41238996] DEFAULT ((0)) FOR [ManagerValue01]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4217ADCF] DEFAULT ((0)) FOR [ManagerValue02]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__430BD208] DEFAULT ((0)) FOR [ManagerValue03]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__43FFF641] DEFAULT ((0)) FOR [ManagerValue04]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__44F41A7A] DEFAULT ((0)) FOR [ManagerValue05]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__45E83EB3] DEFAULT ((0)) FOR [ManagerValue06]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__46DC62EC] DEFAULT ((0)) FOR [ManagerValue07]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__47D08725] DEFAULT ((0)) FOR [ManagerValue08]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__48C4AB5E] DEFAULT ((0)) FOR [ManagerValue09]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__49B8CF97] DEFAULT ((0)) FOR [ManagerValue10]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4AACF3D0] DEFAULT ((0)) FOR [ManagerValue11]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4BA11809] DEFAULT ((0)) FOR [ManagerValue12]; GO
ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4C953C42] DEFAULT ((0)) FOR [ManagerValueTotal]; GO

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

---------------------------------------------
-- fp.FactReportChargesNotCrosswalkedData ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportChargesNotCrosswalkedData] (
    [DepartmentID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [ProjectionDollarsAdjustedTotal] decimal NOT NULL,
    [TargetDollarsAdjustedTotal] decimal NOT NULL,
    [BudgetDollarsAdjustedTotal] decimal NOT NULL,
    [PayorGroupID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [PatientClassID], [ChargeCodeID], [PayorGroupID])
);
GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Depar__219831A9] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Charg__228C55E2] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Patie__23807A1B] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Budge__24749E54] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Proje__2568C28D] DEFAULT ((0)) FOR [ProjectionDollarsAdjustedTotal]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Targe__265CE6C6] DEFAULT ((0)) FOR [TargetDollarsAdjustedTotal]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Budge__27510AFF] DEFAULT ((0)) FOR [BudgetDollarsAdjustedTotal]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Payor__49E61A25] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Entit__4ADA3E5E] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO

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

---------------------------------------------
-- fp.FactReportEncounter ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncounter] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] int NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL
);
GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Budge__532C5FE1] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Entit__5420841A] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Servi__5514A853] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Servi__5608CC8C] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Patie__56FCF0C5] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__AgeCo__57F114FE] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Medic__58E53937] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Depar__59D95D70] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Payor__5ACD81A9] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Payor__5BC1A5E2] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__MSDRG__5CB5CA1B] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__CPTID__5DA9EE54] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Provi__5E9E128D] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Physi__5F9236C6] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__UnitT__60865AFF] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__TimeC__617A7F38] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Fisca__626EA371] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Fisca__6362C7AA] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Origi__6456EBE3] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Value__654B101C] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Manag__663F3455] DEFAULT ((0)) FOR [ManagerValue]; GO

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

---------------------------------------------
-- fp.FactReportEncounterHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncounterHistory] (
    [ServiceLineEncounterID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] int NULL,
    [Value] decimal NOT NULL
);
GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Servi__00F32A91] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Servi__01E74ECA] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Patie__02DB7303] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__AgeCo__03CF973C] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Medic__04C3BB75] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Depar__05B7DFAE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Payor__06AC03E7] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Payor__07A02820] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__MSDRG__08944C59] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__CPTID__09887092] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Provi__0A7C94CB] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Physi__0B70B904] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__UnitT__0C64DD3D] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__TimeC__0D590176] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Fisca__0E4D25AF] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Fisca__0F4149E8] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Value__10356E21] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Servi__7D2299AD] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Budge__7E16BDE6] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Entit__7F0AE21F] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Entit__7FFF0658] DEFAULT ((0)) FOR [EntityID]; GO

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

---------------------------------------------
-- fp.FactReportEncounterHistory_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncounterHistory_archive] (
    [ServiceLineEncounterID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] int NULL,
    [Value] decimal NOT NULL
);
GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__121DB693] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Budge__1311DACC] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__1405FF05] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__14FA233E] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__15EE4777] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__16E26BB0] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Patie__17D68FE9] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__18CAB422] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Medic__19BED85B] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Depar__1AB2FC94] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Payor__1BA720CD] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Payor__1C9B4506] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__MSDRG__1D8F693F] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__CPTID__1E838D78] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__1F77B1B1] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Physi__206BD5EA] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__215FFA23] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__22541E5C] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__23484295] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__243C66CE] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Value__25308B07] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.FactReportEncounter_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncounter_archive] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] int NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL
);
GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Budge__68277CC7] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Entit__691BA100] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Servi__6A0FC539] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Servi__6B03E972] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Patie__6BF80DAB] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__6CEC31E4] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Medic__6DE0561D] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Depar__6ED47A56] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Payor__6FC89E8F] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Payor__70BCC2C8] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__MSDRG__71B0E701] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__CPTID__72A50B3A] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Provi__73992F73] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Physi__748D53AC] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__758177E5] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__76759C1E] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__7769C057] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__785DE490] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Origi__795208C9] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Value__7A462D02] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Manag__7B3A513B] DEFAULT ((0)) FOR [ManagerValue]; GO

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

---------------------------------------------
-- fp.FactReportEncountersToChargeDollars ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncountersToChargeDollars] (
    [BudgetConfigID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [AdjustmentDate] datetime NOT NULL,
    [AdjustmentAuthor] nvarchar(260) NOT NULL,
    [AdjustmentClassificationCategoryID] int NOT NULL,
    [AdjustmentClassificationGroupID] int NOT NULL,
    [AdjustmentComment] nvarchar(max) NOT NULL,
    [DollarImpact01] decimal NOT NULL,
    [DollarImpact02] decimal NOT NULL,
    [DollarImpact03] decimal NOT NULL,
    [DollarImpact04] decimal NOT NULL,
    [DollarImpact05] decimal NOT NULL,
    [DollarImpact06] decimal NOT NULL,
    [DollarImpact07] decimal NOT NULL,
    [DollarImpact08] decimal NOT NULL,
    [DollarImpact09] decimal NOT NULL,
    [DollarImpact10] decimal NOT NULL,
    [DollarImpact11] decimal NOT NULL,
    [DollarImpact12] decimal NOT NULL,
    [DollarImpactTotal] decimal NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL
);

CREATE NONCLUSTERED INDEX [CORE_Dimensionality_FactReportEncountersToChargeDollars] ON [fp].[FactReportEncountersToChargeDollars] ([BudgetConfigID], [ServiceEntityID], [EntityID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [MSDRGID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [ServiceLineID], [ServiceLineRollupID], [DepartmentID], [UBRevCodeID], [PayorID], [PayorGroupID], [TimeClassID], [AdjustmentID]);
GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__08FFF75B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF_FactReportEncountersToChargeDollars_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Budge__36C5F6B4] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__37BA1AED] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Entit__38AE3F26] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Patie__39A2635F] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__AgeCo__3A968798] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Medic__3B8AABD1] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__MSDRG__3C7ED00A] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Prima__3D72F443] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__3E67187C] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__3F5B3CB5] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__404F60EE] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__41438527] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Depar__4237A960] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__UBRev__432BCD99] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Payor__441FF1D2] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Payor__4514160B] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__TimeC__46083A44] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__46FC5E7D] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__47F082B6] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__48E4A6EF] DEFAULT ('') FOR [AdjustmentAuthor]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__49D8CB28] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__4ACCEF61] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4CB537D3] DEFAULT ((0)) FOR [DollarImpact01]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4DA95C0C] DEFAULT ((0)) FOR [DollarImpact02]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4E9D8045] DEFAULT ((0)) FOR [DollarImpact03]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4F91A47E] DEFAULT ((0)) FOR [DollarImpact04]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5085C8B7] DEFAULT ((0)) FOR [DollarImpact05]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5179ECF0] DEFAULT ((0)) FOR [DollarImpact06]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__526E1129] DEFAULT ((0)) FOR [DollarImpact07]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__53623562] DEFAULT ((0)) FOR [DollarImpact08]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5456599B] DEFAULT ((0)) FOR [DollarImpact09]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__554A7DD4] DEFAULT ((0)) FOR [DollarImpact10]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__563EA20D] DEFAULT ((0)) FOR [DollarImpact11]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5732C646] DEFAULT ((0)) FOR [DollarImpact12]; GO

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

---------------------------------------------
-- fp.FactReportEncountersToChargeDollars_Initial ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncountersToChargeDollars_Initial] (
    [BudgetConfigID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [ServiceProviderID] int NOT NULL,
    [ServiceProviderSpecialtyID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [AdjustmentDate] datetime NOT NULL,
    [AdjustmentAuthor] nvarchar(260) NOT NULL,
    [AdjustmentClassificationCategoryID] int NOT NULL,
    [AdjustmentClassificationGroupID] int NOT NULL,
    [AdjustmentComment] nvarchar(max) NOT NULL,
    [DollarImpact01] decimal NOT NULL,
    [DollarImpact02] decimal NOT NULL,
    [DollarImpact03] decimal NOT NULL,
    [DollarImpact04] decimal NOT NULL,
    [DollarImpact05] decimal NOT NULL,
    [DollarImpact06] decimal NOT NULL,
    [DollarImpact07] decimal NOT NULL,
    [DollarImpact08] decimal NOT NULL,
    [DollarImpact09] decimal NOT NULL,
    [DollarImpact10] decimal NOT NULL,
    [DollarImpact11] decimal NOT NULL,
    [DollarImpact12] decimal NOT NULL,
    [DollarImpactTotal] decimal NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL
);

CREATE NONCLUSTERED INDEX [CORE_Dimensionality_FactReportEncountersToChargeDollars_Initial] ON [fp].[FactReportEncountersToChargeDollars_Initial] ([BudgetConfigID], [ServiceEntityID], [EntityID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [MSDRGID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [ServiceLineID], [ServiceLineRollupID], [DepartmentID], [UBRevCodeID], [PayorID], [PayorGroupID], [TimeClassID], [AdjustmentID]);
GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__0AE83FCD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Budge__1470DEB0] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__156502E9] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Entit__16592722] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Patie__174D4B5B] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__AgeCo__18416F94] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Medic__193593CD] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__MSDRG__1A29B806] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Prima__1B1DDC3F] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1C120078] DEFAULT ((0)) FOR [ServiceProviderID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1D0624B1] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1DFA48EA] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1EEE6D23] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Depar__1FE2915C] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__UBRev__20D6B595] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Payor__21CAD9CE] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Payor__22BEFE07] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__TimeC__23B32240] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__24A74679] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__259B6AB2] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__268F8EEB] DEFAULT ('') FOR [AdjustmentAuthor]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2783B324] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2877D75D] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2A601FCF] DEFAULT ((0)) FOR [DollarImpact01]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2B544408] DEFAULT ((0)) FOR [DollarImpact02]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2C486841] DEFAULT ((0)) FOR [DollarImpact03]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF_FactReportEncountersToChargeDollars_Initial_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2D3C8C7A] DEFAULT ((0)) FOR [DollarImpact04]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2E30B0B3] DEFAULT ((0)) FOR [DollarImpact05]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2F24D4EC] DEFAULT ((0)) FOR [DollarImpact06]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__3018F925] DEFAULT ((0)) FOR [DollarImpact07]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__310D1D5E] DEFAULT ((0)) FOR [DollarImpact08]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__32014197] DEFAULT ((0)) FOR [DollarImpact09]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__32F565D0] DEFAULT ((0)) FOR [DollarImpact10]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__33E98A09] DEFAULT ((0)) FOR [DollarImpact11]; GO
ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__34DDAE42] DEFAULT ((0)) FOR [DollarImpact12]; GO

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

---------------------------------------------
-- fp.FactReportEncountersToStats ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncountersToStats] (
    [BudgetConfigID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PayorID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [AdjustmentDate] datetime NOT NULL,
    [AdjustmentAuthor] nvarchar(260) NOT NULL,
    [AdjustmentClassificationCategoryID] int NOT NULL,
    [AdjustmentClassificationGroupID] int NOT NULL,
    [AdjustmentComment] nvarchar(max) NOT NULL,
    [StatisticsImpact] decimal NOT NULL,
    [EncountersImpact] decimal NOT NULL,
    [ChargeVolumeImpact] decimal NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__09F41B94] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF_FactReportEncountersToStats_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Encou__2DD0BE00] DEFAULT ((0)) FOR [EncountersImpact]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Charg__2FB90672] DEFAULT ((0)) FOR [ChargeVolumeImpact]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Servi__54EA8B21] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Servi__56D2D393] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Budge__5E1EEFA0] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Servi__5F1313D9] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Entit__60073812] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Patie__60FB5C4B] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__AgeCo__61EF8084] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Medic__62E3A4BD] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__MSDRG__63D7C8F6] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Prima__64CBED2F] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Perfo__65C01168] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Provi__66B435A1] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Depar__67A859DA] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Accou__689C7E13] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Payor__6990A24C] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Finan__6A84C685] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__TimeC__6B78EABE] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Fisca__6C6D0EF7] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__6D613330] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__6E555769] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__6F497BA2] DEFAULT ('') FOR [AdjustmentAuthor]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__703D9FDB] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__7131C414] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Stati__731A0C86] DEFAULT ((0)) FOR [StatisticsImpact]; GO

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

---------------------------------------------
-- fp.FactReportEncountersToStats_Initial ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportEncountersToStats_Initial] (
    [BudgetConfigID] int NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PayorID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [AdjustmentDate] datetime NOT NULL,
    [AdjustmentAuthor] nvarchar(260) NOT NULL,
    [AdjustmentClassificationCategoryID] int NOT NULL,
    [AdjustmentClassificationGroupID] int NOT NULL,
    [AdjustmentComment] nvarchar(max) NOT NULL,
    [StatisticsImpact] decimal NOT NULL,
    [EncountersImpact] decimal NOT NULL,
    [ChargeVolumeImpact] decimal NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__0BDC6406] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Budge__1A33D9A7] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1B27FDE0] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Entit__1C1C2219] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Patie__1D104652] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__AgeCo__1E046A8B] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Medic__1EF88EC4] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__MSDRG__1FECB2FD] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Prima__20E0D736] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Perfo__21D4FB6F] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Provi__22C91FA8] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Depar__23BD43E1] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Accou__24B1681A] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Payor__25A58C53] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Finan__2699B08C] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__TimeC__278DD4C5] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Fisca__2881F8FE] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__29761D37] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2A6A4170] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2B5E65A9] DEFAULT ('') FOR [AdjustmentAuthor]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2C5289E2] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2D46AE1B] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF_FactReportEncountersToStats_Initial_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Encou__2EC4E239] DEFAULT ((0)) FOR [EncountersImpact]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Stati__2F2EF68D] DEFAULT ((0)) FOR [StatisticsImpact]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Charg__30AD2AAB] DEFAULT ((0)) FOR [ChargeVolumeImpact]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__55DEAF5A] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__57C6F7CC] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO

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

---------------------------------------------
-- fp.FactReportGeneralLedger ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedger] (
    [GeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [LockType] int NULL,
    [OriginalValue] decimal NULL,
    [Value] decimal NULL,
    [ManagerValue] decimal NULL,
    [Rate] decimal NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportGeneralLedger] ON [fp].[FactReportGeneralLedger] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [APEModelSectionID], [VariabilityID], [FiscalMonthID]);
CREATE NONCLUSTERED INDEX [NCNU_GeneralLedgerID] ON [fp].[FactReportGeneralLedger] ([GeneralLedgerID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportGeneralLedger] ([DepartmentID]);
GO
ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_OriginalValue] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_Value] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_ManagerValue] DEFAULT ((0)) FOR [ManagerValue]; GO
ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_Rate] DEFAULT ((0)) FOR [Rate]; GO
ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_LockType] DEFAULT ((0)) FOR [LockType]; GO

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

---------------------------------------------
-- fp.FactReportGeneralLedgerDataTransfer ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedgerDataTransfer] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [OriginalValue] decimal NULL,
    [Value] decimal NULL,
    [ManagerValue] decimal NULL,
    [Rate] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO

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

---------------------------------------------
-- fp.FactReportGeneralLedgerDataTransferSnapshot ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedgerDataTransferSnapshot] (
    [RowID] int NOT NULL,
    [SnapshotID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [OriginalValue] decimal NULL,
    [Value] decimal NULL,
    [ManagerValue] decimal NULL,
    [Rate] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO

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

---------------------------------------------
-- fp.FactReportGeneralLedgerHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedgerHistory] (
    [GeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportGeneralLedgerHistory] ON [fp].[FactReportGeneralLedgerHistory] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [APEModelSectionID], [VariabilityID], [FiscalMonthID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportGeneralLedgerHistory] ([DepartmentID]);
GO

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

---------------------------------------------
-- fp.FactReportGeneralLedgerHistoryDataTransfer ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedgerHistoryDataTransfer] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO

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

---------------------------------------------
-- fp.FactReportGeneralLedgerHistory_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedgerHistory_archive] (
    [GeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL
);
GO

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

---------------------------------------------
-- fp.FactReportGeneralLedgerSnapshot ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedgerSnapshot] (
    [GeneralLedgerID] int NOT NULL,
    [SnapshotID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [LockType] tinyint NULL,
    [OriginalValue] decimal NULL,
    [Value] decimal NULL,
    [ManagerValue] decimal NULL,
    [Rate] decimal NULL
);
GO
ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__LockT__566C1E65] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__Origi__5760429E] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__Value__585466D7] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__Manag__59488B10] DEFAULT ((0)) FOR [ManagerValue]; GO
ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactReport__Rate__5A3CAF49] DEFAULT ((0)) FOR [Rate]; GO

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

---------------------------------------------
-- fp.FactReportGeneralLedger_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportGeneralLedger_archive] (
    [GeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [LockType] tinyint NULL,
    [OriginalValue] decimal NULL,
    [Value] decimal NULL,
    [ManagerValue] decimal NULL,
    [Rate] decimal NULL
);
GO

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

---------------------------------------------
-- fp.FactReportReimbursement ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportReimbursement] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [NCNU_FactReportReimbursement_RowID] ON [fp].[FactReportReimbursement] ([RowID]);
CREATE NONCLUSTERED INDEX [NCNU_FactReportReimbursement_EntityID] ON [fp].[FactReportReimbursement] ([EntityID], [PayorGroupID], [PatientClassID]);
GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Budge__4E3FEF97] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Entit__4F3413D0] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Entit__50283809] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Patie__511C5C42] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Payor__5210807B] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Payor__5304A4B4] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Servi__53F8C8ED] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Servi__54ECED26] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__MSDRG__55E1115F] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Medic__56D53598] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Prima__57C959D1] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__UnitT__58BD7E0A] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__TimeC__59B1A243] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Fisca__5AA5C67C] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Fisca__5B99EAB5] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Value__5C8E0EEE] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.FactReportStaffing ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStaffing] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NULL,
    [PayCodeGroupID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportStaffing] ON [fp].[FactReportStaffing] ([BudgetConfigID], [UnitTypeID], [TimeClassID], [FiscalYearID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID], [FiscalMonthID], [EmployeeID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStaffing] ([DepartmentID]);
GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [FK_FacReporttStaffing_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Emplo__0FEA8A07] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [df_FactReportStaffing_OriginalValue] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [df_FactReportStaffing_Value] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [df_FactReportStaffing_ManagerValue] DEFAULT ((0)) FOR [ManagerValue]; GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__577E75B7] DEFAULT ('0') FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__587299F0] DEFAULT ('0') FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__5966BE29] DEFAULT ('0') FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__5A5AE262] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO

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

---------------------------------------------
-- fp.FactReportStaffingHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStaffingHistory] (
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [Value] decimal NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportStaffingHistory] ON [fp].[FactReportStaffingHistory] ([BudgetConfigID], [UnitTypeID], [TimeClassID], [FiscalYearID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [FiscalMonthID], [EmployeeID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStaffingHistory] ([DepartmentID]);
GO
ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [FK_FacReporttStaffingHistory_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Emplo__11D2D279] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__5F1F977F] DEFAULT ('0') FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__6013BBB8] DEFAULT ('0') FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__6107DFF1] DEFAULT ('0') FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__61FC042A] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO

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

---------------------------------------------
-- fp.FactReportStaffingHistory_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStaffingHistory_archive] (
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [Value] decimal NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportStaffingHistory_archive] ON [fp].[FactReportStaffingHistory_archive] ([BudgetConfigID], [UnitTypeID], [TimeClassID], [FiscalYearID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [FiscalMonthID], [EmployeeID]);
GO
ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Emplo__1741930C] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__62F02863] DEFAULT ('0') FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__63E44C9C] DEFAULT ('0') FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__64D870D5] DEFAULT ('0') FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__65CC950E] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO

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

---------------------------------------------
-- fp.FactReportStaffing_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStaffing_archive] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NULL,
    [PayCodeGroupID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL
);
GO
ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Emplo__164D6ED3] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5B4F069B] DEFAULT ('0') FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5C432AD4] DEFAULT ('0') FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5D374F0D] DEFAULT ('0') FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5E2B7346] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO

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

---------------------------------------------
-- fp.FactReportStatistics ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStatistics] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] smallint NOT NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportStatistics] ON [fp].[FactReportStatistics] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [EntityID], [DepartmentID], [AccountID], [PatientClassID], [PayorID], [FinancialReportingID], [UnitTypeID], [FiscalMonthID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStatistics] ([DepartmentID]);
GO
ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1C9C105D] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1D903496] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1E8458CF] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1F787D08] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [df_FactReportStatistics_OriginalValue] DEFAULT ((0)) FOR [OriginalValue]; GO
ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [df_FactReportStatistics_Value] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [df_FactReportStatistics_ManagerValue] DEFAULT ((0)) FOR [ManagerValue]; GO

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

---------------------------------------------
-- fp.FactReportStatisticsDataTransfer ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStatisticsDataTransfer] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] smallint NOT NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO

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

---------------------------------------------
-- fp.FactReportStatisticsHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStatisticsHistory] (
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [Value] decimal NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportStatisticsHistory] ON [fp].[FactReportStatisticsHistory] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [FiscalMonthID]);
CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStatisticsHistory] ([DepartmentID]);
GO
ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__243D3225] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__2531565E] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__26257A97] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__27199ED0] DEFAULT ((0)) FOR [ProviderTypeID]; GO

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

---------------------------------------------
-- fp.FactReportStatisticsHistoryDataTransfer ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStatisticsHistoryDataTransfer] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [Value] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO

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

---------------------------------------------
-- fp.FactReportStatisticsHistory_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStatisticsHistory_archive] (
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalYearID] int NULL,
    [FiscalMonthID] tinyint NULL,
    [Value] decimal NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL
);

CREATE CLUSTERED INDEX [IDX_FactReportStatisticsHistory_archive] ON [fp].[FactReportStatisticsHistory_archive] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [FiscalMonthID]);
GO
ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__280DC309] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2901E742] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__29F60B7B] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2AEA2FB4] DEFAULT ((0)) FOR [ProviderTypeID]; GO

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

---------------------------------------------
-- fp.FactReportStatistics_archive ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportStatistics_archive] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] int NOT NULL,
    [FiscalMonthID] tinyint NULL,
    [FiscalYearID] smallint NOT NULL,
    [OriginalValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [ManagerValue] decimal NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL
);
GO
ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__206CA141] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2160C57A] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2254E9B3] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__23490DEC] DEFAULT ((0)) FOR [ProviderTypeID]; GO

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

---------------------------------------------
-- fp.FactReportingAP ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportingAP] (
    [RowID] bigint NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [EntityID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [FiscalYearID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [CostComponentID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [ActualDollars] decimal NOT NULL,
    [BudgetDollars] decimal NOT NULL,
    [ProjectedDollars] decimal NOT NULL,
    [TargetDollars] decimal NOT NULL,
    [FlexDollars] decimal NOT NULL,
    [ActualUnits] decimal NOT NULL,
    [BudgetUnits] decimal NOT NULL,
    [ProjectedUnits] decimal NOT NULL,
    [TargetUnits] decimal NOT NULL,
    [FlexUnits] decimal NOT NULL,
    [ActualHours] decimal NOT NULL,
    [BudgetHours] decimal NOT NULL,
    [ProjectedHours] decimal NOT NULL,
    [TargetHours] decimal NOT NULL,
    [FlexHours] decimal NOT NULL,
    [ActualFTEs] decimal NOT NULL,
    [BudgetFTEs] decimal NOT NULL,
    [ProjectedFTEs] decimal NOT NULL,
    [TargetFTEs] decimal NOT NULL,
    [FlexFTEs] decimal NOT NULL,
    [ActualDollarsYTD] decimal NOT NULL,
    [BudgetDollarsYTD] decimal NOT NULL,
    [ProjectedDollarsYTD] decimal NOT NULL,
    [TargetDollarsYTD] decimal NOT NULL,
    [FlexDollarsYTD] decimal NOT NULL,
    [ActualUnitsYTD] decimal NOT NULL,
    [BudgetUnitsYTD] decimal NOT NULL,
    [ProjectedUnitsYTD] decimal NOT NULL,
    [TargetUnitsYTD] decimal NOT NULL,
    [FlexUnitsYTD] decimal NOT NULL,
    [ActualHoursYTD] decimal NOT NULL,
    [BudgetHoursYTD] decimal NOT NULL,
    [ProjectedHoursYTD] decimal NOT NULL,
    [TargetHoursYTD] decimal NOT NULL,
    [FlexHoursYTD] decimal NOT NULL,
    [ActualFTEsYTD] decimal NOT NULL,
    [BudgetFTEsYTD] decimal NOT NULL,
    [ProjectedFTEsYTD] decimal NOT NULL,
    [TargetFTEsYTD] decimal NOT NULL,
    [FlexFTEsYTD] decimal NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] bit NOT NULL,
    [IsPrimaryNonStaffingStatistic] bit NOT NULL,
    [IsPrimaryRevenueStatistic] bit NOT NULL,
    [IsPrimaryStaffingStatistic] bit NOT NULL,
    [InitialUnits] decimal NOT NULL,
    [InitialDollars] decimal NOT NULL,
    [InitialHours] decimal NOT NULL,
    [InitialFTEs] decimal NOT NULL,
    [FiscalTimeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [NCNU_FactReportingAP_FiscalYearFiscalMonth] ON [fp].[FactReportingAP] ([FiscalYearID], [FiscalMonthID]);
GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__79DC18AE] DEFAULT ((0)) FOR [BudgetHoursYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsPri__7A92A7CA] DEFAULT ((0)) FOR [IsPrimaryRevenueStatistic]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__7AD03CE7] DEFAULT ((0)) FOR [ProjectedHoursYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsPri__7B86CC03] DEFAULT ((0)) FOR [IsPrimaryStaffingStatistic]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__7BC46120] DEFAULT ((0)) FOR [TargetHoursYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexH__7CB88559] DEFAULT ((0)) FOR [FlexHoursYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__7DACA992] DEFAULT ((0)) FOR [ActualFTEsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__7EA0CDCB] DEFAULT ((0)) FOR [BudgetFTEsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__7F94F204] DEFAULT ((0)) FOR [ProjectedFTEsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Fisca__37E69A24] DEFAULT ((0)) FOR [FiscalTimeID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__0089163D] DEFAULT ((0)) FOR [TargetFTEsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexF__017D3A76] DEFAULT ((0)) FOR [FlexFTEsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Depar__4D097237] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Accou__4DFD9670] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Entit__4EF1BAA9] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Varia__4FE5DEE2] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Fisca__50DA031B] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Fisca__51CE2754] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Patie__52C24B8D] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Payor__53B66FC6] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__JobCo__54AA93FF] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__PayCo__559EB838] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Produ__5692DC71] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Emplo__578700AA] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5A85CAEB] DEFAULT ((0)) FOR [InitialUnits]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Charg__587B24E3] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5B79EF24] DEFAULT ((0)) FOR [InitialDollars]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Servi__596F491C] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5C6E135D] DEFAULT ((0)) FOR [InitialHours]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__CostC__5A636D55] DEFAULT ((0)) FOR [CostComponentID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5D623796] DEFAULT ((0)) FOR [InitialFTEs]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Finan__5B57918E] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__5C4BB5C7] DEFAULT ((0)) FOR [ActualDollars]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__5D3FDA00] DEFAULT ((0)) FOR [BudgetDollars]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__5E33FE39] DEFAULT ((0)) FOR [ProjectedDollars]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__5F282272] DEFAULT ((0)) FOR [TargetDollars]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexD__601C46AB] DEFAULT ((0)) FOR [FlexDollars]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__61106AE4] DEFAULT ((0)) FOR [ActualUnits]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__62048F1D] DEFAULT ((0)) FOR [BudgetUnits]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsDel__628E9F02] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__62F8B356] DEFAULT ((0)) FOR [ProjectedUnits]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Histo__6382C33B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__63ECD78F] DEFAULT ((0)) FOR [TargetUnits]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Trans__6476E774] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexU__64E0FBC8] DEFAULT ((0)) FOR [FlexUnits]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__65D52001] DEFAULT ((0)) FOR [ActualHours]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__66C9443A] DEFAULT ((0)) FOR [BudgetHours]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__67BD6873] DEFAULT ((0)) FOR [ProjectedHours]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__68B18CAC] DEFAULT ((0)) FOR [TargetHours]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexH__69A5B0E5] DEFAULT ((0)) FOR [FlexHours]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__6A99D51E] DEFAULT ((0)) FOR [ActualFTEs]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__6B8DF957] DEFAULT ((0)) FOR [BudgetFTEs]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__6C821D90] DEFAULT ((0)) FOR [ProjectedFTEs]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__6D7641C9] DEFAULT ((0)) FOR [TargetFTEs]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexF__6E6A6602] DEFAULT ((0)) FOR [FlexFTEs]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__6F5E8A3B] DEFAULT ((0)) FOR [ActualDollarsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__7052AE74] DEFAULT ((0)) FOR [BudgetDollarsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__7146D2AD] DEFAULT ((0)) FOR [ProjectedDollarsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__723AF6E6] DEFAULT ((0)) FOR [TargetDollarsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexD__732F1B1F] DEFAULT ((0)) FOR [FlexDollarsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__74233F58] DEFAULT ((0)) FOR [ActualUnitsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__75176391] DEFAULT ((0)) FOR [BudgetUnitsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__760B87CA] DEFAULT ((0)) FOR [ProjectedUnitsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__76FFAC03] DEFAULT ((0)) FOR [TargetUnitsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexU__77F3D03C] DEFAULT ((0)) FOR [FlexUnitsYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__78E7F475] DEFAULT ((0)) FOR [ActualHoursYTD]; GO
ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsPri__799E8391] DEFAULT ((0)) FOR [IsPrimaryNonStaffingStatistic]; GO

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

---------------------------------------------
-- fp.FactReportingAPCharges ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportingAPCharges] (
    [RowID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [ServiceEntityID] int NOT NULL,
    [UBRevenueCodeID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [PhysicianID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [PerformingProviderID] int NOT NULL,
    [PerformingPhysicianSpecialtyID] int NOT NULL,
    [BilledCPTID] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [ActualUnits01] decimal NOT NULL,
    [ActualUnits02] decimal NOT NULL,
    [ActualUnits03] decimal NOT NULL,
    [ActualUnits04] decimal NOT NULL,
    [ActualUnits05] decimal NOT NULL,
    [ActualUnits06] decimal NOT NULL,
    [ActualUnits07] decimal NOT NULL,
    [ActualUnits08] decimal NOT NULL,
    [ActualUnits09] decimal NOT NULL,
    [ActualUnits10] decimal NOT NULL,
    [ActualUnits11] decimal NOT NULL,
    [ActualUnits12] decimal NOT NULL,
    [BudgetUnits01] decimal NOT NULL,
    [BudgetUnits02] decimal NOT NULL,
    [BudgetUnits03] decimal NOT NULL,
    [BudgetUnits04] decimal NOT NULL,
    [BudgetUnits05] decimal NOT NULL,
    [BudgetUnits06] decimal NOT NULL,
    [BudgetUnits07] decimal NOT NULL,
    [BudgetUnits08] decimal NOT NULL,
    [BudgetUnits09] decimal NOT NULL,
    [BudgetUnits10] decimal NOT NULL,
    [BudgetUnits11] decimal NOT NULL,
    [BudgetUnits12] decimal NOT NULL,
    [ProjectedUnits01] decimal NOT NULL,
    [ProjectedUnits02] decimal NOT NULL,
    [ProjectedUnits03] decimal NOT NULL,
    [ProjectedUnits04] decimal NOT NULL,
    [ProjectedUnits05] decimal NOT NULL,
    [ProjectedUnits06] decimal NOT NULL,
    [ProjectedUnits07] decimal NOT NULL,
    [ProjectedUnits08] decimal NOT NULL,
    [ProjectedUnits09] decimal NOT NULL,
    [ProjectedUnits10] decimal NOT NULL,
    [ProjectedUnits11] decimal NOT NULL,
    [ProjectedUnits12] decimal NOT NULL,
    [TargetUnits01] decimal NOT NULL,
    [TargetUnits02] decimal NOT NULL,
    [TargetUnits03] decimal NOT NULL,
    [TargetUnits04] decimal NOT NULL,
    [TargetUnits05] decimal NOT NULL,
    [TargetUnits06] decimal NOT NULL,
    [TargetUnits07] decimal NOT NULL,
    [TargetUnits08] decimal NOT NULL,
    [TargetUnits09] decimal NOT NULL,
    [TargetUnits10] decimal NOT NULL,
    [TargetUnits11] decimal NOT NULL,
    [TargetUnits12] decimal NOT NULL,
    [ActualDollars01] decimal NOT NULL,
    [ActualDollars02] decimal NOT NULL,
    [ActualDollars03] decimal NOT NULL,
    [ActualDollars04] decimal NOT NULL,
    [ActualDollars05] decimal NOT NULL,
    [ActualDollars06] decimal NOT NULL,
    [ActualDollars07] decimal NOT NULL,
    [ActualDollars08] decimal NOT NULL,
    [ActualDollars09] decimal NOT NULL,
    [ActualDollars10] decimal NOT NULL,
    [ActualDollars11] decimal NOT NULL,
    [ActualDollars12] decimal NOT NULL,
    [BudgetDollars01] decimal NOT NULL,
    [BudgetDollars02] decimal NOT NULL,
    [BudgetDollars03] decimal NOT NULL,
    [BudgetDollars04] decimal NOT NULL,
    [BudgetDollars05] decimal NOT NULL,
    [BudgetDollars06] decimal NOT NULL,
    [BudgetDollars07] decimal NOT NULL,
    [BudgetDollars08] decimal NOT NULL,
    [BudgetDollars09] decimal NOT NULL,
    [BudgetDollars10] decimal NOT NULL,
    [BudgetDollars11] decimal NOT NULL,
    [BudgetDollars12] decimal NOT NULL,
    [ProjectedDollars01] decimal NOT NULL,
    [ProjectedDollars02] decimal NOT NULL,
    [ProjectedDollars03] decimal NOT NULL,
    [ProjectedDollars04] decimal NOT NULL,
    [ProjectedDollars05] decimal NOT NULL,
    [ProjectedDollars06] decimal NOT NULL,
    [ProjectedDollars07] decimal NOT NULL,
    [ProjectedDollars08] decimal NOT NULL,
    [ProjectedDollars09] decimal NOT NULL,
    [ProjectedDollars10] decimal NOT NULL,
    [ProjectedDollars11] decimal NOT NULL,
    [ProjectedDollars12] decimal NOT NULL,
    [TargetDollars01] decimal NOT NULL,
    [TargetDollars02] decimal NOT NULL,
    [TargetDollars03] decimal NOT NULL,
    [TargetDollars04] decimal NOT NULL,
    [TargetDollars05] decimal NOT NULL,
    [TargetDollars06] decimal NOT NULL,
    [TargetDollars07] decimal NOT NULL,
    [TargetDollars08] decimal NOT NULL,
    [TargetDollars09] decimal NOT NULL,
    [TargetDollars10] decimal NOT NULL,
    [TargetDollars11] decimal NOT NULL,
    [TargetDollars12] decimal NOT NULL,
    [ActualUnitsTotal] decimal NOT NULL,
    [BudgetUnitsTotal] decimal NOT NULL,
    [ProjectedUnitsTotal] decimal NOT NULL,
    [TargetUnitsTotal] decimal NOT NULL,
    [ActualDollarsTotal] decimal NOT NULL,
    [BudgetDollarsTotal] decimal NOT NULL,
    [ProjectedDollarsTotal] decimal NOT NULL,
    [TargetDollarsTotal] decimal NOT NULL,
    [MSDRGRollupID] int NOT NULL,
    [InitialUnits01] decimal NOT NULL,
    [InitialUnits02] decimal NOT NULL,
    [InitialUnits03] decimal NOT NULL,
    [InitialUnits04] decimal NOT NULL,
    [InitialUnits05] decimal NOT NULL,
    [InitialUnits06] decimal NOT NULL,
    [InitialUnits07] decimal NOT NULL,
    [InitialUnits08] decimal NOT NULL,
    [InitialUnits09] decimal NOT NULL,
    [InitialUnits10] decimal NOT NULL,
    [InitialUnits11] decimal NOT NULL,
    [InitialUnits12] decimal NOT NULL,
    [InitialDollars01] decimal NOT NULL,
    [InitialDollars02] decimal NOT NULL,
    [InitialDollars03] decimal NOT NULL,
    [InitialDollars04] decimal NOT NULL,
    [InitialDollars05] decimal NOT NULL,
    [InitialDollars06] decimal NOT NULL,
    [InitialDollars07] decimal NOT NULL,
    [InitialDollars08] decimal NOT NULL,
    [InitialDollars09] decimal NOT NULL,
    [InitialDollars10] decimal NOT NULL,
    [InitialDollars11] decimal NOT NULL,
    [InitialDollars12] decimal NOT NULL,
    [InitialUnitsTotal] decimal NOT NULL,
    [InitialDollarsTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__AgeCo__257D05CF] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Charg__294D96B3] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Depar__1FC42C79] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Entit__1DDBE407] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Fisca__2B35DF25] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Medic__27654E41] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__MSDRG__57DE686A] FOREIGN KEY ([MSDRGRollupID]) REFERENCES [dss].[DimMSDRGRollup] ([MSDRGRollupID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Patie__2394BD5D] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Physi__34BF495F] FOREIGN KEY ([PhysicianID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Physi__36A791D1] FOREIGN KEY ([PhysicianSpecialtyID]) REFERENCES [dss].[DimPhysicianSpecialty] ([PhysicianSpecialtyID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Servi__21AC74EB] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__UBRev__31E2DCB4] FOREIGN KEY ([UBRevenueCodeID]) REFERENCES [dss].[DimUBRevenueCode] ([UBRevenueCodeID]); GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__002163EE] DEFAULT ((0)) FOR [BudgetUnits11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__01158827] DEFAULT ((0)) FOR [BudgetUnits12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0209AC60] DEFAULT ((0)) FOR [ProjectedUnits01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__02FDD099] DEFAULT ((0)) FOR [ProjectedUnits02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__03F1F4D2] DEFAULT ((0)) FOR [ProjectedUnits03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__04E6190B] DEFAULT ((0)) FOR [ProjectedUnits04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__05DA3D44] DEFAULT ((0)) FOR [ProjectedUnits05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__06CE617D] DEFAULT ((0)) FOR [ProjectedUnits06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__07C285B6] DEFAULT ((0)) FOR [ProjectedUnits07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__08B6A9EF] DEFAULT ((0)) FOR [ProjectedUnits08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__09AACE28] DEFAULT ((0)) FOR [ProjectedUnits09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0A9EF261] DEFAULT ((0)) FOR [ProjectedUnits10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0B93169A] DEFAULT ((0)) FOR [ProjectedUnits11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0C873AD3] DEFAULT ((0)) FOR [ProjectedUnits12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__0D7B5F0C] DEFAULT ((0)) FOR [TargetUnits01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__0E6F8345] DEFAULT ((0)) FOR [TargetUnits02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__0F63A77E] DEFAULT ((0)) FOR [TargetUnits03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__1057CBB7] DEFAULT ((0)) FOR [TargetUnits04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__114BEFF0] DEFAULT ((0)) FOR [TargetUnits05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__12401429] DEFAULT ((0)) FOR [TargetUnits06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__13343862] DEFAULT ((0)) FOR [TargetUnits07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__14285C9B] DEFAULT ((0)) FOR [TargetUnits08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__151C80D4] DEFAULT ((0)) FOR [TargetUnits09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__1610A50D] DEFAULT ((0)) FOR [TargetUnits10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__1704C946] DEFAULT ((0)) FOR [TargetUnits11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__17F8ED7F] DEFAULT ((0)) FOR [TargetUnits12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__18ED11B8] DEFAULT ((0)) FOR [ActualDollars01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__19E135F1] DEFAULT ((0)) FOR [ActualDollars02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1AD55A2A] DEFAULT ((0)) FOR [ActualDollars03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1BC97E63] DEFAULT ((0)) FOR [ActualDollars04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1CBDA29C] DEFAULT ((0)) FOR [ActualDollars05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Entit__1CE7BFCE] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1DB1C6D5] DEFAULT ((0)) FOR [ActualDollars06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1EA5EB0E] DEFAULT ((0)) FOR [ActualDollars07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Depar__1ED00840] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1F9A0F47] DEFAULT ((0)) FOR [ActualDollars08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__208E3380] DEFAULT ((0)) FOR [ActualDollars09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Servi__20B850B2] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__218257B9] DEFAULT ((0)) FOR [ActualDollars10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__22767BF2] DEFAULT ((0)) FOR [ActualDollars11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Patie__22A09924] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__236AA02B] DEFAULT ((0)) FOR [ActualDollars12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__245EC464] DEFAULT ((0)) FOR [BudgetDollars01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__AgeCo__2488E196] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2552E89D] DEFAULT ((0)) FOR [BudgetDollars02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__26470CD6] DEFAULT ((0)) FOR [BudgetDollars03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Medic__26712A08] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__273B310F] DEFAULT ((0)) FOR [BudgetDollars04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__282F5548] DEFAULT ((0)) FOR [BudgetDollars05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Charg__2859727A] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__29237981] DEFAULT ((0)) FOR [BudgetDollars06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2A179DBA] DEFAULT ((0)) FOR [BudgetDollars07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Fisca__2A41BAEC] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2B0BC1F3] DEFAULT ((0)) FOR [BudgetDollars08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2BFFE62C] DEFAULT ((0)) FOR [BudgetDollars09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2CF40A65] DEFAULT ((0)) FOR [BudgetDollars10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2DE82E9E] DEFAULT ((0)) FOR [BudgetDollars11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Servi__2E124BD0] DEFAULT ((0)) FOR [ServiceEntityID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2EDC52D7] DEFAULT ((0)) FOR [BudgetDollars12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__2FD07710] DEFAULT ((0)) FOR [ProjectedDollars01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__30C49B49] DEFAULT ((0)) FOR [ProjectedDollars02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__UBRev__30EEB87B] DEFAULT ((0)) FOR [UBRevenueCodeID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__31B8BF82] DEFAULT ((0)) FOR [ProjectedDollars03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__32ACE3BB] DEFAULT ((0)) FOR [ProjectedDollars04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Prima__32D700ED] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__33A107F4] DEFAULT ((0)) FOR [ProjectedDollars05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Physi__33CB2526] DEFAULT ((0)) FOR [PhysicianID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__34952C2D] DEFAULT ((0)) FOR [ProjectedDollars06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__35895066] DEFAULT ((0)) FOR [ProjectedDollars07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Physi__35B36D98] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__367D749F] DEFAULT ((0)) FOR [ProjectedDollars08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__377198D8] DEFAULT ((0)) FOR [ProjectedDollars09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Perfo__379BB60A] DEFAULT ((0)) FOR [PerformingProviderID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__3865BD11] DEFAULT ((0)) FOR [ProjectedDollars10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Perfo__388FDA43] DEFAULT ((0)) FOR [PerformingPhysicianSpecialtyID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__3959E14A] DEFAULT ((0)) FOR [ProjectedDollars11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Bille__3983FE7C] DEFAULT ((0)) FOR [BilledCPTID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__3A4E0583] DEFAULT ((0)) FOR [ProjectedDollars12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3B4229BC] DEFAULT ((0)) FOR [TargetDollars01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3C364DF5] DEFAULT ((0)) FOR [TargetDollars02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3D2A722E] DEFAULT ((0)) FOR [TargetDollars03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3E1E9667] DEFAULT ((0)) FOR [TargetDollars04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3F12BAA0] DEFAULT ((0)) FOR [TargetDollars05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__4006DED9] DEFAULT ((0)) FOR [TargetDollars06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__40FB0312] DEFAULT ((0)) FOR [TargetDollars07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__41EF274B] DEFAULT ((0)) FOR [TargetDollars08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__IsDel__4219447D] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__42E34B84] DEFAULT ((0)) FOR [TargetDollars09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Histo__430D68B6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__43D76FBD] DEFAULT ((0)) FOR [TargetDollars10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Trans__44018CEF] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__44CB93F6] DEFAULT ((0)) FOR [TargetDollars11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__45BFB82F] DEFAULT ((0)) FOR [TargetDollars12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__MSDRG__56EA4431] DEFAULT ((0)) FOR [MSDRGRollupID]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__5E565BCF] DEFAULT ((0)) FOR [InitialUnits01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__5F4A8008] DEFAULT ((0)) FOR [InitialUnits02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__603EA441] DEFAULT ((0)) FOR [InitialUnits03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6132C87A] DEFAULT ((0)) FOR [InitialUnits04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6226ECB3] DEFAULT ((0)) FOR [InitialUnits05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__631B10EC] DEFAULT ((0)) FOR [InitialUnits06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__640F3525] DEFAULT ((0)) FOR [InitialUnits07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6503595E] DEFAULT ((0)) FOR [InitialUnits08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__65F77D97] DEFAULT ((0)) FOR [InitialUnits09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__66EBA1D0] DEFAULT ((0)) FOR [InitialUnits10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__67DFC609] DEFAULT ((0)) FOR [InitialUnits11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__68D3EA42] DEFAULT ((0)) FOR [InitialUnits12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__69C80E7B] DEFAULT ((0)) FOR [InitialDollars01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6ABC32B4] DEFAULT ((0)) FOR [InitialDollars02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6B264708] DEFAULT ((0)) FOR [ActualUnits01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6BB056ED] DEFAULT ((0)) FOR [InitialDollars03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6C1A6B41] DEFAULT ((0)) FOR [ActualUnits02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6CA47B26] DEFAULT ((0)) FOR [InitialDollars04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6D0E8F7A] DEFAULT ((0)) FOR [ActualUnits03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6D989F5F] DEFAULT ((0)) FOR [InitialDollars05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6E02B3B3] DEFAULT ((0)) FOR [ActualUnits04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6E8CC398] DEFAULT ((0)) FOR [InitialDollars06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6EF6D7EC] DEFAULT ((0)) FOR [ActualUnits05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6F80E7D1] DEFAULT ((0)) FOR [InitialDollars07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6FEAFC25] DEFAULT ((0)) FOR [ActualUnits06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__70750C0A] DEFAULT ((0)) FOR [InitialDollars08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__70DF205E] DEFAULT ((0)) FOR [ActualUnits07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__71693043] DEFAULT ((0)) FOR [InitialDollars09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__71D34497] DEFAULT ((0)) FOR [ActualUnits08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__725D547C] DEFAULT ((0)) FOR [InitialDollars10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__72C768D0] DEFAULT ((0)) FOR [ActualUnits09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__735178B5] DEFAULT ((0)) FOR [InitialDollars11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__73BB8D09] DEFAULT ((0)) FOR [ActualUnits10]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__74459CEE] DEFAULT ((0)) FOR [InitialDollars12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__74AFB142] DEFAULT ((0)) FOR [ActualUnits11]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__75A3D57B] DEFAULT ((0)) FOR [ActualUnits12]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7697F9B4] DEFAULT ((0)) FOR [BudgetUnits01]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__778C1DED] DEFAULT ((0)) FOR [BudgetUnits02]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__78804226] DEFAULT ((0)) FOR [BudgetUnits03]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7974665F] DEFAULT ((0)) FOR [BudgetUnits04]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7A688A98] DEFAULT ((0)) FOR [BudgetUnits05]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7B5CAED1] DEFAULT ((0)) FOR [BudgetUnits06]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7C50D30A] DEFAULT ((0)) FOR [BudgetUnits07]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7D44F743] DEFAULT ((0)) FOR [BudgetUnits08]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7E391B7C] DEFAULT ((0)) FOR [BudgetUnits09]; GO
ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7F2D3FB5] DEFAULT ((0)) FOR [BudgetUnits10]; GO

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

---------------------------------------------
-- fp.FactReportingAPEncounters ------------------
---------------------------------------------
CREATE TABLE [fp].[FactReportingAPEncounters] (
    [RowID] int NOT NULL,
    [IsDeleted] bit NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [Version] timestamp NOT NULL,
    [TransactionID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [ActualEncounters] decimal NOT NULL,
    [ActualEncountersYTD] decimal NOT NULL,
    [BudgetEncounters] decimal NOT NULL,
    [ProjectedEncounters] decimal NOT NULL,
    [TargetEncounters] decimal NOT NULL,
    [MSDRGRollupID] int NOT NULL,
    [InitialEncounters] decimal NOT NULL,
    [FiscalTimeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__IsDel__0AFE19BD] DEFAULT ((0)) FOR [IsDeleted]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Histo__0BF23DF6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Trans__0CE6622F] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Entit__0DDA8668] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Patie__0ECEAAA1] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Servi__0FC2CEDA] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Servi__10B6F313] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__AgeCo__11AB174C] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Medic__129F3B85] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Depar__13935FBE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Payor__148783F7] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Payor__157BA830] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__CPTID__1763F0A2] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Provi__185814DB] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Physi__194C3914] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Fisca__1A405D4D] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Fisca__1B348186] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Actua__1C28A5BF] DEFAULT ((0)) FOR [ActualEncounters]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Actua__1D1CC9F8] DEFAULT ((0)) FOR [ActualEncountersYTD]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Budge__1E10EE31] DEFAULT ((0)) FOR [BudgetEncounters]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Proje__1F05126A] DEFAULT ((0)) FOR [ProjectedEncounters]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Targe__1FF936A3] DEFAULT ((0)) FOR [TargetEncounters]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Fisca__38DABE5D] DEFAULT ((0)) FOR [FiscalTimeID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__MSDRG__58D28CA3] DEFAULT ((0)) FOR [MSDRGRollupID]; GO
ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Initi__7539C127] DEFAULT ((0)) FOR [InitialEncounters]; GO

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

---------------------------------------------
-- fp.FactStaffingVariabilityDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[FactStaffingVariabilityDetail] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeID] int NOT NULL,
    [FixedPercentage] decimal NOT NULL,
    [RowID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_FactPayrollVariabilityDetail] ON [fp].[FactStaffingVariabilityDetail] ([EntityGroupConfigGUID], [DepartmentID], [JobCodeID], [PayCodeID], [ProviderLineItemID]);
GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [FK_FactStaffingVariabilityDetail_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [FK_FactStaffingVariabilityDetail_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_FixedPercentage] DEFAULT ((0.0)) FOR [FixedPercentage]; GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF__FactStaff__Emplo__6ADC2E45] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF__FactStaff__Provi__72CFF3C3] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactStaffingVariabilityDetail_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO

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

---------------------------------------------
-- fp.FactStatistics ------------------
---------------------------------------------
CREATE TABLE [fp].[FactStatistics] (
    [StatisticsID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    [InitialBudgetRate01] decimal NOT NULL,
    [InitialBudgetRate02] decimal NOT NULL,
    [InitialBudgetRate03] decimal NOT NULL,
    [InitialBudgetRate04] decimal NOT NULL,
    [InitialBudgetRate05] decimal NOT NULL,
    [InitialBudgetRate06] decimal NOT NULL,
    [InitialBudgetRate07] decimal NOT NULL,
    [InitialBudgetRate08] decimal NOT NULL,
    [InitialBudgetRate09] decimal NOT NULL,
    [InitialBudgetRate10] decimal NOT NULL,
    [InitialBudgetRate11] decimal NOT NULL,
    [InitialBudgetRate12] decimal NOT NULL,
    [InitialProjectionRate01] decimal NOT NULL,
    [InitialProjectionRate02] decimal NOT NULL,
    [InitialProjectionRate03] decimal NOT NULL,
    [InitialProjectionRate04] decimal NOT NULL,
    [InitialProjectionRate05] decimal NOT NULL,
    [InitialProjectionRate06] decimal NOT NULL,
    [InitialProjectionRate07] decimal NOT NULL,
    [InitialProjectionRate08] decimal NOT NULL,
    [InitialProjectionRate09] decimal NOT NULL,
    [InitialProjectionRate10] decimal NOT NULL,
    [InitialProjectionRate11] decimal NOT NULL,
    [InitialProjectionRate12] decimal NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([StatisticsID])
);

CREATE CLUSTERED INDEX [IX_FactStatistics] ON [fp].[FactStatistics] ([StatisticsID]);
CREATE NONCLUSTERED INDEX [IX_FactStatistics_Account] ON [fp].[FactStatistics] ([AccountID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactStatistics_BudgetConfig] ON [fp].[FactStatistics] ([BudgetConfigID]) INCLUDE ([StatisticsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactStatistics_Department] ON [fp].[FactStatistics] ([DepartmentID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactStatistics_Entity] ON [fp].[FactStatistics] ([EntityID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_FactStatistics_FinancialReporting] ON [fp].[FactStatistics] ([FinancialReportingID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [PayorID], [PatientClassID], [UnitTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatistics] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PatientClassID], [PayorID], [UnitTypeID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID]);
GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__0009F350] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [df_Stat_SubsectionID] DEFAULT ('1') FOR [SubsectionID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Budge__27D0C779] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Entit__28C4EBB2] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Entit__29B90FEB] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Depar__2AAD3424] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2B495710] DEFAULT ((0)) FOR [InitialBudgetRate01]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Accou__2BA1585D] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2C3D7B49] DEFAULT ((0)) FOR [InitialBudgetRate02]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Finan__2C957C96] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2D319F82] DEFAULT ((0)) FOR [InitialBudgetRate03]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Payor__2D89A0CF] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2E25C3BB] DEFAULT ((0)) FOR [InitialBudgetRate04]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Patie__2E7DC508] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2F19E7F4] DEFAULT ((0)) FOR [InitialBudgetRate05]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__UnitT__2F71E941] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__300E0C2D] DEFAULT ((0)) FOR [InitialBudgetRate06]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__AddDa__30660D7A] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__31023066] DEFAULT ((0)) FOR [InitialBudgetRate07]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__315A31B3] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__31F6549F] DEFAULT ((0)) FOR [InitialBudgetRate08]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__324E55EC] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__32EA78D8] DEFAULT ((0)) FOR [InitialBudgetRate09]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__33427A25] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__IsNew__3343457C] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__33DE9D11] DEFAULT ((0)) FOR [InitialBudgetRate10]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__34369E5E] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__34D2C14A] DEFAULT ((0)) FOR [InitialBudgetRate11]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__352AC297] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__35C6E583] DEFAULT ((0)) FOR [InitialBudgetRate12]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__361EE6D0] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__36BB09BC] DEFAULT ((0)) FOR [InitialProjectionRate01]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__37130B09] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__37AF2DF5] DEFAULT ((0)) FOR [InitialProjectionRate02]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__38072F42] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__38A3522E] DEFAULT ((0)) FOR [InitialProjectionRate03]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__38FB537B] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__39977667] DEFAULT ((0)) FOR [InitialProjectionRate04]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__39EF77B4] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3A8B9AA0] DEFAULT ((0)) FOR [InitialProjectionRate05]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3AE39BED] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3B7FBED9] DEFAULT ((0)) FOR [InitialProjectionRate06]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3BD7C026] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3C73E312] DEFAULT ((0)) FOR [InitialProjectionRate07]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3CCBE45F] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3D68074B] DEFAULT ((0)) FOR [InitialProjectionRate08]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3DC00898] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3E5C2B84] DEFAULT ((0)) FOR [InitialProjectionRate09]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3EB42CD1] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3F504FBD] DEFAULT ((0)) FOR [InitialProjectionRate10]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3FA8510A] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__404473F6] DEFAULT ((0)) FOR [InitialProjectionRate11]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__409C7543] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4138982F] DEFAULT ((0)) FOR [InitialProjectionRate12]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__4190997C] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__4284BDB5] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__4378E1EE] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__446D0627] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__45612A60] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__46554E99] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__474972D2] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__483D970B] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4931BB44] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4A25DF7D] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4B1A03B6] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4C0E27EF] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4D024C28] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4DF67061] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4EEA949A] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4FDEB8D3] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__50D2DD0C] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__51C70145] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__52BB257E] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__53AF49B7] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__54A36DF0] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__55979229] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__568BB662] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__577FDA9B] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5873FED4] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5968230D] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5A5C4746] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5B506B7F] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5C448FB8] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5D38B3F1] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5E2CD82A] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__7D2D86A5] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__7E21AADE] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Group__7EA19922] DEFAULT (newid()) FOR [GroupingGUID]; GO
ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__7F15CF17] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO

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

---------------------------------------------
-- fp.FactStatisticsBudget ------------------
---------------------------------------------
CREATE TABLE [fp].[FactStatisticsBudget] (
    [RowID] int NOT NULL,
    [StatisticsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [RateAdjustedValue01] decimal NOT NULL,
    [RateAdjustedValue02] decimal NOT NULL,
    [RateAdjustedValue03] decimal NOT NULL,
    [RateAdjustedValue04] decimal NOT NULL,
    [RateAdjustedValue05] decimal NOT NULL,
    [RateAdjustedValue06] decimal NOT NULL,
    [RateAdjustedValue07] decimal NOT NULL,
    [RateAdjustedValue08] decimal NOT NULL,
    [RateAdjustedValue09] decimal NOT NULL,
    [RateAdjustedValue10] decimal NOT NULL,
    [RateAdjustedValue11] decimal NOT NULL,
    [RateAdjustedValue12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactStatisticsBudget] ON [fp].[FactStatisticsBudget] ([StatisticsID], [BudgetPhaseID]);
CREATE NONCLUSTERED INDEX [IX_FactStatisticsBudget_BudgetPhaseID] ON [fp].[FactStatisticsBudget] ([BudgetPhaseID], [StatisticsID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatisticsBudget] ([StatisticsID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [FK_FactStatisticsBudget_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Stati__279BBD4F] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__LockT__288FE188] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__LockF__298405C1] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Budge__2A7829FA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2B6C4E33] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2C60726C] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2D5496A5] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2E48BADE] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2F3CDF17] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__30310350] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__31252789] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__32194BC2] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__330D6FFB] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__34019434] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__34F5B86D] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__35E9DCA6] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__422CBC68] DEFAULT ((0)) FOR [RateAdjustedValue01]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4320E0A1] DEFAULT ((0)) FOR [RateAdjustedValue02]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__441504DA] DEFAULT ((0)) FOR [RateAdjustedValue03]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__45092913] DEFAULT ((0)) FOR [RateAdjustedValue04]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__45FD4D4C] DEFAULT ((0)) FOR [RateAdjustedValue05]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__46F17185] DEFAULT ((0)) FOR [RateAdjustedValue06]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__47E595BE] DEFAULT ((0)) FOR [RateAdjustedValue07]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__48D9B9F7] DEFAULT ((0)) FOR [RateAdjustedValue08]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__49CDDE30] DEFAULT ((0)) FOR [RateAdjustedValue09]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4AC20269] DEFAULT ((0)) FOR [RateAdjustedValue10]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4BB626A2] DEFAULT ((0)) FOR [RateAdjustedValue11]; GO
ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4CAA4ADB] DEFAULT ((0)) FOR [RateAdjustedValue12]; GO

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

---------------------------------------------
-- fp.FactStatisticsHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[FactStatisticsHistory] (
    [RowID] int NOT NULL,
    [StatisticsID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactStatisticsHistory] ON [fp].[FactStatisticsHistory] ([StatisticsID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatisticsHistory] ([StatisticsID]);
GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [FK_FactStatisticsHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__004CE604] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__01410A3D] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__02352E76] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__032952AF] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__041D76E8] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__05119B21] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0605BF5A] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__06F9E393] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__07EE07CC] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__08E22C05] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__09D6503E] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0ACA7477] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0BBE98B0] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0CB2BCE9] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0DA6E122] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0E9B055B] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0F8F2994] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__10834DCD] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Stati__6E2E35C9] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__6F225A02] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__70167E3B] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__710AA274] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__71FEC6AD] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__72F2EAE6] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__73E70F1F] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__74DB3358] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__75CF5791] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__76C37BCA] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__77B7A003] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__78ABC43C] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__799FE875] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7A940CAE] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7B8830E7] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7C7C5520] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7D707959] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7E649D92] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7F58C1CB] DEFAULT ((0)) FOR [ActualYTDValue06]; GO

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

---------------------------------------------
-- fp.FactStatisticsProjection ------------------
---------------------------------------------
CREATE TABLE [fp].[FactStatisticsProjection] (
    [RowID] int NOT NULL,
    [StatisticsID] int NOT NULL,
    [LockType] tinyint NOT NULL,
    [LockFlag] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustedValue01] decimal NOT NULL,
    [AdjustedValue02] decimal NOT NULL,
    [AdjustedValue03] decimal NOT NULL,
    [AdjustedValue04] decimal NOT NULL,
    [AdjustedValue05] decimal NOT NULL,
    [AdjustedValue06] decimal NOT NULL,
    [AdjustedValue07] decimal NOT NULL,
    [AdjustedValue08] decimal NOT NULL,
    [AdjustedValue09] decimal NOT NULL,
    [AdjustedValue10] decimal NOT NULL,
    [AdjustedValue11] decimal NOT NULL,
    [AdjustedValue12] decimal NOT NULL,
    [AdjustedValueTotal] decimal NOT NULL,
    [RateAdjustedValue01] decimal NOT NULL,
    [RateAdjustedValue02] decimal NOT NULL,
    [RateAdjustedValue03] decimal NOT NULL,
    [RateAdjustedValue04] decimal NOT NULL,
    [RateAdjustedValue05] decimal NOT NULL,
    [RateAdjustedValue06] decimal NOT NULL,
    [RateAdjustedValue07] decimal NOT NULL,
    [RateAdjustedValue08] decimal NOT NULL,
    [RateAdjustedValue09] decimal NOT NULL,
    [RateAdjustedValue10] decimal NOT NULL,
    [RateAdjustedValue11] decimal NOT NULL,
    [RateAdjustedValue12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_FactStatisticsProjection] ON [fp].[FactStatisticsProjection] ([StatisticsID], [BudgetPhaseID]);
CREATE NONCLUSTERED INDEX [IX_FactStatisticsProjection_BudgetPhaseID] ON [fp].[FactStatisticsProjection] ([BudgetPhaseID], [StatisticsID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatisticsProjection] ([StatisticsID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [FK_FactStatisticsProjection_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Stati__452C2036] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__LockT__4620446F] DEFAULT ((0)) FOR [LockType]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__LockF__471468A8] DEFAULT ((0)) FOR [LockFlag]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Budge__48088CE1] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__48FCB11A] DEFAULT ((0)) FOR [AdjustedValue01]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__49F0D553] DEFAULT ((0)) FOR [AdjustedValue02]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4AE4F98C] DEFAULT ((0)) FOR [AdjustedValue03]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4BD91DC5] DEFAULT ((0)) FOR [AdjustedValue04]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4CCD41FE] DEFAULT ((0)) FOR [AdjustedValue05]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__4D9E6F14] DEFAULT ((0)) FOR [RateAdjustedValue01]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4DC16637] DEFAULT ((0)) FOR [AdjustedValue06]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__4E92934D] DEFAULT ((0)) FOR [RateAdjustedValue02]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4EB58A70] DEFAULT ((0)) FOR [AdjustedValue07]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__4F86B786] DEFAULT ((0)) FOR [RateAdjustedValue03]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4FA9AEA9] DEFAULT ((0)) FOR [AdjustedValue08]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__507ADBBF] DEFAULT ((0)) FOR [RateAdjustedValue04]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__509DD2E2] DEFAULT ((0)) FOR [AdjustedValue09]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__516EFFF8] DEFAULT ((0)) FOR [RateAdjustedValue05]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__5191F71B] DEFAULT ((0)) FOR [AdjustedValue10]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__52632431] DEFAULT ((0)) FOR [RateAdjustedValue06]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__52861B54] DEFAULT ((0)) FOR [AdjustedValue11]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__5357486A] DEFAULT ((0)) FOR [RateAdjustedValue07]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__537A3F8D] DEFAULT ((0)) FOR [AdjustedValue12]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__544B6CA3] DEFAULT ((0)) FOR [RateAdjustedValue08]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__553F90DC] DEFAULT ((0)) FOR [RateAdjustedValue09]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__5633B515] DEFAULT ((0)) FOR [RateAdjustedValue10]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__5727D94E] DEFAULT ((0)) FOR [RateAdjustedValue11]; GO
ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__581BFD87] DEFAULT ((0)) FOR [RateAdjustedValue12]; GO

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

---------------------------------------------
-- fp.FixChangeHistoryRequest ------------------
---------------------------------------------
CREATE TABLE [fp].[FixChangeHistoryRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [ChangeHistoryRecordType] tinyint NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [BasisID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF_FixChangeHistoryRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF_FixChangeHistoryRequest_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF_FixChangeHistoryRequest_DateCreatedUTC] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__IsRec__35DE5621] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__37C69E93] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__38BAC2CC] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__39AEE705] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3AA30B3E] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3B972F77] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3C8B53B0] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3D7F77E9] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3E739C22] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3F67C05B] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__405BE494] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__415008CD] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__42442D06] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.FlexConfigMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[FlexConfigMapping] (
    [EntityGroupConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [GLAccountID] int NOT NULL,
    [StatAccountID] int NOT NULL,
    [FlexingTypeID] int NOT NULL,
    [PRJobCodeID] int NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [DependentStatisticAccountID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [SourceDepartmentID] int NOT NULL,
    PRIMARY KEY ([EntityGroupConfigID], [FlexingTypeID], [DepartmentID], [GLAccountID], [StatAccountID], [PRJobCodeID], [ChargeCodeID], [PatientClassID], [DependentStatisticAccountID], [ProviderLineItemID], [SourceDepartmentID])
);
GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__PRJob__03CE9A1B] DEFAULT ((0)) FOR [PRJobCodeID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Patie__0B872C81] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Sourc__172FB1CF] DEFAULT ((0)) FOR [SourceDepartmentID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Depen__29610E9E] DEFAULT ((0)) FOR [DependentStatisticAccountID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Provi__29EB1E83] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Charg__44008FCE] DEFAULT ((0)) FOR [ChargeCodeID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Entit__76749EFD] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Depar__7768C336] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__GLAcc__785CE76F] DEFAULT ((0)) FOR [GLAccountID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__StatA__79510BA8] DEFAULT ((0)) FOR [StatAccountID]; GO
ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Flexi__7A452FE1] DEFAULT ((0)) FOR [FlexingTypeID]; GO

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

---------------------------------------------
-- fp.GeneralLedger ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedger] (
    [GeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [IsNew] bit NOT NULL,
    [FlexingTypeID] smallint NOT NULL,
    [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL,
    [BudgetLockType] tinyint NOT NULL,
    [BudgetLockFlag] tinyint NOT NULL,
    [TargetLockType] tinyint NOT NULL,
    [TargetLockFlag] tinyint NOT NULL,
    [ProjectionLockType] tinyint NOT NULL,
    [ProjectionLockFlag] tinyint NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [BudgetAdjustedTotal] decimal NOT NULL,
    [TargetAdjustedTotal] decimal NOT NULL,
    [ProjectionAdjustedTotal] decimal NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [TargetAdjusted01] decimal NOT NULL,
    [TargetAdjusted02] decimal NOT NULL,
    [TargetAdjusted03] decimal NOT NULL,
    [TargetAdjusted04] decimal NOT NULL,
    [TargetAdjusted05] decimal NOT NULL,
    [TargetAdjusted06] decimal NOT NULL,
    [TargetAdjusted07] decimal NOT NULL,
    [TargetAdjusted08] decimal NOT NULL,
    [TargetAdjusted09] decimal NOT NULL,
    [TargetAdjusted10] decimal NOT NULL,
    [TargetAdjusted11] decimal NOT NULL,
    [TargetAdjusted12] decimal NOT NULL,
    [BudgetAdjusted01] decimal NOT NULL,
    [BudgetAdjusted02] decimal NOT NULL,
    [BudgetAdjusted03] decimal NOT NULL,
    [BudgetAdjusted04] decimal NOT NULL,
    [BudgetAdjusted05] decimal NOT NULL,
    [BudgetAdjusted06] decimal NOT NULL,
    [BudgetAdjusted07] decimal NOT NULL,
    [BudgetAdjusted08] decimal NOT NULL,
    [BudgetAdjusted09] decimal NOT NULL,
    [BudgetAdjusted10] decimal NOT NULL,
    [BudgetAdjusted11] decimal NOT NULL,
    [BudgetAdjusted12] decimal NOT NULL,
    [ProjectionAdjusted01] decimal NOT NULL,
    [ProjectionAdjusted02] decimal NOT NULL,
    [ProjectionAdjusted03] decimal NOT NULL,
    [ProjectionAdjusted04] decimal NOT NULL,
    [ProjectionAdjusted05] decimal NOT NULL,
    [ProjectionAdjusted06] decimal NOT NULL,
    [ProjectionAdjusted07] decimal NOT NULL,
    [ProjectionAdjusted08] decimal NOT NULL,
    [ProjectionAdjusted09] decimal NOT NULL,
    [ProjectionAdjusted10] decimal NOT NULL,
    [ProjectionAdjusted11] decimal NOT NULL,
    [ProjectionAdjusted12] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS01] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS02] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS03] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS04] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS05] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS06] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS07] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS08] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS09] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS10] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS11] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS12] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS01] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS02] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS03] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS04] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS05] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS06] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS07] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS08] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS09] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS10] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS11] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS12] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted01] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted02] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted03] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted04] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted05] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted06] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted07] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted08] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted09] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted10] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted11] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted12] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted01] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted02] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted03] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted04] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted05] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted06] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted07] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted08] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted09] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted10] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted11] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted12] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted01] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted02] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted03] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted04] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted05] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted06] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted07] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted08] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted09] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted10] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted11] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted12] decimal NOT NULL,
    [InitialBudgetPercentOfCharge01] decimal NOT NULL,
    [InitialBudgetPercentOfCharge02] decimal NOT NULL,
    [InitialBudgetPercentOfCharge03] decimal NOT NULL,
    [InitialBudgetPercentOfCharge04] decimal NOT NULL,
    [InitialBudgetPercentOfCharge05] decimal NOT NULL,
    [InitialBudgetPercentOfCharge06] decimal NOT NULL,
    [InitialBudgetPercentOfCharge07] decimal NOT NULL,
    [InitialBudgetPercentOfCharge08] decimal NOT NULL,
    [InitialBudgetPercentOfCharge09] decimal NOT NULL,
    [InitialBudgetPercentOfCharge10] decimal NOT NULL,
    [InitialBudgetPercentOfCharge11] decimal NOT NULL,
    [InitialBudgetPercentOfCharge12] decimal NOT NULL,
    [InitialProjectionPercentOfCharge01] decimal NOT NULL,
    [InitialProjectionPercentOfCharge02] decimal NOT NULL,
    [InitialProjectionPercentOfCharge03] decimal NOT NULL,
    [InitialProjectionPercentOfCharge04] decimal NOT NULL,
    [InitialProjectionPercentOfCharge05] decimal NOT NULL,
    [InitialProjectionPercentOfCharge06] decimal NOT NULL,
    [InitialProjectionPercentOfCharge07] decimal NOT NULL,
    [InitialProjectionPercentOfCharge08] decimal NOT NULL,
    [InitialProjectionPercentOfCharge09] decimal NOT NULL,
    [InitialProjectionPercentOfCharge10] decimal NOT NULL,
    [InitialProjectionPercentOfCharge11] decimal NOT NULL,
    [InitialProjectionPercentOfCharge12] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted01] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted02] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted03] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted04] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted05] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted06] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted07] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted08] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted09] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted10] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted11] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted12] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted01] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted02] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted03] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted04] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted05] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted06] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted07] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted08] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted09] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted10] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted11] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted12] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted01] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted02] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted03] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted04] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted05] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted06] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted07] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted08] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted09] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted10] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted11] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted12] decimal NOT NULL,
    [TargetPercentAdjustmentFactor01] decimal NOT NULL,
    [TargetPercentAdjustmentFactor02] decimal NOT NULL,
    [TargetPercentAdjustmentFactor03] decimal NOT NULL,
    [TargetPercentAdjustmentFactor04] decimal NOT NULL,
    [TargetPercentAdjustmentFactor05] decimal NOT NULL,
    [TargetPercentAdjustmentFactor06] decimal NOT NULL,
    [TargetPercentAdjustmentFactor07] decimal NOT NULL,
    [TargetPercentAdjustmentFactor08] decimal NOT NULL,
    [TargetPercentAdjustmentFactor09] decimal NOT NULL,
    [TargetPercentAdjustmentFactor10] decimal NOT NULL,
    [TargetPercentAdjustmentFactor11] decimal NOT NULL,
    [TargetPercentAdjustmentFactor12] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor01] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor02] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor03] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor04] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor05] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor06] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor07] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor08] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor09] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor10] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor11] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor12] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor01] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor02] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor03] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor04] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor05] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor06] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor07] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor08] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor09] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor10] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor11] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor12] decimal NOT NULL,
    PRIMARY KEY ([GeneralLedgerID])
);

CREATE UNIQUE CLUSTERED INDEX [IX_Unique] ON [fp].[GeneralLedger] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]);
CREATE NONCLUSTERED INDEX [IX_GeneralLedger_Account] ON [fp].[GeneralLedger] ([AccountID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [VariabilityID]);
CREATE NONCLUSTERED INDEX [IX_GeneralLedger_BudgetDollarsConfig] ON [fp].[GeneralLedger] ([BudgetConfigID]) INCLUDE ([GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]);
CREATE NONCLUSTERED INDEX [IX_GeneralLedger_Department] ON [fp].[GeneralLedger] ([DepartmentID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [VariabilityID]);
CREATE NONCLUSTERED INDEX [IX_GeneralLedger_Entity] ON [fp].[GeneralLedger] ([EntityID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]);
CREATE NONCLUSTERED INDEX [IX_GeneralLedger_EntityGroupConfig] ON [fp].[GeneralLedger] ([EntityGroupConfigID], [FlexingTypeID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]);
GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__00222F45] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__0116537E] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__020A77B7] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__02FE9BF0] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__03F2C029] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__04E6E462] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__05DB089B] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__06CF2CD4] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__07C3510D] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__08B77546] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__09AB997F] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0A9FBDB8] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0B93E1F1] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0C88062A] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0D7C2A63] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0E704E9C] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0F6472D5] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1058970E] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__114CBB47] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1240DF80] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__133503B9] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__142927F2] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__151D4C2B] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__16117064] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1705949D] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__17F9B8D6] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__18EDDD0F] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__19E20148] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1AD62581] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1BCA49BA] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1CBE6DF3] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1DB2922C] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1EA6B665] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1F9ADA9E] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__208EFED7] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__21832310] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__22774749] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__236B6B82] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__245F8FBB] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2553B3F4] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2647D82D] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__273BFC66] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2830209F] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__292444D8] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__29594F02] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2A186911] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Entit__2A4D733B] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2B0C8D4A] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Entit__2B419774] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2C00B183] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Depar__2C35BBAD] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2CF4D5BC] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Accou__2D29DFE6] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2DE8F9F5] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Finan__2E1E041F] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2EDD1E2E] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Varia__2F122858] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2FD14267] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__APEMo__30064C91] DEFAULT ((0)) FOR [APEModelSectionID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__30C566A0] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__AddDa__30FA70CA] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__31B98AD9] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__IsNew__31EE9503] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__32ADAF12] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Flexi__32E2B93C] DEFAULT ((0)) FOR [FlexingTypeID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__33A1D34B] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Chang__33D6DD75] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__3495F784] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__34CB01AE] DEFAULT ((0)) FOR [BudgetLockType]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__358A1BBD] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__35BF25E7] DEFAULT ((0)) FOR [BudgetLockFlag]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__367E3FF6] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__36B34A20] DEFAULT ((0)) FOR [TargetLockType]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__3772642F] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__37A76E59] DEFAULT ((0)) FOR [TargetLockFlag]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__38668868] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__389B9292] DEFAULT ((0)) FOR [ProjectionLockType]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__395AACA1] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__398FB6CB] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3A4ED0DA] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3A83DB04] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3B42F513] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3B77FF3D] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3C37194C] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3C6C2376] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3D2B3D85] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3D6047AF] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3E1F61BE] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3E546BE8] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3F1385F7] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3F489021] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__4007AA30] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__403CB45A] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__40FBCE69] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4130D893] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__41EFF2A2] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4224FCCC] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__42E416DB] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__43192105] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__43D83B14] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__440D453E] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__44CC5F4D] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__45016977] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__45C08386] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__45F58DB0] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__46B4A7BF] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__46E9B1E9] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__47A8CBF8] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__47DDD622] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__489CF031] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__48D1FA5B] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4991146A] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__49C61E94] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4A8538A3] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4ABA42CD] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4B795CDC] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4BAE6706] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4C6D8115] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4CA28B3F] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4D61A54E] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4D96AF78] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4E55C987] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4E8AD3B1] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4F49EDC0] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4F7EF7EA] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__503E11F9] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__50731C23] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__51323632] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5167405C] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__52265A6B] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__525B6495] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__531A7EA4] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__534F88CE] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__540EA2DD] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5443AD07] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5502C716] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5537D140] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__55F6EB4F] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__562BF579] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__56EB0F88] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__572019B2] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__57DF33C1] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__58143DEB] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__58D357FA] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__59086224] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__59C77C33] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__59FC865D] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5ABBA06C] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5AF0AA96] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5BAFC4A5] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5BE4CECF] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5CA3E8DE] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5CD8F308] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5D980D17] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5DCD1741] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5E8C3150] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5EC13B7A] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5F805589] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5FB55FB3] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__607479C2] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__60A983EC] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__61689DFB] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__619DA825] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__625CC234] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__6291CC5E] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6350E66D] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__6385F097] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__64450AA6] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__647A14D0] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__65392EDF] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__656E3909] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__662D5318] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__66625D42] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__67217751] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__6756817B] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__68159B8A] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__684AA5B4] DEFAULT ((0)) FOR [TargetAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6909BFC3] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__693EC9ED] DEFAULT ((0)) FOR [TargetAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__69FDE3FC] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6A32EE26] DEFAULT ((0)) FOR [TargetAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6AF20835] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6B27125F] DEFAULT ((0)) FOR [TargetAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6BE62C6E] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6C1B3698] DEFAULT ((0)) FOR [TargetAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6CDA50A7] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6D0F5AD1] DEFAULT ((0)) FOR [TargetAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6DCE74E0] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6E037F0A] DEFAULT ((0)) FOR [TargetAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6EC29919] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6EF7A343] DEFAULT ((0)) FOR [TargetAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6FB6BD52] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6FEBC77C] DEFAULT ((0)) FOR [TargetAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__70AAE18B] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__70DFEBB5] DEFAULT ((0)) FOR [TargetAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__719F05C4] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__71D40FEE] DEFAULT ((0)) FOR [TargetAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__729329FD] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__72C83427] DEFAULT ((0)) FOR [TargetAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__73874E36] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__73BC5860] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__747B726F] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__74B07C99] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__756F96A8] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__75A4A0D2] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7663BAE1] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7698C50B] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7757DF1A] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__778CE944] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__784C0353] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__78810D7D] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7940278C] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__797531B6] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7A344BC5] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7A6955EF] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7B286FFE] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7B5D7A28] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7C1C9437] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7C519E61] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7D45C29A] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7E39E6D3] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7F2E0B0C] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO

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

---------------------------------------------
-- fp.GeneralLedgerAddAccountAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerAddAccountAdjustment] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [Comment] nvarchar(1000) NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE NONCLUSTERED INDEX [NCNU_GeneralLedgerAddAccountAdjustment_RowID] ON [fp].[GeneralLedgerAddAccountAdjustment] ([RowID]);
GO
ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__7095079B] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Depar__71892BD4] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Accou__727D500D] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Comme__73717446] DEFAULT ('') FOR [Comment]; GO

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

---------------------------------------------
-- fp.GeneralLedgerAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [AdjustmentID] int NOT NULL,
    [IsErrored] bit NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [FK__GeneralLe__Budge__14EBD720] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__15DFFB59] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__16D41F92] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__17C843CB] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__18BC6804] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Group__19B08C3D] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__1AA4B076] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Comme__1B98D4AF] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Autho__1C8CF8E8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Autho__1D811D21] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__UnitT__2339F677] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__IsErr__4CE1B70A] DEFAULT ((0)) FOR [IsErrored]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__LastM__644BFEEB] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__DateC__65402324] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Dimen__65CA3309] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__IsRec__661E6D6D] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Group__6F503E1D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerAdjustmentImport ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerAdjustmentImport] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [Version] timestamp NOT NULL,
    [VariabilityID] int NOT NULL,
    [EntityID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [AdjustmentID] int NOT NULL,
    [OriginalUnitTypeID] tinyint NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[GeneralLedgerAdjustmentImport] ([AdjustmentID]);
GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Varia__05B61736] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Adjus__24A67B22] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Entit__3288BDAD] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Adjus__368E58BB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__AccountID__2D57C830] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__FinancialReportingID__2D57C830] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF_INTGeneralLedgerAdjImport_VALUE] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__IsRec__6806B5DF] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentImport_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerAdjustment_backup ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerAdjustment_backup] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AdjustmentID] int NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [FK__GeneralLe__Budge__399E38E2] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentBackup_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__2D3861FD] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__2E2C8636] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Value__2F20AA6F] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__3014CEA8] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Group__3108F2E1] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__31FD171A] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Comme__32F13B53] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Autho__33E55F8C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Autho__34D983C5] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__LastM__35CDA7FE] DEFAULT (getdate()) FOR [LastModifiedDate]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__DateC__36C1CC37] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__UnitT__37B5F070] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Group__38AA14A9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__67809EAD] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerBasisFlexRate ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerBasisFlexRate] (
    [RowID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [FlexRate01] decimal NOT NULL,
    [FlexRate02] decimal NOT NULL,
    [FlexRate03] decimal NOT NULL,
    [FlexRate04] decimal NOT NULL,
    [FlexRate05] decimal NOT NULL,
    [FlexRate06] decimal NOT NULL,
    [FlexRate07] decimal NOT NULL,
    [FlexRate08] decimal NOT NULL,
    [FlexRate09] decimal NOT NULL,
    [FlexRate10] decimal NOT NULL,
    [FlexRate11] decimal NOT NULL,
    [FlexRate12] decimal NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [AdjustmentID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[GeneralLedgerBasisFlexRate] ([BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [TimeClassID], [AdjustmentID]);
GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Entit__40A466A9] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Depar__41988AE2] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Accou__428CAF1B] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Finan__4380D354] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Fisca__4474F78D] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__TimeC__45691BC6] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__465D3FFF] DEFAULT ((0.0)) FOR [FlexRate01]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__47516438] DEFAULT ((0.0)) FOR [FlexRate02]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__48458871] DEFAULT ((0.0)) FOR [FlexRate03]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4939ACAA] DEFAULT ((0.0)) FOR [FlexRate04]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4A2DD0E3] DEFAULT ((0.0)) FOR [FlexRate05]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4B21F51C] DEFAULT ((0.0)) FOR [FlexRate06]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4C161955] DEFAULT ((0.0)) FOR [FlexRate07]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4D0A3D8E] DEFAULT ((0.0)) FOR [FlexRate08]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4DFE61C7] DEFAULT ((0.0)) FOR [FlexRate09]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4EF28600] DEFAULT ((0.0)) FOR [FlexRate10]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4FE6AA39] DEFAULT ((0.0)) FOR [FlexRate11]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__50DACE72] DEFAULT ((0.0)) FOR [FlexRate12]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Budge__51CEF2AB] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Adjus__52C316E4] DEFAULT ((0)) FOR [AdjustmentID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerChangeHistory] (
    [RowID] bigint NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_GeneralLedgerChangeHistory] ON [fp].[GeneralLedgerChangeHistory] ([GeneralLedgerID]);
CREATE NONCLUSTERED INDEX [IX_GeneralLedgerChangeHistory_AdjustmentGuid] ON [fp].[GeneralLedgerChangeHistory] ([AdjustmentGUID]) INCLUDE ([GeneralLedgerID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [FK_GeneralLedgerChangeHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[GeneralLedger] ([GeneralLedgerID]); GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Gener__06BA1E3B] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Adjus__07AE4274] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Group__08A266AD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Adjus__09968AE6] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Fisca__0A8AAF1F] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__UnitT__0B7ED358] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__TimeC__0C72F791] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__0D671BCA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__0E5B4003] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__0F4F643C] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__10438875] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__DateC__1137ACAE] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO

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

---------------------------------------------
-- fp.GeneralLedgerChangeHistory_OLD ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerChangeHistory_OLD] (
    [RowID] bigint NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__DateC__06B62588] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Budge__61EEB52D] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Gener__766E760F] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Adjus__77629A48] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Group__7856BE81] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Adjus__794AE2BA] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Fisca__7B332B2C] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__UnitT__7C274F65] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__TimeC__7D1B739E] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Budge__7E0F97D7] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__OldVa__7F03BC10] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__NewVa__7FF7E049] DEFAULT ((0)) FOR [NewValue]; GO

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

---------------------------------------------
-- fp.GeneralLedgerFixedDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerFixedDetail] (
    [CommentGUID] uniqueidentifier NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [AccountID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [DollarsValue] decimal NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [SortOrder] int NOT NULL,
    [SpreadID] int NOT NULL,
    [IsMarkedForDeletion] bit NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [CategoryID] int NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [LastModifiedAuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedAuthorGUID] uniqueidentifier NOT NULL,
    [IsSetValue] bit NOT NULL,
    PRIMARY KEY ([CommentGUID])
);
GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0B7BA5FC] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0C6FCA35] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0D63EE6E] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0E5812A7] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0F4C36E0] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__10405B19] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__11347F52] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__1228A38B] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__131CC7C4] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__1410EBFD] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__15051036] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__15F9346F] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Total__16ED58A8] DEFAULT ((0)) FOR [TotalImportedValue]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_CategoryID] DEFAULT ((0)) FOR [CategoryID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_LastModifiedDateUtc] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_LastModifiedAuthorFullName] DEFAULT ('') FOR [LastModifiedAuthorFullName]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_LastModifiedAuthorGUID] DEFAULT (newid()) FOR [LastModifiedAuthorGUID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Adjus__4182B0F2] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__4276D52B] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__436AF964] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Finan__445F1D9D] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__455341D6] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__4647660F] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Dolla__473B8A48] DEFAULT ((0)) FOR [DollarsValue]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Comme__482FAE81] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__SortO__4923D2BA] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__4A17F6F3] DEFAULT ((0)) FOR [SpreadID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__IsDel__4B0C1B2C] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Autho__4CF4639E] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__DateC__4DE887D7] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerI_Auth] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerI_Comm] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__IsSet__6C87ACF1] DEFAULT ((0)) FOR [IsSetValue]; GO

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

---------------------------------------------
-- fp.GeneralLedgerHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerHistory] (
    [RowID] int NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_GeneralLedgerHistory] ON [fp].[GeneralLedgerHistory] ([GeneralLedgerID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[GeneralLedgerHistory] ([GeneralLedgerID]);
GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [FK_GeneralLedgerHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[GeneralLedger] ([GeneralLedgerID]); GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2612CE03] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2706F23C] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__27FB1675] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__28EF3AAE] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__29E35EE7] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2AD78320] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2BCBA759] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2CBFCB92] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2DB3EFCB] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2EA81404] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2F9C383D] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__30905C76] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__318480AF] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3278A4E8] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__336CC921] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3460ED5A] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__35551193] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__364935CC] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__373D5A05] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__38317E3E] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3925A277] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3A19C6B0] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3B0DEAE9] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3C020F22] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3CF6335B] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3DEA5794] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3EDE7BCD] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3FD2A006] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__40C6C43F] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__41BAE878] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__42AF0CB1] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__43A330EA] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__44975523] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__458B795C] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__467F9D95] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__4773C1CE] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.GeneralLedgerInitialPlanConfigDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [APEModelSectionID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [VersionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [FK__GeneralLe__Budge__34EBC896] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [FK__GeneralLe__Versi__6F6D6FE6] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__2A6E3A23] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__2B625E5C] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Entit__2C568295] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__2D4AA6CE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__2E3ECB07] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Finan__2F32EF40] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Varia__30271379] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__APEMo__311B37B2] DEFAULT ((0)) FOR [APEModelSectionID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__320F5BEB] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Proje__33038024] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Trail__33F7A45D] DEFAULT ((0)) FOR [TrailingMonths]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Versi__6E794BAD] DEFAULT ((0)) FOR [VersionID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerInitialPlanConfigDetailHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [APEModelSectionID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [VersionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__GeneralLe__Budge__7DBB8F3D] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__GeneralLe__Versi__7EAFB376] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__7249DC91] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__733E00CA] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Entit__74322503] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Depar__7526493C] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Accou__761A6D75] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Finan__770E91AE] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Varia__7802B5E7] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__APEMo__78F6DA20] DEFAULT ((0)) FOR [APEModelSectionID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__TimeC__79EAFE59] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Proje__7ADF2292] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Trail__7BD346CB] DEFAULT ((0)) FOR [TrailingMonths]; GO
ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Versi__7CC76B04] DEFAULT ((0)) FOR [VersionID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerItemizationDetailLink ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerItemizationDetailLink] (
    [OriginalAdjustmentCommentGUID] uniqueidentifier NOT NULL,
    [InverseAdjustmentCommentGUID] uniqueidentifier NOT NULL
);
GO
ALTER TABLE [fp].[GeneralLedgerItemizationDetailLink] ADD CONSTRAINT [FK_InverseAdj_CommentGUID] FOREIGN KEY ([InverseAdjustmentCommentGUID]) REFERENCES [fp].[GeneralLedgerFixedDetail] ([CommentGUID]); GO
ALTER TABLE [fp].[GeneralLedgerItemizationDetailLink] ADD CONSTRAINT [FK_OriginalAdj_CommentGUID] FOREIGN KEY ([OriginalAdjustmentCommentGUID]) REFERENCES [fp].[GeneralLedgerFixedDetail] ([CommentGUID]); GO

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

---------------------------------------------
-- fp.GeneralLedgerItemizationReportData ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerItemizationReportData] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [AccountID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [ItemizationDataTypeID] int 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,
    [TotalValue] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [CORE_Unique_GLItemizationReportData] ON [fp].[GeneralLedgerItemizationReportData] ([BudgetConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [ItemizationDataTypeID], [TimeClassID]);
GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Budge__557F87FE] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Entit__5673AC37] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Depar__5767D070] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Finan__585BF4A9] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Accou__595018E2] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__TimeC__5A443D1B] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Itemi__5B386154] DEFAULT ((0)) FOR [ItemizationDataTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5C2C858D] DEFAULT ((0)) FOR [Month01]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5D20A9C6] DEFAULT ((0)) FOR [Month02]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5E14CDFF] DEFAULT ((0)) FOR [Month03]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5F08F238] DEFAULT ((0)) FOR [Month04]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5FFD1671] DEFAULT ((0)) FOR [Month05]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__60F13AAA] DEFAULT ((0)) FOR [Month06]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__61E55EE3] DEFAULT ((0)) FOR [Month07]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__62D9831C] DEFAULT ((0)) FOR [Month08]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__63CDA755] DEFAULT ((0)) FOR [Month09]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__64C1CB8E] DEFAULT ((0)) FOR [Month10]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__65B5EFC7] DEFAULT ((0)) FOR [Month11]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__66AA1400] DEFAULT ((0)) FOR [Month12]; GO
ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Total__679E3839] DEFAULT ((0)) FOR [TotalValue]; GO

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

---------------------------------------------
-- fp.GeneralLedgerManagerAdjustmentComment ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerManagerAdjustmentComment] (
    [CommentGUID] uniqueidentifier NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [InitialValue] decimal NOT NULL,
    [DeltaValue] decimal NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [IsRollupLevel] int NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [DateModifiedUtc] datetime NOT NULL,
    PRIMARY KEY ([CommentGUID])
);
GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__IsRol__2F8D5292] DEFAULT ((0)) FOR [IsRollupLevel]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [Default_GLManagerAdjComment_FinancialReportingID] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__DateC__3388CBFF] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__DateM__347CF038] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Comme__57D27E51] DEFAULT (newid()) FOR [CommentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Depar__5AAEEAFC] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Accou__5BA30F35] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Fisca__5D8B57A7] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Comme__5E7F7BE0] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Initi__5F73A019] DEFAULT ((0)) FOR [InitialValue]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Updat__6067C452] DEFAULT ((0)) FOR [DeltaValue]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Autho__62500CC4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Autho__634430FD] DEFAULT ('') FOR [AuthorFullName]; GO

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

---------------------------------------------
-- fp.GeneralLedgerManagerAdjustmentData ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerManagerAdjustmentData] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [EntityID] int NOT NULL,
    [Value] decimal NULL,
    [TimeClassID] tinyint NOT NULL
);

CREATE NONCLUSTERED INDEX [NCNU_AdjustmentGUID] ON [fp].[GeneralLedgerManagerAdjustmentData] ([AdjustmentGUID]) INCLUDE ([DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], [EntityID], [Value], [TimeClassID]);
GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [Default_GLManagerAdj_TC] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Adjus__394DF731] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Depar__3A421B6A] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Accou__3B363FA3] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Finan__3C2A63DC] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Fisca__3D1E8815] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__UnitT__3E12AC4E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Fisca__3F06D087] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Entit__40EF18F9] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Value__41E33D32] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.GeneralLedgerMyBudgetAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerMyBudgetAdjustment] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [AccountID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [CLU_GLAdjustmentItemization] ON [fp].[GeneralLedgerMyBudgetAdjustment] ([BudgetConfigID], [DepartmentID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[GeneralLedgerMyBudgetAdjustment] ([BudgetConfigID], [AdjustmentID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [VariabilityID], [UnitTypeID], [TimeClassID]);
GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__07C023B1] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Budge__08B447EA] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Entit__09A86C23] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Depar__0A9C905C] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Finan__0B90B495] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Accou__0C84D8CE] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Varia__0D78FD07] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__UnitT__0E6D2140] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__TimeC__0F614579] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__105569B2] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__11498DEB] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__123DB224] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__1331D65D] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__1425FA96] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__151A1ECF] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__160E4308] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__17026741] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__17F68B7A] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__18EAAFB3] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__19DED3EC] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__1AD2F825] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.GeneralLedgerReimbursementExcludedDepartments ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [EntityID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [FK__GeneralLe__Budge__56B3D523] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [DF__GeneralLe__Budge__53D76878] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [DF__GeneralLe__Depar__54CB8CB1] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [DF__GeneralLe__Entit__55BFB0EA] DEFAULT ((0)) FOR [EntityID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerSnapshot ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerSnapshot] (
    [GeneralLedgerID] int NOT NULL,
    [SnapshotID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [IsNew] bit NOT NULL,
    [FlexingTypeID] smallint NOT NULL,
    [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL,
    [BudgetLockType] tinyint NOT NULL,
    [BudgetLockFlag] tinyint NOT NULL,
    [TargetLockType] tinyint NOT NULL,
    [TargetLockFlag] tinyint NOT NULL,
    [ProjectionLockType] tinyint NOT NULL,
    [ProjectionLockFlag] tinyint NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [TargetAdjusted01] decimal NOT NULL,
    [TargetAdjusted02] decimal NOT NULL,
    [TargetAdjusted03] decimal NOT NULL,
    [TargetAdjusted04] decimal NOT NULL,
    [TargetAdjusted05] decimal NOT NULL,
    [TargetAdjusted06] decimal NOT NULL,
    [TargetAdjusted07] decimal NOT NULL,
    [TargetAdjusted08] decimal NOT NULL,
    [TargetAdjusted09] decimal NOT NULL,
    [TargetAdjusted10] decimal NOT NULL,
    [TargetAdjusted11] decimal NOT NULL,
    [TargetAdjusted12] decimal NOT NULL,
    [BudgetAdjusted01] decimal NOT NULL,
    [BudgetAdjusted02] decimal NOT NULL,
    [BudgetAdjusted03] decimal NOT NULL,
    [BudgetAdjusted04] decimal NOT NULL,
    [BudgetAdjusted05] decimal NOT NULL,
    [BudgetAdjusted06] decimal NOT NULL,
    [BudgetAdjusted07] decimal NOT NULL,
    [BudgetAdjusted08] decimal NOT NULL,
    [BudgetAdjusted09] decimal NOT NULL,
    [BudgetAdjusted10] decimal NOT NULL,
    [BudgetAdjusted11] decimal NOT NULL,
    [BudgetAdjusted12] decimal NOT NULL,
    [ProjectionAdjusted01] decimal NOT NULL,
    [ProjectionAdjusted02] decimal NOT NULL,
    [ProjectionAdjusted03] decimal NOT NULL,
    [ProjectionAdjusted04] decimal NOT NULL,
    [ProjectionAdjusted05] decimal NOT NULL,
    [ProjectionAdjusted06] decimal NOT NULL,
    [ProjectionAdjusted07] decimal NOT NULL,
    [ProjectionAdjusted08] decimal NOT NULL,
    [ProjectionAdjusted09] decimal NOT NULL,
    [ProjectionAdjusted10] decimal NOT NULL,
    [ProjectionAdjusted11] decimal NOT NULL,
    [ProjectionAdjusted12] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS01] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS02] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS03] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS04] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS05] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS06] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS07] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS08] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS09] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS10] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS11] decimal NOT NULL,
    [InitialBudgetDollarsPerUOS12] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS01] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS02] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS03] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS04] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS05] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS06] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS07] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS08] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS09] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS10] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS11] decimal NOT NULL,
    [InitialProjectionDollarsPerUOS12] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted01] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted02] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted03] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted04] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted05] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted06] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted07] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted08] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted09] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted10] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted11] decimal NOT NULL,
    [TargetDollarsPerUOSAdjusted12] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted01] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted02] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted03] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted04] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted05] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted06] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted07] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted08] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted09] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted10] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted11] decimal NOT NULL,
    [BudgetDollarsPerUOSAdjusted12] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted01] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted02] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted03] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted04] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted05] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted06] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted07] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted08] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted09] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted10] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted11] decimal NOT NULL,
    [ProjectionDollarsPerUOSAdjusted12] decimal NOT NULL,
    [InitialBudgetPercentOfCharge01] decimal NOT NULL,
    [InitialBudgetPercentOfCharge02] decimal NOT NULL,
    [InitialBudgetPercentOfCharge03] decimal NOT NULL,
    [InitialBudgetPercentOfCharge04] decimal NOT NULL,
    [InitialBudgetPercentOfCharge05] decimal NOT NULL,
    [InitialBudgetPercentOfCharge06] decimal NOT NULL,
    [InitialBudgetPercentOfCharge07] decimal NOT NULL,
    [InitialBudgetPercentOfCharge08] decimal NOT NULL,
    [InitialBudgetPercentOfCharge09] decimal NOT NULL,
    [InitialBudgetPercentOfCharge10] decimal NOT NULL,
    [InitialBudgetPercentOfCharge11] decimal NOT NULL,
    [InitialBudgetPercentOfCharge12] decimal NOT NULL,
    [InitialProjectionPercentOfCharge01] decimal NOT NULL,
    [InitialProjectionPercentOfCharge02] decimal NOT NULL,
    [InitialProjectionPercentOfCharge03] decimal NOT NULL,
    [InitialProjectionPercentOfCharge04] decimal NOT NULL,
    [InitialProjectionPercentOfCharge05] decimal NOT NULL,
    [InitialProjectionPercentOfCharge06] decimal NOT NULL,
    [InitialProjectionPercentOfCharge07] decimal NOT NULL,
    [InitialProjectionPercentOfCharge08] decimal NOT NULL,
    [InitialProjectionPercentOfCharge09] decimal NOT NULL,
    [InitialProjectionPercentOfCharge10] decimal NOT NULL,
    [InitialProjectionPercentOfCharge11] decimal NOT NULL,
    [InitialProjectionPercentOfCharge12] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted01] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted02] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted03] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted04] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted05] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted06] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted07] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted08] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted09] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted10] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted11] decimal NOT NULL,
    [TargetPercentOfChargeAdjusted12] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted01] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted02] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted03] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted04] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted05] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted06] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted07] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted08] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted09] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted10] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted11] decimal NOT NULL,
    [BudgetPercentOfChargeAdjusted12] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted01] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted02] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted03] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted04] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted05] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted06] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted07] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted08] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted09] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted10] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted11] decimal NOT NULL,
    [ProjectionPercentOfChargeAdjusted12] decimal NOT NULL,
    [TargetPercentAdjustmentFactor01] decimal NOT NULL,
    [TargetPercentAdjustmentFactor02] decimal NOT NULL,
    [TargetPercentAdjustmentFactor03] decimal NOT NULL,
    [TargetPercentAdjustmentFactor04] decimal NOT NULL,
    [TargetPercentAdjustmentFactor05] decimal NOT NULL,
    [TargetPercentAdjustmentFactor06] decimal NOT NULL,
    [TargetPercentAdjustmentFactor07] decimal NOT NULL,
    [TargetPercentAdjustmentFactor08] decimal NOT NULL,
    [TargetPercentAdjustmentFactor09] decimal NOT NULL,
    [TargetPercentAdjustmentFactor10] decimal NOT NULL,
    [TargetPercentAdjustmentFactor11] decimal NOT NULL,
    [TargetPercentAdjustmentFactor12] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor01] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor02] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor03] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor04] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor05] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor06] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor07] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor08] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor09] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor10] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor11] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor12] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor01] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor02] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor03] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor04] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor05] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor06] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor07] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor08] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor09] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor10] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor11] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor12] decimal NOT NULL,
    PRIMARY KEY ([GeneralLedgerID], [BudgetConfigID], [SnapshotID])
);
GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0097625B] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__00CC6C85] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__018B8694] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__01C090BE] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__027FAACD] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__02B4B4F7] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0373CF06] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__03A8D930] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0467F33F] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__049CFD69] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__055C1778] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__059121A2] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__06503BB1] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__068545DB] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__07445FEA] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__07796A14] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__08388423] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__086D8E4D] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__092CA85C] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__0961B286] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0A20CC95] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0A55D6BF] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0B14F0CE] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0B49FAF8] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0C091507] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0C3E1F31] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0CFD3940] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0D32436A] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0DF15D79] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0E2667A3] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0EE581B2] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0F1A8BDC] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0FD9A5EB] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__100EB015] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__10CDCA24] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__1102D44E] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__11C1EE5D] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__11F6F887] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__12B61296] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__12EB1CC0] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__13AA36CF] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__13DF40F9] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__149E5B08] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__14D36532] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__15927F41] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__15C7896B] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1686A37A] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__16BBADA4] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__177AC7B3] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__17AFD1DD] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__186EEBEC] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__18A3F616] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__19631025] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__19981A4F] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1A57345E] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1A8C3E88] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1B4B5897] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1B8062C1] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1C3F7CD0] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1C7486FA] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1D33A109] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1D68AB33] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1E27C542] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1E5CCF6C] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__1F1BE97B] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1F50F3A5] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__20100DB4] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__204517DE] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__210431ED] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__21393C17] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__21F85626] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__222D6050] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__22EC7A5F] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__23218489] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__23E09E98] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2415A8C2] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__24D4C2D1] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2509CCFB] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__25C8E70A] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__25FDF134] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__26BD0B43] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__26F2156D] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__27B12F7C] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__27E639A6] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__28A553B5] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__28DA5DDF] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__299977EE] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__29CE8218] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2AC2A651] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2BB6CA8A] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2CAAEEC3] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2D9F12FC] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2E933735] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2F875B6E] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__307B7FA7] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__316FA3E0] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__3263C819] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Gener__3298D243] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__3357EC52] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Snaps__338CF67C] DEFAULT ((0)) FOR [SnapshotID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__344C108B] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__34811AB5] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__354034C4] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Entit__35753EEE] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__363458FD] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Entit__36696327] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__37287D36] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Depar__375D8760] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__381CA16F] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Accou__3851AB99] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3910C5A8] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Finan__3945CFD2] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3A04E9E1] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Varia__3A39F40B] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3AF90E1A] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__APEMo__3B2E1844] DEFAULT ((0)) FOR [APEModelSectionID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3BED3253] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__AddDa__3C223C7D] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3CE1568C] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__IsNew__3D1660B6] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3DD57AC5] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Flexi__3E0A84EF] DEFAULT ((0)) FOR [FlexingTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3EC99EFE] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Chang__3EFEA928] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3FBDC337] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3FF2CD61] DEFAULT ((0)) FOR [BudgetLockType]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__40B1E770] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__40E6F19A] DEFAULT ((0)) FOR [BudgetLockFlag]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__41A60BA9] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__41DB15D3] DEFAULT ((0)) FOR [TargetLockType]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__429A2FE2] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__42CF3A0C] DEFAULT ((0)) FOR [TargetLockFlag]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__438E541B] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__43C35E45] DEFAULT ((0)) FOR [ProjectionLockType]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__44827854] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__44B7827E] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__45769C8D] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__45ABA6B7] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__466AC0C6] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__469FCAF0] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__475EE4FF] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4793EF29] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__48530938] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__48881362] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__49472D71] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__497C379B] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4A3B51AA] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4A705BD4] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4B2F75E3] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4B64800D] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4C239A1C] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4C58A446] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4D17BE55] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4D4CC87F] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4E0BE28E] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4E40ECB8] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__4F0006C7] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4F3510F1] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__4FF42B00] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5029352A] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__50E84F39] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__511D5963] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__51DC7372] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__52117D9C] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__52D097AB] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5305A1D5] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__53C4BBE4] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__53F9C60E] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__54B8E01D] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__54EDEA47] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__55AD0456] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__55E20E80] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__56A1288F] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__56D632B9] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__57954CC8] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__57CA56F2] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__58897101] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__58BE7B2B] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__597D953A] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__59B29F64] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5A71B973] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5AA6C39D] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5B65DDAC] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5B9AE7D6] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5C5A01E5] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5C8F0C0F] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5D4E261E] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5D833048] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5E424A57] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5E775481] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5F366E90] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5F6B78BA] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__602A92C9] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__605F9CF3] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__611EB702] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6153C12C] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6212DB3B] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6247E565] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6306FF74] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__633C099E] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__63FB23AD] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__64302DD7] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__64EF47E6] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__65245210] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__65E36C1F] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__66187649] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__66D79058] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__670C9A82] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__67CBB491] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6800BEBB] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__68BFD8CA] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__68F4E2F4] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__69B3FD03] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__69E9072D] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6AA8213C] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6ADD2B66] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6B9C4575] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6BD14F9F] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6C9069AE] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6CC573D8] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6D848DE7] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6DB99811] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6E78B220] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6EADBC4A] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6F6CD659] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6FA1E083] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7060FA92] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__709604BC] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__71551ECB] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__718A28F5] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__72494304] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__727E4D2E] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__733D673D] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__73727167] DEFAULT ((0)) FOR [TargetAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__74318B76] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__746695A0] DEFAULT ((0)) FOR [TargetAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7525AFAF] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__755AB9D9] DEFAULT ((0)) FOR [TargetAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7619D3E8] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__764EDE12] DEFAULT ((0)) FOR [TargetAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__770DF821] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7743024B] DEFAULT ((0)) FOR [TargetAdjusted05]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__78021C5A] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__78372684] DEFAULT ((0)) FOR [TargetAdjusted06]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__78F64093] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__792B4ABD] DEFAULT ((0)) FOR [TargetAdjusted07]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__79EA64CC] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7A1F6EF6] DEFAULT ((0)) FOR [TargetAdjusted08]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7ADE8905] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7B13932F] DEFAULT ((0)) FOR [TargetAdjusted09]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7BD2AD3E] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7C07B768] DEFAULT ((0)) FOR [TargetAdjusted10]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7CC6D177] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7CFBDBA1] DEFAULT ((0)) FOR [TargetAdjusted11]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7DBAF5B0] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted02]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7DEFFFDA] DEFAULT ((0)) FOR [TargetAdjusted12]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7EAF19E9] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted03]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7EE42413] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7FA33E22] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted04]; GO
ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7FD8484C] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO

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

---------------------------------------------
-- fp.GeneralLedgerSpreadUnlockData ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerSpreadUnlockData] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [Version] timestamp NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__0066B8A7] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__015ADCE0] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__IsRec__01C687E2] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__024F0119] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__03432552] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__0437498B] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__052B6DC4] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__061F91FD] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__0713B636] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Budge__76DD4E6D] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Adjus__77D172A6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Entit__78C596DF] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Depar__79B9BB18] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Accou__7AADDF51] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Finan__7BA2038A] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7C9627C3] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7D8A4BFC] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7E7E7035] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7F72946E] DEFAULT ((0)) FOR [Value04]; GO

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

---------------------------------------------
-- fp.GeneralLedgerSpreads ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerSpreads] (
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [IsInactive] bit NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [GlobalSpreadID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [DepartmentID], [AccountID])
);
GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [FK_FpGeneralLedgerSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Budge__313EFA2C] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Depar__32331E65] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Accou__3327429E] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__IsIna__341B66D7] DEFAULT ((0)) FOR [IsInactive]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__350F8B10] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3603AF49] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__36F7D382] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__37EBF7BB] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__38E01BF4] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__39D4402D] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3AC86466] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3BBC889F] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3CB0ACD8] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3DA4D111] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3E98F54A] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3F8D1983] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Total__40813DBC] DEFAULT ((0)) FOR [TotalImportedValue]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [df_GeneralLedgerSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Globa__6B2C6FF6] DEFAULT ((1)) FOR [GlobalSpreadID]; GO

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

---------------------------------------------
-- fp.GeneralLedgerSpreadsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerSpreadsChangeHistory] (
    [RowID] bigint NOT NULL,
    [GeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [OldValue01] decimal NOT NULL,
    [OldValue02] decimal NOT NULL,
    [OldValue03] decimal NOT NULL,
    [OldValue04] decimal NOT NULL,
    [OldValue05] decimal NOT NULL,
    [OldValue06] decimal NOT NULL,
    [OldValue07] decimal NOT NULL,
    [OldValue08] decimal NOT NULL,
    [OldValue09] decimal NOT NULL,
    [OldValue10] decimal NOT NULL,
    [OldValue11] decimal NOT NULL,
    [OldValue12] decimal NOT NULL,
    [NewValue01] decimal NOT NULL,
    [NewValue02] decimal NOT NULL,
    [NewValue03] decimal NOT NULL,
    [NewValue04] decimal NOT NULL,
    [NewValue05] decimal NOT NULL,
    [NewValue06] decimal NOT NULL,
    [NewValue07] decimal NOT NULL,
    [NewValue08] decimal NOT NULL,
    [NewValue09] decimal NOT NULL,
    [NewValue10] decimal NOT NULL,
    [NewValue11] decimal NOT NULL,
    [NewValue12] decimal NOT NULL
);

CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[GeneralLedgerSpreadsChangeHistory] ([BudgetConfigID], [GeneralLedgerID], [RowID]);
GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Gener__4F409776] DEFAULT ((0)) FOR [GeneralLedgerID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__5034BBAF] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__DateC__5128DFE8] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__521D0421] DEFAULT ((0)) FOR [OldValue01]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5311285A] DEFAULT ((0)) FOR [OldValue02]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__54054C93] DEFAULT ((0)) FOR [OldValue03]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__54F970CC] DEFAULT ((0)) FOR [OldValue04]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__55ED9505] DEFAULT ((0)) FOR [OldValue05]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__56E1B93E] DEFAULT ((0)) FOR [OldValue06]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__57D5DD77] DEFAULT ((0)) FOR [OldValue07]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__58CA01B0] DEFAULT ((0)) FOR [OldValue08]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__59BE25E9] DEFAULT ((0)) FOR [OldValue09]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5AB24A22] DEFAULT ((0)) FOR [OldValue10]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5BA66E5B] DEFAULT ((0)) FOR [OldValue11]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5C9A9294] DEFAULT ((0)) FOR [OldValue12]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__5D8EB6CD] DEFAULT ((0)) FOR [NewValue01]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__5E82DB06] DEFAULT ((0)) FOR [NewValue02]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__5F76FF3F] DEFAULT ((0)) FOR [NewValue03]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__606B2378] DEFAULT ((0)) FOR [NewValue04]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__615F47B1] DEFAULT ((0)) FOR [NewValue05]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__62536BEA] DEFAULT ((0)) FOR [NewValue06]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__63479023] DEFAULT ((0)) FOR [NewValue07]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__643BB45C] DEFAULT ((0)) FOR [NewValue08]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__652FD895] DEFAULT ((0)) FOR [NewValue09]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__6623FCCE] DEFAULT ((0)) FOR [NewValue10]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__67182107] DEFAULT ((0)) FOR [NewValue11]; GO
ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__680C4540] DEFAULT ((0)) FOR [NewValue12]; GO

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

---------------------------------------------
-- fp.GeneralLedgerSubAccountItemizedAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] (
    [SubAccountItemizedID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [Itemized] bit NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([SubAccountItemizedID])
);
GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__1C48A150] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Budge__1D3CC589] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Depar__1E30E9C2] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Accou__1F250DFB] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__UnitT__20193234] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__TimeC__210D566D] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Budge__22017AA6] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Itemi__22F59EDF] DEFAULT ((0)) FOR [Itemized]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__23E9C318] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__24DDE751] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__25D20B8A] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__26C62FC3] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__27BA53FC] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__28AE7835] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__29A29C6E] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2A96C0A7] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2B8AE4E0] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2C7F0919] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2D732D52] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2E67518B] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.GeneralLedgerSubAccountItemizedDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [AccountID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [Description] nvarchar(1000) NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [CategoryID] int NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [CreatedAuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedAuthorFullName] nvarchar(260) NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Categ__045C0926] DEFAULT ((0)) FOR [CategoryID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__2409BEA9] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__UnitT__24FDE2E2] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__25F2071B] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__26E62B54] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__27DA4F8D] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__28CE73C6] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Descr__2AB6BC38] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2BAAE071] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2C9F04AA] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2D9328E3] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2E874D1C] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2F7B7155] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__306F958E] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__3163B9C7] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__3257DE00] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__334C0239] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__34402672] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__35344AAB] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__36286EE4] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_LastModifiedDateUtc] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_DateCreatedUtc] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_CreatedAuthorFullName] DEFAULT ('') FOR [CreatedAuthorFullName]; GO
ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_LastModifiedAuthorFullName] DEFAULT ('') FOR [LastModifiedAuthorFullName]; GO

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

---------------------------------------------
-- fp.GeneralLedgerVariableDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[GeneralLedgerVariableDetail] (
    [CommentGUID] uniqueidentifier NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [AccountID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [DollarsValue] decimal NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    PRIMARY KEY ([CommentGUID])
);
GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Comme__50C4F482] DEFAULT (newid()) FOR [CommentGUID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Adjus__51B918BB] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__52AD3CF4] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__53A1612D] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Finan__54958566] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__5589A99F] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__567DCDD8] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Dolla__5771F211] DEFAULT ((0)) FOR [DollarsValue]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Comme__5866164A] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Autho__595A3A83] DEFAULT ('') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Autho__5A4E5EBC] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__DateC__5B4282F5] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO

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

---------------------------------------------
-- fp.GlobalSpread ------------------
---------------------------------------------
CREATE TABLE [fp].[GlobalSpread] (
    [GlobalSpreadID] int NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [SpreadName] nvarchar(4000) NOT NULL,
    [SortOrder] int NOT NULL,
    [SpreadPercentage01] decimal NOT NULL,
    [SpreadPercentage02] decimal NOT NULL,
    [SpreadPercentage03] decimal NOT NULL,
    [SpreadPercentage04] decimal NOT NULL,
    [SpreadPercentage05] decimal NOT NULL,
    [SpreadPercentage06] decimal NOT NULL,
    [SpreadPercentage07] decimal NOT NULL,
    [SpreadPercentage08] decimal NOT NULL,
    [SpreadPercentage09] decimal NOT NULL,
    [SpreadPercentage10] decimal NOT NULL,
    [SpreadPercentage11] decimal NOT NULL,
    [SpreadPercentage12] decimal NOT NULL,
    [TotalSpreadValue] decimal NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([GlobalSpreadID])
);
GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [df_GlobalSpread_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Budge__5AF6082D] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5BEA2C66] DEFAULT ('') FOR [SpreadName]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__SortO__5CDE509F] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5DD274D8] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5EC69911] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5FBABD4A] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__60AEE183] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__61A305BC] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__629729F5] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__638B4E2E] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__647F7267] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__657396A0] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__6667BAD9] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__675BDF12] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__6850034B] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Total__69442784] DEFAULT ((0)) FOR [TotalSpreadValue]; GO

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

---------------------------------------------
-- fp.InitialPlanRule ------------------
---------------------------------------------
CREATE TABLE [fp].[InitialPlanRule] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [PlanSectionID] int NOT NULL,
    [SubSectionID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [DimensionalityJSON] nvarchar(max) NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [RulePriority] int NOT NULL,
    [VersionID] int NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [FK__InitialPl__Budge__269DA93F] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [FK__InitialPl__Versi__344CAA18] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Budge__1E08633E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Budge__1EFC8777] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__PlanS__1FF0ABB0] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__SubSe__20E4CFE9] DEFAULT ((0)) FOR [SubSectionID]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__TimeC__21D8F422] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Dimen__22CD185B] DEFAULT ('') FOR [DimensionalityJSON]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Proje__23C13C94] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Trail__24B560CD] DEFAULT ((0)) FOR [TrailingMonths]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__RuleP__25A98506] DEFAULT ((0)) FOR [RulePriority]; GO
ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Versi__335885DF] DEFAULT ((0)) FOR [VersionID]; GO

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

---------------------------------------------
-- fp.InitialPlanRuleHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[InitialPlanRuleHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [PlanSectionID] int NOT NULL,
    [SubSectionID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [DimensionalityJSON] nvarchar(max) NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [RulePriority] int NOT NULL,
    [VersionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [FK__InitialPl__Budge__307C1934] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [FK__InitialPl__Versi__31703D6D] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Budge__26F2AEFA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Budge__27E6D333] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__PlanS__28DAF76C] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__SubSe__29CF1BA5] DEFAULT ((0)) FOR [SubSectionID]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__TimeC__2AC33FDE] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Dimen__2BB76417] DEFAULT ('') FOR [DimensionalityJSON]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Proje__2CAB8850] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Trail__2D9FAC89] DEFAULT ((0)) FOR [TrailingMonths]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__RuleP__2E93D0C2] DEFAULT ((0)) FOR [RulePriority]; GO
ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Versi__2F87F4FB] DEFAULT ((0)) FOR [VersionID]; GO

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

---------------------------------------------
-- fp.InitialPlanRuleVersion ------------------
---------------------------------------------
CREATE TABLE [fp].[InitialPlanRuleVersion] (
    [VersionID] int NOT NULL,
    [DateCreated] datetime NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [IsSampled] bit NOT NULL,
    [IsConfigDetailDataReady] bit NOT NULL,
    PRIMARY KEY ([VersionID])
);
GO
ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__DateC__222DF9DD] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__Autho__23221E16] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__Autho__2416424F] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__IsSam__2826CA55] DEFAULT ((0)) FOR [IsSampled]; GO
ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__IsCon__5736BEF9] DEFAULT ((0)) FOR [IsConfigDetailDataReady]; GO

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

---------------------------------------------
-- fp.LineItemJobCode ------------------
---------------------------------------------
CREATE TABLE [fp].[LineItemJobCode] (
    [RowID] int NOT NULL,
    [FinancialLineItem] nvarchar(100) NOT NULL,
    [JobCodeID] int NOT NULL,
    [JobCode] nvarchar(100) NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [PreviousActualHours] decimal NOT NULL,
    [YTDActualHours] decimal NOT NULL,
    [CurrentBudgetHours] decimal NOT NULL,
    [JanBudgetHours] decimal NOT NULL,
    [FebBudgetHours] decimal NOT NULL,
    [MarBudgetHours] decimal NOT NULL,
    [AprBudgetHours] decimal NOT NULL,
    [MayBudgetHours] decimal NOT NULL,
    [JunBudgetHours] decimal NOT NULL,
    [JulBudgetHours] decimal NOT NULL,
    [AugBudgetHours] decimal NOT NULL,
    [SepBudgetHours] decimal NOT NULL,
    [OctBudgetHours] decimal NOT NULL,
    [NovBudgetHours] decimal NOT NULL,
    [DecBudgetHours] decimal NOT NULL,
    [PreviousActualWorkingHours] decimal NOT NULL,
    [YTDActualWorkingHours] decimal NOT NULL,
    [CurrentBudgetWorkingHours] decimal NOT NULL,
    [JanBudgetWorkingHours] decimal NOT NULL,
    [FebBudgetWorkingHours] decimal NOT NULL,
    [MarBudgetWorkingHours] decimal NOT NULL,
    [AprBudgetWorkingHours] decimal NOT NULL,
    [MayBudgetWorkingHours] decimal NOT NULL,
    [JunBudgetWorkingHours] decimal NOT NULL,
    [JulBudgetWorkingHours] decimal NOT NULL,
    [AugBudgetWorkingHours] decimal NOT NULL,
    [SepBudgetWorkingHours] decimal NOT NULL,
    [OctBudgetWorkingHours] decimal NOT NULL,
    [NovBudgetWorkingHours] decimal NOT NULL,
    [DecBudgetWorkingHours] decimal NOT NULL,
    [PreviousActualFTEs] decimal NOT NULL,
    [YTDActualFTEs] decimal NOT NULL,
    [CurrentBudgetFTEs] decimal NOT NULL,
    [JanBudgetFTEs] decimal NOT NULL,
    [FebBudgetFTEs] decimal NOT NULL,
    [MarBudgetFTEs] decimal NOT NULL,
    [AprBudgetFTEs] decimal NOT NULL,
    [MayBudgetFTEs] decimal NOT NULL,
    [JunBudgetFTEs] decimal NOT NULL,
    [JulBudgetFTEs] decimal NOT NULL,
    [AugBudgetFTEs] decimal NOT NULL,
    [SepBudgetFTEs] decimal NOT NULL,
    [OctBudgetFTEs] decimal NOT NULL,
    [NovBudgetFTEs] decimal NOT NULL,
    [DecBudgetFTEs] decimal NOT NULL,
    [PreviousActualDollars] decimal NOT NULL,
    [YTDActualDollars] decimal NOT NULL,
    [CurrentBudgetDollars] decimal NOT NULL,
    [JanBudgetDollars] decimal NOT NULL,
    [FebBudgetDollars] decimal NOT NULL,
    [MarBudgetDollars] decimal NOT NULL,
    [AprBudgetDollars] decimal NOT NULL,
    [MayBudgetDollars] decimal NOT NULL,
    [JunBudgetDollars] decimal NOT NULL,
    [JulBudgetDollars] decimal NOT NULL,
    [AugBudgetDollars] decimal NOT NULL,
    [SepBudgetDollars] decimal NOT NULL,
    [OctBudgetDollars] decimal NOT NULL,
    [NovBudgetDollars] decimal NOT NULL,
    [DecBudgetDollars] decimal NOT NULL,
    [PreviousActualWageRate] decimal NOT NULL,
    [YTDActualWageRate] decimal NOT NULL,
    [CurrentBudgetWageRate] decimal NOT NULL,
    [CurrentBudgetWageRateMultiplier] decimal NOT NULL,
    [JanBudgetWageRate] decimal NOT NULL,
    [FebBudgetWageRate] decimal NOT NULL,
    [MarBudgetWageRate] decimal NOT NULL,
    [AprBudgetWageRate] decimal NOT NULL,
    [MayBudgetWageRate] decimal NOT NULL,
    [JunBudgetWageRate] decimal NOT NULL,
    [JulBudgetWageRate] decimal NOT NULL,
    [AugBudgetWageRate] decimal NOT NULL,
    [SepBudgetWageRate] decimal NOT NULL,
    [OctBudgetWageRate] decimal NOT NULL,
    [NovBudgetWageRate] decimal NOT NULL,
    [DecBudgetWageRate] decimal NOT NULL,
    [OriginalBudgetHours] decimal NOT NULL,
    [OriginalBudgetFTEs] decimal NOT NULL,
    [OriginalBudgetDollars] decimal NOT NULL,
    [OriginalBudgetWageRate] decimal NOT NULL,
    [AnnualizedActualHours] decimal NOT NULL,
    [AnnualizedActualWorkingHours] decimal NOT NULL,
    [AnnualizedActualDollars] decimal NOT NULL,
    [AnnualizedActualFTEs] decimal NOT NULL,
    [AnnualizedActualWageRate] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__052A70A3] DEFAULT ((0)) FOR [AnnualizedActualHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__061E94DC] DEFAULT ((0)) FOR [AnnualizedActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__0712B915] DEFAULT ((0)) FOR [AnnualizedActualDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__0806DD4E] DEFAULT ((0)) FOR [AnnualizedActualFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__08FB0187] DEFAULT ((0)) FOR [AnnualizedActualWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FinancialLineItem] DEFAULT ('') FOR [FinancialLineItem]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JobCode] DEFAULT ('') FOR [JobCode]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualHours] DEFAULT ((0)) FOR [PreviousActualHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualHours] DEFAULT ((0)) FOR [YTDActualHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetHours] DEFAULT ((0)) FOR [CurrentBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetHours] DEFAULT ((0)) FOR [JanBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetHours] DEFAULT ((0)) FOR [FebBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetHours] DEFAULT ((0)) FOR [MarBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetHours] DEFAULT ((0)) FOR [AprBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetHours] DEFAULT ((0)) FOR [MayBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetHours] DEFAULT ((0)) FOR [JunBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetHours] DEFAULT ((0)) FOR [JulBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetHours] DEFAULT ((0)) FOR [AugBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetHours] DEFAULT ((0)) FOR [SepBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetHours] DEFAULT ((0)) FOR [OctBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetHours] DEFAULT ((0)) FOR [NovBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetHours] DEFAULT ((0)) FOR [DecBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualWorkingHours] DEFAULT ((0)) FOR [PreviousActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualWorkingHours] DEFAULT ((0)) FOR [YTDActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetWorkingHours] DEFAULT ((0)) FOR [CurrentBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetWorkingHours] DEFAULT ((0)) FOR [JanBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetWorkingHours] DEFAULT ((0)) FOR [FebBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetWorkingHours] DEFAULT ((0)) FOR [MarBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetWorkingHours] DEFAULT ((0)) FOR [AprBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetWorkingHours] DEFAULT ((0)) FOR [MayBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetWorkingHours] DEFAULT ((0)) FOR [JunBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetWorkingHours] DEFAULT ((0)) FOR [JulBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetWorkingHours] DEFAULT ((0)) FOR [AugBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetWorkingHours] DEFAULT ((0)) FOR [SepBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetWorkingHours] DEFAULT ((0)) FOR [OctBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetWorkingHours] DEFAULT ((0)) FOR [NovBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetWorkingHours] DEFAULT ((0)) FOR [DecBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualFTEs] DEFAULT ((0)) FOR [PreviousActualFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [df_LineItemJobCode_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualFTEs] DEFAULT ((0)) FOR [YTDActualFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetFTEs] DEFAULT ((0)) FOR [CurrentBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetFTEs] DEFAULT ((0)) FOR [JanBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetFTEs] DEFAULT ((0)) FOR [FebBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetFTEs] DEFAULT ((0)) FOR [MarBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetFTEs] DEFAULT ((0)) FOR [AprBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetFTEs] DEFAULT ((0)) FOR [MayBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetFTEs] DEFAULT ((0)) FOR [JunBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetFTEs] DEFAULT ((0)) FOR [JulBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetFTEs] DEFAULT ((0)) FOR [AugBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetFTEs] DEFAULT ((0)) FOR [SepBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetFTEs] DEFAULT ((0)) FOR [OctBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetFTEs] DEFAULT ((0)) FOR [NovBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetFTEs] DEFAULT ((0)) FOR [DecBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualDollars] DEFAULT ((0)) FOR [PreviousActualDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualDollars] DEFAULT ((0)) FOR [YTDActualDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetDollars] DEFAULT ((0)) FOR [CurrentBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetDollars] DEFAULT ((0)) FOR [JanBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetDollars] DEFAULT ((0)) FOR [FebBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetDollars] DEFAULT ((0)) FOR [MarBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetDollars] DEFAULT ((0)) FOR [AprBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetDollars] DEFAULT ((0)) FOR [MayBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetDollars] DEFAULT ((0)) FOR [JunBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetDollars] DEFAULT ((0)) FOR [JulBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetDollars] DEFAULT ((0)) FOR [AugBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetDollars] DEFAULT ((0)) FOR [SepBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetDollars] DEFAULT ((0)) FOR [OctBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetDollars] DEFAULT ((0)) FOR [NovBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetDollars] DEFAULT ((0)) FOR [DecBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualWageRate] DEFAULT ((0)) FOR [PreviousActualWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualWageRate] DEFAULT ((0)) FOR [YTDActualWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetWageRate] DEFAULT ((0)) FOR [CurrentBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetWageRateMultiplier] DEFAULT ((0)) FOR [CurrentBudgetWageRateMultiplier]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetWageRate] DEFAULT ((0)) FOR [JanBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetWageRate] DEFAULT ((0)) FOR [FebBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetWageRate] DEFAULT ((0)) FOR [MarBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetWageRate] DEFAULT ((0)) FOR [AprBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetWageRate] DEFAULT ((0)) FOR [MayBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetWageRate] DEFAULT ((0)) FOR [JunBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__4FC2842B] DEFAULT ((0)) FOR [OriginalBudgetHours]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetWageRate] DEFAULT ((0)) FOR [JulBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__50B6A864] DEFAULT ((0)) FOR [OriginalBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetWageRate] DEFAULT ((0)) FOR [AugBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__51AACC9D] DEFAULT ((0)) FOR [OriginalBudgetDollars]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetWageRate] DEFAULT ((0)) FOR [SepBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__529EF0D6] DEFAULT ((0)) FOR [OriginalBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetWageRate] DEFAULT ((0)) FOR [OctBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetWageRate] DEFAULT ((0)) FOR [NovBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetWageRate] DEFAULT ((0)) FOR [DecBudgetWageRate]; GO

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

---------------------------------------------
-- fp.LineItemPayCodeGroup ------------------
---------------------------------------------
CREATE TABLE [fp].[LineItemPayCodeGroup] (
    [RowID] int NOT NULL,
    [FinancialLineItem] nvarchar(100) NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [PayCodeGroup] nvarchar(100) NOT NULL,
    [PayCodeGroupSortOrder] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [ProductiveClass] nvarchar(100) NOT NULL,
    [JobCodeID] int NOT NULL,
    [JobCode] nvarchar(100) NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [PreviousActualHours] decimal NOT NULL,
    [YTDActualHours] decimal NOT NULL,
    [CurrentBudgetHours] decimal NOT NULL,
    [JanBudgetHours] decimal NOT NULL,
    [FebBudgetHours] decimal NOT NULL,
    [MarBudgetHours] decimal NOT NULL,
    [AprBudgetHours] decimal NOT NULL,
    [MayBudgetHours] decimal NOT NULL,
    [JunBudgetHours] decimal NOT NULL,
    [JulBudgetHours] decimal NOT NULL,
    [AugBudgetHours] decimal NOT NULL,
    [SepBudgetHours] decimal NOT NULL,
    [OctBudgetHours] decimal NOT NULL,
    [NovBudgetHours] decimal NOT NULL,
    [DecBudgetHours] decimal NOT NULL,
    [PreviousActualWorkingHours] decimal NOT NULL,
    [YTDActualWorkingHours] decimal NOT NULL,
    [CurrentBudgetWorkingHours] decimal NOT NULL,
    [JanBudgetWorkingHours] decimal NOT NULL,
    [FebBudgetWorkingHours] decimal NOT NULL,
    [MarBudgetWorkingHours] decimal NOT NULL,
    [AprBudgetWorkingHours] decimal NOT NULL,
    [MayBudgetWorkingHours] decimal NOT NULL,
    [JunBudgetWorkingHours] decimal NOT NULL,
    [JulBudgetWorkingHours] decimal NOT NULL,
    [AugBudgetWorkingHours] decimal NOT NULL,
    [SepBudgetWorkingHours] decimal NOT NULL,
    [OctBudgetWorkingHours] decimal NOT NULL,
    [NovBudgetWorkingHours] decimal NOT NULL,
    [DecBudgetWorkingHours] decimal NOT NULL,
    [PreviousActualFTEs] decimal NOT NULL,
    [YTDActualFTEs] decimal NOT NULL,
    [CurrentBudgetFTEs] decimal NOT NULL,
    [JanBudgetFTEs] decimal NOT NULL,
    [FebBudgetFTEs] decimal NOT NULL,
    [MarBudgetFTEs] decimal NOT NULL,
    [AprBudgetFTEs] decimal NOT NULL,
    [MayBudgetFTEs] decimal NOT NULL,
    [JunBudgetFTEs] decimal NOT NULL,
    [JulBudgetFTEs] decimal NOT NULL,
    [AugBudgetFTEs] decimal NOT NULL,
    [SepBudgetFTEs] decimal NOT NULL,
    [OctBudgetFTEs] decimal NOT NULL,
    [NovBudgetFTEs] decimal NOT NULL,
    [DecBudgetFTEs] decimal NOT NULL,
    [PreviousActualDollars] decimal NOT NULL,
    [YTDActualDollars] decimal NOT NULL,
    [CurrentBudgetDollars] decimal NOT NULL,
    [JanBudgetDollars] decimal NOT NULL,
    [FebBudgetDollars] decimal NOT NULL,
    [MarBudgetDollars] decimal NOT NULL,
    [AprBudgetDollars] decimal NOT NULL,
    [MayBudgetDollars] decimal NOT NULL,
    [JunBudgetDollars] decimal NOT NULL,
    [JulBudgetDollars] decimal NOT NULL,
    [AugBudgetDollars] decimal NOT NULL,
    [SepBudgetDollars] decimal NOT NULL,
    [OctBudgetDollars] decimal NOT NULL,
    [NovBudgetDollars] decimal NOT NULL,
    [DecBudgetDollars] decimal NOT NULL,
    [PreviousActualWageRate] decimal NOT NULL,
    [YTDActualWageRate] decimal NOT NULL,
    [CurrentBudgetWageRate] decimal NOT NULL,
    [CurrentBudgetWageRateMultiplier] decimal NOT NULL,
    [JanBudgetWageRate] decimal NOT NULL,
    [FebBudgetWageRate] decimal NOT NULL,
    [MarBudgetWageRate] decimal NOT NULL,
    [AprBudgetWageRate] decimal NOT NULL,
    [MayBudgetWageRate] decimal NOT NULL,
    [JunBudgetWageRate] decimal NOT NULL,
    [JulBudgetWageRate] decimal NOT NULL,
    [AugBudgetWageRate] decimal NOT NULL,
    [SepBudgetWageRate] decimal NOT NULL,
    [OctBudgetWageRate] decimal NOT NULL,
    [NovBudgetWageRate] decimal NOT NULL,
    [DecBudgetWageRate] decimal NOT NULL,
    [OriginalBudgetHours] decimal NOT NULL,
    [OriginalBudgetFTEs] decimal NOT NULL,
    [OriginalBudgetDollars] decimal NOT NULL,
    [OriginalBudgetWageRate] decimal NOT NULL,
    [AnnualizedActualHours] decimal NOT NULL,
    [AnnualizedActualWorkingHours] decimal NOT NULL,
    [AnnualizedActualDollars] decimal NOT NULL,
    [AnnualizedActualFTEs] decimal NOT NULL,
    [AnnualizedActualWageRate] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__09EF25C0] DEFAULT ((0)) FOR [AnnualizedActualHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0AE349F9] DEFAULT ((0)) FOR [AnnualizedActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0BD76E32] DEFAULT ((0)) FOR [AnnualizedActualDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0CCB926B] DEFAULT ((0)) FOR [AnnualizedActualFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0DBFB6A4] DEFAULT ((0)) FOR [AnnualizedActualWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FinancialLineItem] DEFAULT ('') FOR [FinancialLineItem]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PayCodeGroup] DEFAULT ('') FOR [PayCodeGroup]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PayCodeGroupSortOrder] DEFAULT ((0)) FOR [PayCodeGroupSortOrder]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_ProductiveClassID] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_ProductiveClass] DEFAULT ('') FOR [ProductiveClass]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JobCode] DEFAULT ('') FOR [JobCode]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualHours] DEFAULT ((0)) FOR [PreviousActualHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualHours] DEFAULT ((0)) FOR [YTDActualHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetHours] DEFAULT ((0)) FOR [CurrentBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetHours] DEFAULT ((0)) FOR [JanBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetHours] DEFAULT ((0)) FOR [FebBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetHours] DEFAULT ((0)) FOR [MarBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetHours] DEFAULT ((0)) FOR [AprBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetHours] DEFAULT ((0)) FOR [MayBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [df_LineItemPayCodeGroup_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetHours] DEFAULT ((0)) FOR [JunBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetHours] DEFAULT ((0)) FOR [JulBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetHours] DEFAULT ((0)) FOR [AugBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetHours] DEFAULT ((0)) FOR [SepBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetHours] DEFAULT ((0)) FOR [OctBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetHours] DEFAULT ((0)) FOR [NovBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetHours] DEFAULT ((0)) FOR [DecBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualWorkingHours] DEFAULT ((0)) FOR [PreviousActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualWorkingHours] DEFAULT ((0)) FOR [YTDActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetWorkingHours] DEFAULT ((0)) FOR [CurrentBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetWorkingHours] DEFAULT ((0)) FOR [JanBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetWorkingHours] DEFAULT ((0)) FOR [FebBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetWorkingHours] DEFAULT ((0)) FOR [MarBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetWorkingHours] DEFAULT ((0)) FOR [AprBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetWorkingHours] DEFAULT ((0)) FOR [MayBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetWorkingHours] DEFAULT ((0)) FOR [JunBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetWorkingHours] DEFAULT ((0)) FOR [JulBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetWorkingHours] DEFAULT ((0)) FOR [AugBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetWorkingHours] DEFAULT ((0)) FOR [SepBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetWorkingHours] DEFAULT ((0)) FOR [OctBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetWorkingHours] DEFAULT ((0)) FOR [NovBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetWorkingHours] DEFAULT ((0)) FOR [DecBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualFTEs] DEFAULT ((0)) FOR [PreviousActualFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualFTEs] DEFAULT ((0)) FOR [YTDActualFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetFTEs] DEFAULT ((0)) FOR [CurrentBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetFTEs] DEFAULT ((0)) FOR [JanBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetFTEs] DEFAULT ((0)) FOR [FebBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetFTEs] DEFAULT ((0)) FOR [MarBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__5393150F] DEFAULT ((0)) FOR [OriginalBudgetHours]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetFTEs] DEFAULT ((0)) FOR [AprBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__54873948] DEFAULT ((0)) FOR [OriginalBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetFTEs] DEFAULT ((0)) FOR [MayBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__557B5D81] DEFAULT ((0)) FOR [OriginalBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetFTEs] DEFAULT ((0)) FOR [JunBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__566F81BA] DEFAULT ((0)) FOR [OriginalBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetFTEs] DEFAULT ((0)) FOR [JulBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetFTEs] DEFAULT ((0)) FOR [AugBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetFTEs] DEFAULT ((0)) FOR [SepBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetFTEs] DEFAULT ((0)) FOR [OctBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetFTEs] DEFAULT ((0)) FOR [NovBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetFTEs] DEFAULT ((0)) FOR [DecBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualDollars] DEFAULT ((0)) FOR [PreviousActualDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualDollars] DEFAULT ((0)) FOR [YTDActualDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetDollars] DEFAULT ((0)) FOR [CurrentBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetDollars] DEFAULT ((0)) FOR [JanBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetDollars] DEFAULT ((0)) FOR [FebBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetDollars] DEFAULT ((0)) FOR [MarBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetDollars] DEFAULT ((0)) FOR [AprBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetDollars] DEFAULT ((0)) FOR [MayBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetDollars] DEFAULT ((0)) FOR [JunBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetDollars] DEFAULT ((0)) FOR [JulBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetDollars] DEFAULT ((0)) FOR [AugBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetDollars] DEFAULT ((0)) FOR [SepBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetDollars] DEFAULT ((0)) FOR [OctBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetDollars] DEFAULT ((0)) FOR [NovBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetDollars] DEFAULT ((0)) FOR [DecBudgetDollars]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualWageRate] DEFAULT ((0)) FOR [PreviousActualWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualWageRate] DEFAULT ((0)) FOR [YTDActualWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetWageRate] DEFAULT ((0)) FOR [CurrentBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetWageRateMultiplier] DEFAULT ((0)) FOR [CurrentBudgetWageRateMultiplier]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetWageRate] DEFAULT ((0)) FOR [JanBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetWageRate] DEFAULT ((0)) FOR [FebBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetWageRate] DEFAULT ((0)) FOR [MarBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetWageRate] DEFAULT ((0)) FOR [AprBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetWageRate] DEFAULT ((0)) FOR [MayBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetWageRate] DEFAULT ((0)) FOR [JunBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetWageRate] DEFAULT ((0)) FOR [JulBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetWageRate] DEFAULT ((0)) FOR [AugBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetWageRate] DEFAULT ((0)) FOR [SepBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetWageRate] DEFAULT ((0)) FOR [OctBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetWageRate] DEFAULT ((0)) FOR [NovBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetWageRate] DEFAULT ((0)) FOR [DecBudgetWageRate]; GO

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

---------------------------------------------
-- fp.LineItemProductiveClass ------------------
---------------------------------------------
CREATE TABLE [fp].[LineItemProductiveClass] (
    [RowID] int NOT NULL,
    [FinancialLineItem] nvarchar(100) NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [ProductiveClass] nvarchar(100) NOT NULL,
    [ProductiveClassSortOrder] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [JobCode] nvarchar(100) NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [PreviousActualHours] decimal NOT NULL,
    [YTDActualHours] decimal NOT NULL,
    [CurrentBudgetHours] decimal NOT NULL,
    [JanBudgetHours] decimal NOT NULL,
    [FebBudgetHours] decimal NOT NULL,
    [MarBudgetHours] decimal NOT NULL,
    [AprBudgetHours] decimal NOT NULL,
    [MayBudgetHours] decimal NOT NULL,
    [JunBudgetHours] decimal NOT NULL,
    [JulBudgetHours] decimal NOT NULL,
    [AugBudgetHours] decimal NOT NULL,
    [SepBudgetHours] decimal NOT NULL,
    [OctBudgetHours] decimal NOT NULL,
    [NovBudgetHours] decimal NOT NULL,
    [DecBudgetHours] decimal NOT NULL,
    [PreviousActualWorkingHours] decimal NOT NULL,
    [YTDActualWorkingHours] decimal NOT NULL,
    [CurrentBudgetWorkingHours] decimal NOT NULL,
    [JanBudgetWorkingHours] decimal NOT NULL,
    [FebBudgetWorkingHours] decimal NOT NULL,
    [MarBudgetWorkingHours] decimal NOT NULL,
    [AprBudgetWorkingHours] decimal NOT NULL,
    [MayBudgetWorkingHours] decimal NOT NULL,
    [JunBudgetWorkingHours] decimal NOT NULL,
    [JulBudgetWorkingHours] decimal NOT NULL,
    [AugBudgetWorkingHours] decimal NOT NULL,
    [SepBudgetWorkingHours] decimal NOT NULL,
    [OctBudgetWorkingHours] decimal NOT NULL,
    [NovBudgetWorkingHours] decimal NOT NULL,
    [DecBudgetWorkingHours] decimal NOT NULL,
    [PreviousActualFTEs] decimal NOT NULL,
    [YTDActualFTEs] decimal NOT NULL,
    [CurrentBudgetFTEs] decimal NOT NULL,
    [JanBudgetFTEs] decimal NOT NULL,
    [FebBudgetFTEs] decimal NOT NULL,
    [MarBudgetFTEs] decimal NOT NULL,
    [AprBudgetFTEs] decimal NOT NULL,
    [MayBudgetFTEs] decimal NOT NULL,
    [JunBudgetFTEs] decimal NOT NULL,
    [JulBudgetFTEs] decimal NOT NULL,
    [AugBudgetFTEs] decimal NOT NULL,
    [SepBudgetFTEs] decimal NOT NULL,
    [OctBudgetFTEs] decimal NOT NULL,
    [NovBudgetFTEs] decimal NOT NULL,
    [DecBudgetFTEs] decimal NOT NULL,
    [PreviousActualDollars] decimal NOT NULL,
    [YTDActualDollars] decimal NOT NULL,
    [CurrentBudgetDollars] decimal NOT NULL,
    [JanBudgetDollars] decimal NOT NULL,
    [FebBudgetDollars] decimal NOT NULL,
    [MarBudgetDollars] decimal NOT NULL,
    [AprBudgetDollars] decimal NOT NULL,
    [MayBudgetDollars] decimal NOT NULL,
    [JunBudgetDollars] decimal NOT NULL,
    [JulBudgetDollars] decimal NOT NULL,
    [AugBudgetDollars] decimal NOT NULL,
    [SepBudgetDollars] decimal NOT NULL,
    [OctBudgetDollars] decimal NOT NULL,
    [NovBudgetDollars] decimal NOT NULL,
    [DecBudgetDollars] decimal NOT NULL,
    [PreviousActualWageRate] decimal NOT NULL,
    [YTDActualWageRate] decimal NOT NULL,
    [CurrentBudgetWageRate] decimal NOT NULL,
    [CurrentBudgetWageRateMultiplier] decimal NOT NULL,
    [JanBudgetWageRate] decimal NOT NULL,
    [FebBudgetWageRate] decimal NOT NULL,
    [MarBudgetWageRate] decimal NOT NULL,
    [AprBudgetWageRate] decimal NOT NULL,
    [MayBudgetWageRate] decimal NOT NULL,
    [JunBudgetWageRate] decimal NOT NULL,
    [JulBudgetWageRate] decimal NOT NULL,
    [AugBudgetWageRate] decimal NOT NULL,
    [SepBudgetWageRate] decimal NOT NULL,
    [OctBudgetWageRate] decimal NOT NULL,
    [NovBudgetWageRate] decimal NOT NULL,
    [DecBudgetWageRate] decimal NOT NULL,
    [OriginalBudgetHours] decimal NOT NULL,
    [OriginalBudgetFTEs] decimal NOT NULL,
    [OriginalBudgetDollars] decimal NOT NULL,
    [OriginalBudgetWageRate] decimal NOT NULL,
    [AnnualizedActualHours] decimal NOT NULL,
    [AnnualizedActualWorkingHours] decimal NOT NULL,
    [AnnualizedActualDollars] decimal NOT NULL,
    [AnnualizedActualFTEs] decimal NOT NULL,
    [AnnualizedActualWageRate] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetFTEs] DEFAULT ((0)) FOR [MarBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetFTEs] DEFAULT ((0)) FOR [AprBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetFTEs] DEFAULT ((0)) FOR [MayBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetFTEs] DEFAULT ((0)) FOR [JunBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetFTEs] DEFAULT ((0)) FOR [JulBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetFTEs] DEFAULT ((0)) FOR [AugBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetFTEs] DEFAULT ((0)) FOR [SepBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetFTEs] DEFAULT ((0)) FOR [OctBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetFTEs] DEFAULT ((0)) FOR [NovBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetFTEs] DEFAULT ((0)) FOR [DecBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualDollars] DEFAULT ((0)) FOR [PreviousActualDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualDollars] DEFAULT ((0)) FOR [YTDActualDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetDollars] DEFAULT ((0)) FOR [CurrentBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetDollars] DEFAULT ((0)) FOR [JanBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetDollars] DEFAULT ((0)) FOR [FebBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetDollars] DEFAULT ((0)) FOR [MarBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__0EB3DADD] DEFAULT ((0)) FOR [AnnualizedActualHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetDollars] DEFAULT ((0)) FOR [AprBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__0FA7FF16] DEFAULT ((0)) FOR [AnnualizedActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetDollars] DEFAULT ((0)) FOR [MayBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__109C234F] DEFAULT ((0)) FOR [AnnualizedActualDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetDollars] DEFAULT ((0)) FOR [JunBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__11904788] DEFAULT ((0)) FOR [AnnualizedActualFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetDollars] DEFAULT ((0)) FOR [JulBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__12846BC1] DEFAULT ((0)) FOR [AnnualizedActualWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetDollars] DEFAULT ((0)) FOR [AugBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetDollars] DEFAULT ((0)) FOR [SepBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetDollars] DEFAULT ((0)) FOR [OctBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetDollars] DEFAULT ((0)) FOR [NovBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetDollars] DEFAULT ((0)) FOR [DecBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualWageRate] DEFAULT ((0)) FOR [PreviousActualWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualWageRate] DEFAULT ((0)) FOR [YTDActualWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetWageRate] DEFAULT ((0)) FOR [CurrentBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetWageRateMultiplier] DEFAULT ((0)) FOR [CurrentBudgetWageRateMultiplier]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetWageRate] DEFAULT ((0)) FOR [JanBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetWageRate] DEFAULT ((0)) FOR [FebBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetWageRate] DEFAULT ((0)) FOR [MarBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetWageRate] DEFAULT ((0)) FOR [AprBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetWageRate] DEFAULT ((0)) FOR [MayBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetWageRate] DEFAULT ((0)) FOR [JunBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetWageRate] DEFAULT ((0)) FOR [JulBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetWageRate] DEFAULT ((0)) FOR [AugBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetWageRate] DEFAULT ((0)) FOR [SepBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetWageRate] DEFAULT ((0)) FOR [OctBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetWageRate] DEFAULT ((0)) FOR [NovBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetWageRate] DEFAULT ((0)) FOR [DecBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [df_LineItemProductiveClass_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__5763A5F3] DEFAULT ((0)) FOR [OriginalBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__5857CA2C] DEFAULT ((0)) FOR [OriginalBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FinancialLineItem] DEFAULT ('') FOR [FinancialLineItem]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__594BEE65] DEFAULT ((0)) FOR [OriginalBudgetDollars]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_ProductiveClassID] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__5A40129E] DEFAULT ((0)) FOR [OriginalBudgetWageRate]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_ProductiveClass] DEFAULT ('') FOR [ProductiveClass]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_ProductiveClassSortOrder] DEFAULT ((0)) FOR [ProductiveClassSortOrder]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JobCode] DEFAULT ('') FOR [JobCode]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualHours] DEFAULT ((0)) FOR [PreviousActualHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualHours] DEFAULT ((0)) FOR [YTDActualHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetHours] DEFAULT ((0)) FOR [CurrentBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetHours] DEFAULT ((0)) FOR [JanBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetHours] DEFAULT ((0)) FOR [FebBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetHours] DEFAULT ((0)) FOR [MarBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetHours] DEFAULT ((0)) FOR [AprBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetHours] DEFAULT ((0)) FOR [MayBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetHours] DEFAULT ((0)) FOR [JunBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetHours] DEFAULT ((0)) FOR [JulBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetHours] DEFAULT ((0)) FOR [AugBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetHours] DEFAULT ((0)) FOR [SepBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetHours] DEFAULT ((0)) FOR [OctBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetHours] DEFAULT ((0)) FOR [NovBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetHours] DEFAULT ((0)) FOR [DecBudgetHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualWorkingHours] DEFAULT ((0)) FOR [PreviousActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualWorkingHours] DEFAULT ((0)) FOR [YTDActualWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetWorkingHours] DEFAULT ((0)) FOR [CurrentBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetWorkingHours] DEFAULT ((0)) FOR [JanBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetWorkingHours] DEFAULT ((0)) FOR [FebBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetWorkingHours] DEFAULT ((0)) FOR [MarBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetWorkingHours] DEFAULT ((0)) FOR [AprBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetWorkingHours] DEFAULT ((0)) FOR [MayBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetWorkingHours] DEFAULT ((0)) FOR [JunBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetWorkingHours] DEFAULT ((0)) FOR [JulBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetWorkingHours] DEFAULT ((0)) FOR [AugBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetWorkingHours] DEFAULT ((0)) FOR [SepBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetWorkingHours] DEFAULT ((0)) FOR [OctBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetWorkingHours] DEFAULT ((0)) FOR [NovBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetWorkingHours] DEFAULT ((0)) FOR [DecBudgetWorkingHours]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualFTEs] DEFAULT ((0)) FOR [PreviousActualFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualFTEs] DEFAULT ((0)) FOR [YTDActualFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetFTEs] DEFAULT ((0)) FOR [CurrentBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetFTEs] DEFAULT ((0)) FOR [JanBudgetFTEs]; GO
ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetFTEs] DEFAULT ((0)) FOR [FebBudgetFTEs]; GO

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

---------------------------------------------
-- fp.ModelSectionMap ------------------
---------------------------------------------
CREATE TABLE [fp].[ModelSectionMap] (
    [ModelSectionMapID] int NOT NULL,
    [OBModelSectionName] nvarchar(200) NOT NULL,
    [APEModelSectionID] tinyint NOT NULL,
    [APEModelSectionName] nvarchar(200) NOT NULL,
    PRIMARY KEY ([ModelSectionMapID])
);
GO
ALTER TABLE [fp].[ModelSectionMap] ADD CONSTRAINT [DF__ModelSect__OBMod__03C8712D] DEFAULT ('') FOR [OBModelSectionName]; GO
ALTER TABLE [fp].[ModelSectionMap] ADD CONSTRAINT [DF__ModelSect__APEMo__04BC9566] DEFAULT ((0)) FOR [APEModelSectionID]; GO
ALTER TABLE [fp].[ModelSectionMap] ADD CONSTRAINT [DF__ModelSect__APEMo__05B0B99F] DEFAULT ('') FOR [APEModelSectionName]; GO

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

---------------------------------------------
-- fp.NSOverrideFlexConfigAssignment ------------------
---------------------------------------------
CREATE TABLE [fp].[NSOverrideFlexConfigAssignment] (
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    [AccountID] int NOT NULL,
    [RowID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [Unique_NSOverrideFlexConfigAssignment_Account_FlexGUID] ON [fp].[NSOverrideFlexConfigAssignment] ([OverrideFlexConfigGUID], [AccountID]);
GO

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

---------------------------------------------
-- fp.NonStaffingExpenseFlexingConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[NonStaffingExpenseFlexingConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID])
);
GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [FK__NonStaffi__Depar__3ED8EC6C] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [df_NonStaffingExpenseFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__NonStaffi__Depar__7891F199] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__NonStaffi__FlexM__798615D2] DEFAULT ((0)) FOR [FlexMethodID]; GO

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

---------------------------------------------
-- fp.NonStaffingExpenseFlexingOverrideConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    [RowID] int NOT NULL,
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [Unique_NonStaffingExpenseFlexingOverrideConfig_EC_Dept_Account] ON [fp].[NonStaffingExpenseFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]);
CREATE UNIQUE NONCLUSTERED INDEX [UQ__NonStaff__173FA2A66EA0FA40] ON [fp].[NonStaffingExpenseFlexingOverrideConfig] ([OverrideFlexConfigGUID]);
GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [FK__NonStaffi__Accou__4585E9FB] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [FK__NonStaffi__Depar__4491C5C2] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [df_NonStaffingExpenseFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__Depar__654A12FB] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__Accou__663E3734] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__FlexM__67325B6D] DEFAULT ((0)) FOR [FlexMethodID]; GO
ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__Overr__6FC7A16E] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO

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

---------------------------------------------
-- fp.NonStaffingVariabilityConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[NonStaffingVariabilityConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [AccountID] int NOT NULL,
    [Variability] decimal NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [AccountID])
);
GO
ALTER TABLE [fp].[NonStaffingVariabilityConfig] ADD CONSTRAINT [DF__NonStaffi__Accou__0601C6A7] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[NonStaffingVariabilityConfig] ADD CONSTRAINT [DF__NonStaffi__Varia__06F5EAE0] DEFAULT ((0)) FOR [Variability]; GO
ALTER TABLE [fp].[NonStaffingVariabilityConfig] ADD CONSTRAINT [df_NonStaffingVariabilityConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO

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

---------------------------------------------
-- fp.OldToNewChargeVolumeIDMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[OldToNewChargeVolumeIDMapping] (
    [RowID] int NOT NULL,
    [OldChargeVolumeID] int NOT NULL,
    [NewChargeVolumeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[OldToNewChargeVolumeIDMapping] ADD CONSTRAINT [DF__OldToNewC__OldCh__78B617A7] DEFAULT ((0)) FOR [OldChargeVolumeID]; GO
ALTER TABLE [fp].[OldToNewChargeVolumeIDMapping] ADD CONSTRAINT [DF__OldToNewC__NewCh__79AA3BE0] DEFAULT ((0)) FOR [NewChargeVolumeID]; GO

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

---------------------------------------------
-- fp.OldToNewGeneralLedgerIDMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[OldToNewGeneralLedgerIDMapping] (
    [RowID] int NOT NULL,
    [OldGeneralLedgerID] int NOT NULL,
    [NewGeneralLedgerID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[OldToNewGeneralLedgerIDMapping] ADD CONSTRAINT [DF__OldToNewG__OldGe__010144E5] DEFAULT ((0)) FOR [OldGeneralLedgerID]; GO
ALTER TABLE [fp].[OldToNewGeneralLedgerIDMapping] ADD CONSTRAINT [DF__OldToNewG__NewGe__01F5691E] DEFAULT ((0)) FOR [NewGeneralLedgerID]; GO
ALTER TABLE [fp].[OldToNewGeneralLedgerIDMapping] ADD CONSTRAINT [DF__OldToNewG__UnitT__02E98D57] DEFAULT ((0)) FOR [UnitTypeID]; GO

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

---------------------------------------------
-- fp.OldToNewServiceLineEncounterIDMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[OldToNewServiceLineEncounterIDMapping] (
    [RowID] int NOT NULL,
    [OldServiceLineEncounterID] int NOT NULL,
    [NewServiceLineEncounterID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[OldToNewServiceLineEncounterIDMapping] ADD CONSTRAINT [DF__OldToNewS__OldSe__74E586C3] DEFAULT ((0)) FOR [OldServiceLineEncounterID]; GO
ALTER TABLE [fp].[OldToNewServiceLineEncounterIDMapping] ADD CONSTRAINT [DF__OldToNewS__NewSe__75D9AAFC] DEFAULT ((0)) FOR [NewServiceLineEncounterID]; GO

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

---------------------------------------------
-- fp.OldToNewStaffingIDMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[OldToNewStaffingIDMapping] (
    [RowID] int NOT NULL,
    [OldStaffingID] int NOT NULL,
    [NewStaffingID] int NOT NULL,
    [UnitTypeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[OldToNewStaffingIDMapping] ADD CONSTRAINT [DF__OldToNewS__OldSt__5C307E40] DEFAULT ((0)) FOR [OldStaffingID]; GO
ALTER TABLE [fp].[OldToNewStaffingIDMapping] ADD CONSTRAINT [DF__OldToNewS__NewSt__5D24A279] DEFAULT ((0)) FOR [NewStaffingID]; GO
ALTER TABLE [fp].[OldToNewStaffingIDMapping] ADD CONSTRAINT [DF__OldToNewS__UnitT__5E18C6B2] DEFAULT ((0)) FOR [UnitTypeID]; GO

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

---------------------------------------------
-- fp.OnePlanPerformanceTestValidationResult ------------------
---------------------------------------------
CREATE TABLE [fp].[OnePlanPerformanceTestValidationResult] (
    [TestResultID] int NOT NULL,
    [PlanSectionID] int NOT NULL,
    [BasisID] int NOT NULL,
    [TableName] nvarchar(100) NOT NULL,
    [ColumnName] nvarchar(100) NOT NULL,
    [BeforeValue01] decimal NOT NULL,
    [BeforeValue02] decimal NOT NULL,
    [BeforeValue03] decimal NOT NULL,
    [BeforeValue04] decimal NOT NULL,
    [BeforeValue05] decimal NOT NULL,
    [BeforeValue06] decimal NOT NULL,
    [BeforeValue07] decimal NOT NULL,
    [BeforeValue08] decimal NOT NULL,
    [BeforeValue09] decimal NOT NULL,
    [BeforeValue10] decimal NOT NULL,
    [BeforeValue11] decimal NOT NULL,
    [BeforeValue12] decimal NOT NULL,
    [AfterValue01] decimal NOT NULL,
    [AfterValue02] decimal NOT NULL,
    [AfterValue03] decimal NOT NULL,
    [AfterValue04] decimal NOT NULL,
    [AfterValue05] decimal NOT NULL,
    [AfterValue06] decimal NOT NULL,
    [AfterValue07] decimal NOT NULL,
    [AfterValue08] decimal NOT NULL,
    [AfterValue09] decimal NOT NULL,
    [AfterValue10] decimal NOT NULL,
    [AfterValue11] decimal NOT NULL,
    [AfterValue12] decimal NOT NULL,
    [Variance01] decimal NULL,
    [Variance02] decimal NULL,
    [Variance03] decimal NULL,
    [Variance04] decimal NULL,
    [Variance05] decimal NULL,
    [Variance06] decimal NULL,
    [Variance07] decimal NULL,
    [Variance08] decimal NULL,
    [Variance09] decimal NULL,
    [Variance10] decimal NULL,
    [Variance11] decimal NULL,
    [Variance12] decimal NULL
);
GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__TestR__000EB75A] DEFAULT ((0)) FOR [TestResultID]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__PlanS__0102DB93] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Basis__01F6FFCC] DEFAULT ((0)) FOR [BasisID]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Table__02EB2405] DEFAULT ('') FOR [TableName]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Colum__03DF483E] DEFAULT ('') FOR [ColumnName]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__04D36C77] DEFAULT ((0)) FOR [BeforeValue01]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__05C790B0] DEFAULT ((0)) FOR [BeforeValue02]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__06BBB4E9] DEFAULT ((0)) FOR [BeforeValue03]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__07AFD922] DEFAULT ((0)) FOR [BeforeValue04]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__08A3FD5B] DEFAULT ((0)) FOR [BeforeValue05]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__09982194] DEFAULT ((0)) FOR [BeforeValue06]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0A8C45CD] DEFAULT ((0)) FOR [BeforeValue07]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0B806A06] DEFAULT ((0)) FOR [BeforeValue08]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0C748E3F] DEFAULT ((0)) FOR [BeforeValue09]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0D68B278] DEFAULT ((0)) FOR [BeforeValue10]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0E5CD6B1] DEFAULT ((0)) FOR [BeforeValue11]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0F50FAEA] DEFAULT ((0)) FOR [BeforeValue12]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__10451F23] DEFAULT ((0)) FOR [AfterValue01]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1139435C] DEFAULT ((0)) FOR [AfterValue02]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__122D6795] DEFAULT ((0)) FOR [AfterValue03]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__13218BCE] DEFAULT ((0)) FOR [AfterValue04]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1415B007] DEFAULT ((0)) FOR [AfterValue05]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1509D440] DEFAULT ((0)) FOR [AfterValue06]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__15FDF879] DEFAULT ((0)) FOR [AfterValue07]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__16F21CB2] DEFAULT ((0)) FOR [AfterValue08]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__17E640EB] DEFAULT ((0)) FOR [AfterValue09]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__18DA6524] DEFAULT ((0)) FOR [AfterValue10]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__19CE895D] DEFAULT ((0)) FOR [AfterValue11]; GO
ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1AC2AD96] DEFAULT ((0)) FOR [AfterValue12]; GO

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

---------------------------------------------
-- fp.PayrollVariabilityConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[PayrollVariabilityConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [JobCodeGroupID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [Variability] decimal NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [JobCodeGroupID], [JobCodeID])
);

CREATE NONCLUSTERED INDEX [NCNU_PayrollVariabilityConfig] ON [fp].[PayrollVariabilityConfig] ([EntityGroupConfigGUID], [JobCodeID]) INCLUDE ([Variability]);
GO
ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [df_PayrollVariabilityConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [DF__PayrollVa__JobCo__4C1F3DD5] DEFAULT ((0)) FOR [JobCodeGroupID]; GO
ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [DF__PayrollVa__JobCo__4D13620E] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [DF__PayrollVa__Varia__4E078647] DEFAULT ((0)) FOR [Variability]; GO

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

---------------------------------------------
-- fp.PercentageOfChargeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[PercentageOfChargeHistory] (
    [PercentageOfChargeHistoryGUID] uniqueidentifier NOT NULL,
    [Date] datetime NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(max) NOT NULL,
    [ExcelFile] varbinary(max) NULL,
    PRIMARY KEY ([PercentageOfChargeHistoryGUID])
);
GO
ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [df_PercentageOfChargeHistory_PercentageOfChargeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PercentageOfChargeHistoryGUID]; GO
ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [df_PercentageOfChargeHistory_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [DF__Percentage__Date__39201316] DEFAULT (getdate()) FOR [Date]; GO
ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [DF__Percentag__Autho__3B085B88] DEFAULT ('') FOR [AuthorFullName]; GO

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

---------------------------------------------
-- fp.PercentageOfChargeImport ------------------
---------------------------------------------
CREATE TABLE [fp].[PercentageOfChargeImport] (
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [TimeClassID], [DepartmentID], [AccountID])
);
GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [FK_PercentageOfChargeImport_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [FK_PercentageOfChargeImport_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Budge__25191A69] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Depar__260D3EA2] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Accou__27F58714] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__TimeC__29DDCF86] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2AD1F3BF] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2BC617F8] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2CBA3C31] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2DAE606A] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2EA284A3] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2F96A8DC] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__308ACD15] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__317EF14E] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__32731587] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__336739C0] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__345B5DF9] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__354F8232] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.PerformanceTestingSetting ------------------
---------------------------------------------
CREATE TABLE [fp].[PerformanceTestingSetting] (
    [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,
    [DateCreated] date NOT NULL,
    PRIMARY KEY ([SystemSettingID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_PerformanceTestingSetting_Unique] ON [fp].[PerformanceTestingSetting] ([Name]);
GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performanc__Name__5247ECAA] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Descr__533C10E3] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Value__5430351C] DEFAULT ('') FOR [Value]; GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__IsEdi__55245955] DEFAULT ((0)) FOR [IsEditable]; GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Colum__56187D8E] DEFAULT ((0)) FOR [ColumnType]; GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Defau__570CA1C7] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__IsEnc__5800C600] DEFAULT ((0)) FOR [IsEncrypted]; GO
ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__DateC__58F4EA39] DEFAULT (getdate()) FOR [DateCreated]; GO

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

---------------------------------------------
-- fp.PerformanceTestingSettingBySection ------------------
---------------------------------------------
CREATE TABLE [fp].[PerformanceTestingSettingBySection] (
    [SectionID] int NOT NULL,
    [Description] nvarchar(100) NOT NULL,
    [NumberOfRecordsInImport_LocalAdmin] int NOT NULL,
    [NumberOfRecordsInImport_SysAdmin] int NOT NULL,
    PRIMARY KEY ([SectionID])
);
GO
ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Numbe__053757DD] DEFAULT ((100)) FOR [NumberOfRecordsInImport_SysAdmin]; GO
ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Secti__1D8BA256] DEFAULT ((0)) FOR [SectionID]; GO
ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Descr__1E7FC68F] DEFAULT ((0)) FOR [Description]; GO
ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Numbe__1F73EAC8] DEFAULT ((0)) FOR [NumberOfRecordsInImport_LocalAdmin]; GO

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

---------------------------------------------
-- fp.PlanEditorCustomReportLink ------------------
---------------------------------------------
CREATE TABLE [fp].[PlanEditorCustomReportLink] (
    [CustomReportLinkGUID] uniqueidentifier NOT NULL,
    [ReportGUID] uniqueidentifier NOT NULL,
    [SectionID] int NOT NULL,
    PRIMARY KEY ([CustomReportLinkGUID])
);
GO
ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [FK_FpPlanEditorCustomReportLink_Report] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO
ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [DF__PlanEdito__Custo__35462BE8] DEFAULT (newid()) FOR [CustomReportLinkGUID]; GO
ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [DF__PlanEdito__Secti__372E745A] DEFAULT ((-1)) FOR [SectionID]; GO
ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [df_PlanEditorCustomReportLink_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO

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

---------------------------------------------
-- fp.PlanManagementHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[PlanManagementHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [AuthorName] nvarchar(250) NOT NULL,
    [DateTimeUTC] datetime NOT NULL,
    [SourceTimeClassID] tinyint NOT NULL,
    [IsEngineDisabled] bit NOT NULL,
    [TargetTimeClassID] tinyint NOT NULL,
    [IsMonthsLoadedIncluded] bit NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__PlanManag__IsEng__03746893] DEFAULT ((0)) FOR [IsEngineDisabled]; GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__PlanManag__Targe__2085A88D] DEFAULT ((0)) FOR [TargetTimeClassID]; GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__PlanManag__IsMon__263E81E3] DEFAULT ((0)) FOR [IsMonthsLoadedIncluded]; GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__Budge__29836C34] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__UserG__2A77906D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__Autho__2B6BB4A6] DEFAULT ('') FOR [AuthorName]; GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__DateT__2C5FD8DF] DEFAULT (getutcdate()) FOR [DateTimeUTC]; GO
ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__TimeC__727EE6BB] DEFAULT ((0)) FOR [SourceTimeClassID]; GO

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

---------------------------------------------
-- fp.PlanSection ------------------
---------------------------------------------
CREATE TABLE [fp].[PlanSection] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [PlanSectionID] int NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [SortOrder] int NOT NULL,
    [PlanSectionGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([PlanSectionID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_PlanSectionDescription] ON [fp].[PlanSection] ([Description]) INCLUDE ([PlanSectionID]);
GO
ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__Histo__3BFEE1C6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__Descr__3DE72A38] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__SortO__3EDB4E71] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__PlanS__3FCF72AA] DEFAULT (newid()) FOR [PlanSectionGUID]; GO

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

---------------------------------------------
-- fp.PlanSectionSettings ------------------
---------------------------------------------
CREATE TABLE [fp].[PlanSectionSettings] (
    [PlanSectionID] int NOT NULL,
    [AdjustmentRowLimit] int NOT NULL
);
GO
ALTER TABLE [fp].[PlanSectionSettings] ADD CONSTRAINT [FK__PlanSecti__PlanS__4BB6F1F9] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO
ALTER TABLE [fp].[PlanSectionSettings] ADD CONSTRAINT [DF__PlanSecti__PlanS__49CEA987] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[PlanSectionSettings] ADD CONSTRAINT [DF__PlanSecti__Adjus__4AC2CDC0] DEFAULT ((3000000)) FOR [AdjustmentRowLimit]; GO

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

---------------------------------------------
-- fp.PlanSubsection ------------------
---------------------------------------------
CREATE TABLE [fp].[PlanSubsection] (
    [SubsectionID] int NOT NULL,
    [PlanSectionID] int NOT NULL,
    [Subsection] varchar(100) NOT NULL,
    PRIMARY KEY ([SubsectionID])
);
GO
ALTER TABLE [fp].[PlanSubsection] ADD CONSTRAINT [FK_PlanSubsection] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO
ALTER TABLE [fp].[PlanSubsection] ADD CONSTRAINT [DF__PlanSubse__PlanS__19C9C553] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[PlanSubsection] ADD CONSTRAINT [DF__PlanSubse__Subse__1ABDE98C] DEFAULT ('') FOR [Subsection]; GO

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

---------------------------------------------
-- fp.PositionControl ------------------
---------------------------------------------
CREATE TABLE [fp].[PositionControl] (
    [PositionControlID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [CostCenter] nvarchar(200) NOT NULL,
    [PositionControlNumber] nvarchar(100) NOT NULL,
    [EmployeeID] int NOT NULL,
    [EmployeeCode] nvarchar(400) NOT NULL,
    [EmployeeName] nvarchar(800) NOT NULL,
    [JobCodeID] int NOT NULL,
    [JobStatus] nvarchar(50) NOT NULL,
    [HireDate] datetime NOT NULL,
    [BiweeklyHours] decimal NOT NULL,
    [AnnualFTE] decimal NOT NULL,
    [HourlyRates] decimal NOT NULL,
    [AnnualSalary] decimal NOT NULL
);
GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Budge__37F0BBC5] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Depar__38E4DFFE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__CostC__39D90437] DEFAULT ('') FOR [CostCenter]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Posit__3ACD2870] DEFAULT ('') FOR [PositionControlNumber]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Emplo__3BC14CA9] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Emplo__3CB570E2] DEFAULT ('') FOR [EmployeeCode]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Emplo__3DA9951B] DEFAULT ('') FOR [EmployeeName]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__JobCo__3E9DB954] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__JobSt__3F91DD8D] DEFAULT ((0)) FOR [JobStatus]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__HireD__408601C6] DEFAULT (getdate()) FOR [HireDate]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Biwee__417A25FF] DEFAULT ((0)) FOR [BiweeklyHours]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Annua__426E4A38] DEFAULT ((0)) FOR [AnnualFTE]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Hourl__43626E71] DEFAULT ((0)) FOR [HourlyRates]; GO
ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Annua__445692AA] DEFAULT ((0)) FOR [AnnualSalary]; GO

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

---------------------------------------------
-- fp.PrimaryStatisticsConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[PrimaryStatisticsConfig] (
    [RowID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [IsRevenue] bit NOT NULL,
    [IsStaffing] bit NOT NULL,
    [IsNonStaffing] bit NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[PrimaryStatisticsConfig] ADD CONSTRAINT [DF__FlexingSt__IsRev__6C2C1AB4] DEFAULT ((0)) FOR [IsRevenue]; GO
ALTER TABLE [fp].[PrimaryStatisticsConfig] ADD CONSTRAINT [DF__FlexingSt__IsSta__6D203EED] DEFAULT ((0)) FOR [IsStaffing]; GO
ALTER TABLE [fp].[PrimaryStatisticsConfig] ADD CONSTRAINT [DF__FlexingSt__IsNon__6E146326] DEFAULT ((0)) FOR [IsNonStaffing]; GO

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

---------------------------------------------
-- fp.PrimaryStatisticsConfigScoreSourceDepartments ------------------
---------------------------------------------
CREATE TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] (
    [ScoreSourceDepartmentGUID] uniqueidentifier NOT NULL,
    [PrimaryStatisticsConfigID] int NOT NULL,
    [ScoreValue] nvarchar(max) NOT NULL,
    PRIMARY KEY ([ScoreSourceDepartmentGUID])
);
GO
ALTER TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Score__194D046B] DEFAULT (newid()) FOR [ScoreSourceDepartmentGUID]; GO
ALTER TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Prima__1A4128A4] DEFAULT ((0)) FOR [PrimaryStatisticsConfigID]; GO
ALTER TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Score__1B354CDD] DEFAULT ('') FOR [ScoreValue]; GO

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

---------------------------------------------
-- fp.PrimaryStatisticsConfigSourceDepartments ------------------
---------------------------------------------
CREATE TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] (
    [SourceDepartmentGUID] uniqueidentifier NOT NULL,
    [PrimaryStatisticsConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    PRIMARY KEY ([SourceDepartmentGUID])
);
GO
ALTER TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Sourc__14884F4E] DEFAULT (newid()) FOR [SourceDepartmentGUID]; GO
ALTER TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Prima__157C7387] DEFAULT ((0)) FOR [PrimaryStatisticsConfigID]; GO
ALTER TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Depar__167097C0] DEFAULT ((0)) FOR [DepartmentID]; GO

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

---------------------------------------------
-- fp.ProvCompAddProviderAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[ProvCompAddProviderAdjustment] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [FK_FpProvCompAddProviderAdjustment_AdjustmentGuid] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[StaffingAdjustment] ([AdjustmentGUID]); GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Budge__63DA2AFB] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Adjus__64CE4F34] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Entit__65C2736D] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Depar__66B697A6] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__67AABBDF] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__689EE018] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__69930451] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__6A87288A] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__JobCo__6B7B4CC3] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__PayCo__6C6F70FC] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Produ__6D639535] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Emplo__6E57B96E] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__UnitT__6F4BDDA7] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Varia__704001E0] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__TimeC__71342619] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Budge__72284A52] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__IsRec__731C6E8B] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__741092C4] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7504B6FD] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__75F8DB36] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__76ECFF6F] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__77E123A8] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__78D547E1] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__79C96C1A] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7ABD9053] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7BB1B48C] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7CA5D8C5] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7D99FCFE] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7E8E2137] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.ProvCompAddProviderSummaryDetails ------------------
---------------------------------------------
CREATE TABLE [fp].[ProvCompAddProviderSummaryDetails] (
    [RowID] int NOT NULL,
    [SummaryID] int NOT NULL,
    [AnnualImpact] decimal NOT NULL,
    [ProjectionImpact] decimal NOT NULL,
    [BudgetImpact] decimal NOT NULL,
    [UnitTypeID] int NOT NULL,
    [TargetImpact] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [FK_FP_ProvCompAddProviderSummaryDetails_SummaryID] FOREIGN KEY ([SummaryID]) REFERENCES [fp].[StatisticAddProviderSummary] ([SummaryID]); GO
ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Summa__2D491020] DEFAULT ((0)) FOR [SummaryID]; GO
ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Annua__2E3D3459] DEFAULT ((0)) FOR [AnnualImpact]; GO
ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Proje__2F315892] DEFAULT ((0)) FOR [ProjectionImpact]; GO
ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Budge__30257CCB] DEFAULT ((0)) FOR [BudgetImpact]; GO
ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__UnitT__3119A104] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF_ProvCompAddProviderSummaryDetails_TargetImpact] DEFAULT ((0)) FOR [TargetImpact]; GO

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

---------------------------------------------
-- fp.ProviderCompensationSpreads ------------------
---------------------------------------------
CREATE TABLE [fp].[ProviderCompensationSpreads] (
    [BudgetConfigID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [IsInactive] bit NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [GlobalSpreadID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [ProviderID], [ProviderLineItemID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [UnitTypeID])
);
GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_Provider] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_ProviderLineItem] FOREIGN KEY ([ProviderLineItemID]) REFERENCES [fp].[ProviderLineItem] ([ProviderLineItemID]); GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_ProviderCompensationSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__00F3F5E8] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__01E81A21] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__02DC3E5A] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__03D06293] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__04C486CC] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__05B8AB05] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__06ACCF3E] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__07A0F377] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__089517B0] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__09893BE9] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__0A7D6022] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Total__0B71845B] DEFAULT ((0)) FOR [TotalImportedValue]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__0C65A894] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Globa__0E4DF106] DEFAULT ((1)) FOR [GlobalSpreadID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__UnitT__458AAE05] DEFAULT ((34)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Budge__748E1F03] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Provi__7582433C] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Provi__776A8BAE] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Depar__7952D420] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__JobCo__7B3B1C92] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__PayCo__7D236504] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__IsIna__7F0BAD76] DEFAULT ((0)) FOR [IsInactive]; GO
ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__7FFFD1AF] DEFAULT ((0)) FOR [SpreadPercentage01]; GO

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

---------------------------------------------
-- fp.ProviderLineItem ------------------
---------------------------------------------
CREATE TABLE [fp].[ProviderLineItem] (
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [Description] nvarchar(200) NOT NULL,
    [PlanSectionID] int NULL,
    [TransactionID] int NULL,
    [SortOrder] int NOT NULL,
    [ProviderLineItemGUID] uniqueidentifier NOT NULL,
    [MemberGUID] uniqueidentifier NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    PRIMARY KEY ([ProviderLineItemID])
);

CREATE UNIQUE NONCLUSTERED INDEX [NCU_ProviderLineItemDescription] ON [fp].[ProviderLineItem] ([Description]) INCLUDE ([ProviderLineItemID]);
GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Histo__41B7BB1C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Descr__43A0038E] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__PlanS__449427C7] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Trans__45884C00] DEFAULT ((0)) FOR [TransactionID]; GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__SortO__467C7039] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Provi__47709472] DEFAULT (newid()) FOR [ProviderLineItemGUID]; GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__PayCo__63A6B77F] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Membe__79CB02C8] DEFAULT (newid()) FOR [MemberGUID]; GO

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

---------------------------------------------
-- fp.ProviderLineItemOBForecastDetailMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[ProviderLineItemOBForecastDetailMapping] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [OBForecastDetailID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [CLU_ProviderLineItemOBForecastDetail_ndx] ON [fp].[ProviderLineItemOBForecastDetailMapping] ([BudgetConfigID], [ProviderLineItemID], [OBForecastDetailID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ProviderLineItemOBForecastDetailMapping] ([BudgetConfigID], [ProviderLineItemID], [OBForecastDetailID]);
GO
ALTER TABLE [fp].[ProviderLineItemOBForecastDetailMapping] ADD CONSTRAINT [DF__ProviderL__Budge__7352440C] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ProviderLineItemOBForecastDetailMapping] ADD CONSTRAINT [DF__ProviderL__Provi__74466845] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[ProviderLineItemOBForecastDetailMapping] ADD CONSTRAINT [DF__ProviderL__OBFor__753A8C7E] DEFAULT ((0)) FOR [OBForecastDetailID]; GO

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

---------------------------------------------
-- fp.ProviderStaffingConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[ProviderStaffingConfig] (
    [ProviderStaffingConfigID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [IsEditByProviderType] bit NOT NULL,
    [AccountID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    PRIMARY KEY ([ProviderStaffingConfigID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UC_ProviderStaffingConfig_BudgetProviderID] ON [fp].[ProviderStaffingConfig] ([BudgetConfigID], [ProviderLineItemID]);
GO
ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [FK_ProviderStaffingConfig_ProviderLineItemID] FOREIGN KEY ([ProviderLineItemID]) REFERENCES [fp].[ProviderLineItem] ([ProviderLineItemID]); GO
ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Budge__22E91B39] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Provi__23DD3F72] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__IsEdi__24D163AB] DEFAULT ((0)) FOR [IsEditByProviderType]; GO
ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Accou__25C587E4] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Varia__70E7AB51] DEFAULT ((0)) FOR [VariabilityID]; GO

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

---------------------------------------------
-- fp.ProviderStaffingConfigProviderType ------------------
---------------------------------------------
CREATE TABLE [fp].[ProviderStaffingConfigProviderType] (
    [ProviderStaffingConfigTypeID] int NOT NULL,
    [ProviderStaffingConfigID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [AccountID] int NOT NULL,
    PRIMARY KEY ([ProviderStaffingConfigTypeID])
);
GO
ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [FK_ProviderStaffConfType_AccountID] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [FK_ProviderStaffConfType_ProviderTypeID] FOREIGN KEY ([ProviderTypeID]) REFERENCES [clientdss].[DimProviderType] ([ProviderTypeID]); GO
ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [FK_ProviderStaffConfType_StaffConfigID] FOREIGN KEY ([ProviderStaffingConfigID]) REFERENCES [fp].[ProviderStaffingConfig] ([ProviderStaffingConfigID]); GO
ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [DF__ProviderS__Provi__62998BFA] DEFAULT ((0)) FOR [ProviderStaffingConfigID]; GO
ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [DF__ProviderS__Provi__638DB033] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [DF__ProviderS__Accou__6481D46C] DEFAULT ((0)) FOR [AccountID]; GO

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

---------------------------------------------
-- fp.ProviderStatisticsConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[ProviderStatisticsConfig] (
    [BudgetConfigID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [AccountID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [ProviderLineItemID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ProviderStatisticsConfig] ([BudgetConfigID], [ProviderLineItemID], [AccountID]);
GO
ALTER TABLE [fp].[ProviderStatisticsConfig] ADD CONSTRAINT [DF__ProviderS__Budge__73A41C6B] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ProviderStatisticsConfig] ADD CONSTRAINT [DF__ProviderS__Provi__749840A4] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[ProviderStatisticsConfig] ADD CONSTRAINT [DF__ProviderS__Accou__758C64DD] DEFAULT ((0)) FOR [AccountID]; GO

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

---------------------------------------------
-- fp.RefreshDatabaseStatisticsConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[RefreshDatabaseStatisticsConfiguration] (
    [SchemaName] nvarchar(2) NOT NULL,
    [TableName] nvarchar(256) NOT NULL,
    [IsActive] bit NOT NULL
);

CREATE UNIQUE NONCLUSTERED INDEX [CORE_SchemaName_TableName] ON [fp].[RefreshDatabaseStatisticsConfiguration] ([SchemaName], [TableName]);
GO
ALTER TABLE [fp].[RefreshDatabaseStatisticsConfiguration] ADD CONSTRAINT [DF__RefreshDa__Schem__296CC6ED] DEFAULT ('') FOR [SchemaName]; GO
ALTER TABLE [fp].[RefreshDatabaseStatisticsConfiguration] ADD CONSTRAINT [DF__RefreshDa__Table__2A60EB26] DEFAULT ('') FOR [TableName]; GO
ALTER TABLE [fp].[RefreshDatabaseStatisticsConfiguration] ADD CONSTRAINT [DF__RefreshDa__IsAct__2B550F5F] DEFAULT ((1)) FOR [IsActive]; GO

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

---------------------------------------------
-- fp.ReimbursementAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [AffectedDataCount] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [IsCarryForward] bit NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentID])
);
GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [FK__Reimburse__Budge__3C165264] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Budge__0FD97421] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__29037DF0] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__29F7A229] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Value__2AEBC662] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__IsCar__2BDFEA9B] DEFAULT ((0)) FOR [IsCarryForward]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__2CD40ED4] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__2DC8330D] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__2EBC5746] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Comme__2FB07B7F] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__30A49FB8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__3198C3F1] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__328CE82A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF_ReimbursementAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF_ReimbursementAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF_ReimbursementAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__IsRec__365D790E] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__DateC__37519D47] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__LastM__3845C180] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Dimen__3939E5B9] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Affec__3A2E09F2] DEFAULT ((0)) FOR [AffectedDataCount]; GO
ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__UnitT__3B222E2B] DEFAULT ((0)) FOR [UnitTypeID]; GO

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

---------------------------------------------
-- fp.ReimbursementAdjustmentChargeImport ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementAdjustmentChargeImport] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [PrimaryCPTID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value01] decimal NULL,
    [Value02] decimal NULL,
    [Value03] decimal NULL,
    [Value04] decimal NULL,
    [Value05] decimal NULL,
    [Value06] decimal NULL,
    [Value07] decimal NULL,
    [Value08] decimal NULL,
    [Value09] decimal NULL,
    [Value10] decimal NULL,
    [Value11] decimal NULL,
    [Value12] decimal NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Budge__23CB5E35] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Adjus__36928338] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Entit__3786A771] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Patie__387ACBAA] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Payor__396EEFE3] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Payor__3A63141C] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Servi__3B573855] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Servi__3C4B5C8E] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Medic__3D3F80C7] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__MSDRG__3E33A500] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Prima__3F27C939] DEFAULT ((0)) FOR [PrimaryCPTID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__UBRev__401BED72] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__UnitT__411011AB] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__TimeC__420435E4] DEFAULT ((0)) FOR [TimeClassID]; GO

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

---------------------------------------------
-- fp.ReimbursementAdjustmentEncounterImport ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementAdjustmentEncounterImport] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value01] decimal NULL,
    [Value02] decimal NULL,
    [Value03] decimal NULL,
    [Value04] decimal NULL,
    [Value05] decimal NULL,
    [Value06] decimal NULL,
    [Value07] decimal NULL,
    [Value08] decimal NULL,
    [Value09] decimal NULL,
    [Value10] decimal NULL,
    [Value11] decimal NULL,
    [Value12] decimal NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Budge__22D739FC] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Adjus__44E0A28F] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Entit__45D4C6C8] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Patie__46C8EB01] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Payor__47BD0F3A] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Payor__48B13373] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Servi__49A557AC] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Servi__4A997BE5] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Medic__4B8DA01E] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__MSDRG__4C81C457] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__CPTID__4D75E890] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__UnitT__4E6A0CC9] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__TimeC__4F5E3102] DEFAULT ((0)) FOR [TimeClassID]; GO

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

---------------------------------------------
-- fp.ReimbursementAdjustmentRate ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementAdjustmentRate] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [UBRevCodeID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_Clustered_ReimbursementAdjustmentRate] ON [fp].[ReimbursementAdjustmentRate] ([BudgetConfigID]);
GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Budge__10CD985A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Adjus__3AED2401] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Budge__3BE1483A] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Entit__3CD56C73] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Patie__3DC990AC] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Servi__3EBDB4E5] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Servi__3FB1D91E] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Medic__40A5FD57] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Payor__419A2190] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Payor__428E45C9] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__MSDRG__43826A02] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__CPTID__44768E3B] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__UBRev__456AB274] DEFAULT ((0)) FOR [UBRevCodeID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__TimeC__465ED6AD] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__UnitT__4752FAE6] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__48471F1F] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__493B4358] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4A2F6791] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4B238BCA] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4C17B003] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4D0BD43C] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4DFFF875] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4EF41CAE] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4FE840E7] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__50DC6520] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__51D08959] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__52C4AD92] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.ReimbursementChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementChangeHistory] (
    [RowID] bigint NOT NULL,
    [ReimbursementID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Reimb__5422E61F] DEFAULT ((0)) FOR [ReimbursementID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Subse__55170A58] DEFAULT ((0)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__560B2E91] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__56FF52CA] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Fisca__57F37703] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__UnitT__58E79B3C] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__TimeC__59DBBF75] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__5ACFE3AE] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__OldVa__5BC407E7] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__NewVa__5CB82C20] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__5DAC5059] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__DateC__5EA07492] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO

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

---------------------------------------------
-- fp.ReimbursementGeneralLedger ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementGeneralLedger] (
    [ReimbursementGeneralLedgerID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [BudgetLockType] tinyint NOT NULL,
    [BudgetLockFlag] tinyint NOT NULL,
    [TargetLockType] tinyint NOT NULL,
    [TargetLockFlag] tinyint NOT NULL,
    [ProjectionLockType] tinyint NOT NULL,
    [ProjectionLockFlag] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [IsNew] bit NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [TargetAdjustedTotal] decimal NOT NULL,
    [BudgetAdjustedTotal] decimal NOT NULL,
    [ProjectionAdjustedTotal] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge01] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge02] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge03] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge04] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge05] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge06] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge07] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge08] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge09] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge10] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge11] decimal NOT NULL,
    [InitialBudgetNetAsPercentOfCharge12] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge01] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge02] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge03] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge04] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge05] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge06] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge07] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge08] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge09] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge10] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge11] decimal NOT NULL,
    [InitialProjectionNetAsPercentOfCharge12] decimal NOT NULL,
    [InitialBudgetNetReimbursement01] decimal NOT NULL,
    [InitialBudgetNetReimbursement02] decimal NOT NULL,
    [InitialBudgetNetReimbursement03] decimal NOT NULL,
    [InitialBudgetNetReimbursement04] decimal NOT NULL,
    [InitialBudgetNetReimbursement05] decimal NOT NULL,
    [InitialBudgetNetReimbursement06] decimal NOT NULL,
    [InitialBudgetNetReimbursement07] decimal NOT NULL,
    [InitialBudgetNetReimbursement08] decimal NOT NULL,
    [InitialBudgetNetReimbursement09] decimal NOT NULL,
    [InitialBudgetNetReimbursement10] decimal NOT NULL,
    [InitialBudgetNetReimbursement11] decimal NOT NULL,
    [InitialBudgetNetReimbursement12] decimal NOT NULL,
    [InitialProjectionNetReimbursement01] decimal NOT NULL,
    [InitialProjectionNetReimbursement02] decimal NOT NULL,
    [InitialProjectionNetReimbursement03] decimal NOT NULL,
    [InitialProjectionNetReimbursement04] decimal NOT NULL,
    [InitialProjectionNetReimbursement05] decimal NOT NULL,
    [InitialProjectionNetReimbursement06] decimal NOT NULL,
    [InitialProjectionNetReimbursement07] decimal NOT NULL,
    [InitialProjectionNetReimbursement08] decimal NOT NULL,
    [InitialProjectionNetReimbursement09] decimal NOT NULL,
    [InitialProjectionNetReimbursement10] decimal NOT NULL,
    [InitialProjectionNetReimbursement11] decimal NOT NULL,
    [InitialProjectionNetReimbursement12] decimal NOT NULL,
    [TargetAdjusted01] decimal NOT NULL,
    [TargetAdjusted02] decimal NOT NULL,
    [TargetAdjusted03] decimal NOT NULL,
    [TargetAdjusted04] decimal NOT NULL,
    [TargetAdjusted05] decimal NOT NULL,
    [TargetAdjusted06] decimal NOT NULL,
    [TargetAdjusted07] decimal NOT NULL,
    [TargetAdjusted08] decimal NOT NULL,
    [TargetAdjusted09] decimal NOT NULL,
    [TargetAdjusted10] decimal NOT NULL,
    [TargetAdjusted11] decimal NOT NULL,
    [TargetAdjusted12] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge01] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge02] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge03] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge04] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge05] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge06] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge07] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge08] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge09] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge10] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge11] decimal NOT NULL,
    [TargetAdjustedNetAsPercentOfCharge12] decimal NOT NULL,
    [TargetAdjustedNetReimbursement01] decimal NOT NULL,
    [TargetAdjustedNetReimbursement02] decimal NOT NULL,
    [TargetAdjustedNetReimbursement03] decimal NOT NULL,
    [TargetAdjustedNetReimbursement04] decimal NOT NULL,
    [TargetAdjustedNetReimbursement05] decimal NOT NULL,
    [TargetAdjustedNetReimbursement06] decimal NOT NULL,
    [TargetAdjustedNetReimbursement07] decimal NOT NULL,
    [TargetAdjustedNetReimbursement08] decimal NOT NULL,
    [TargetAdjustedNetReimbursement09] decimal NOT NULL,
    [TargetAdjustedNetReimbursement10] decimal NOT NULL,
    [TargetAdjustedNetReimbursement11] decimal NOT NULL,
    [TargetAdjustedNetReimbursement12] decimal NOT NULL,
    [BudgetAdjusted01] decimal NOT NULL,
    [BudgetAdjusted02] decimal NOT NULL,
    [BudgetAdjusted03] decimal NOT NULL,
    [BudgetAdjusted04] decimal NOT NULL,
    [BudgetAdjusted05] decimal NOT NULL,
    [BudgetAdjusted06] decimal NOT NULL,
    [BudgetAdjusted07] decimal NOT NULL,
    [BudgetAdjusted08] decimal NOT NULL,
    [BudgetAdjusted09] decimal NOT NULL,
    [BudgetAdjusted10] decimal NOT NULL,
    [BudgetAdjusted11] decimal NOT NULL,
    [BudgetAdjusted12] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge01] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge02] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge03] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge04] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge05] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge06] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge07] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge08] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge09] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge10] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge11] decimal NOT NULL,
    [BudgetAdjustedNetAsPercentOfCharge12] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement01] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement02] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement03] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement04] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement05] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement06] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement07] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement08] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement09] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement10] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement11] decimal NOT NULL,
    [BudgetAdjustedNetReimbursement12] decimal NOT NULL,
    [ProjectionAdjusted01] decimal NOT NULL,
    [ProjectionAdjusted02] decimal NOT NULL,
    [ProjectionAdjusted03] decimal NOT NULL,
    [ProjectionAdjusted04] decimal NOT NULL,
    [ProjectionAdjusted05] decimal NOT NULL,
    [ProjectionAdjusted06] decimal NOT NULL,
    [ProjectionAdjusted07] decimal NOT NULL,
    [ProjectionAdjusted08] decimal NOT NULL,
    [ProjectionAdjusted09] decimal NOT NULL,
    [ProjectionAdjusted10] decimal NOT NULL,
    [ProjectionAdjusted11] decimal NOT NULL,
    [ProjectionAdjusted12] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge01] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge02] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge03] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge04] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge05] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge06] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge07] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge08] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge09] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge10] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge11] decimal NOT NULL,
    [ProjectionAdjustedNetAsPercentOfCharge12] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement01] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement02] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement03] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement04] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement05] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement06] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement07] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement08] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement09] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement10] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement11] decimal NOT NULL,
    [ProjectionAdjustedNetReimbursement12] decimal NOT NULL,
    PRIMARY KEY ([ReimbursementGeneralLedgerID])
);
GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [FK_ReimbursementGeneralLedger_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [FK_ReimbursementGeneralLedger_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [FK_ReimbursementGeneralLedger_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__00CC3ABB] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__01C05EF4] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__02B4832D] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__03A8A766] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__049CCB9F] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0590EFD8] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__06851411] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0779384A] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__086D5C83] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__096180BC] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0A55A4F5] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0B49C92E] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0C3DED67] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0D3211A0] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__0E2635D9] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__0F1A5A12] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__100E7E4B] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1102A284] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__11F6C6BD] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__12EAEAF6] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__13DF0F2F] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__14D33368] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__15C757A1] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__16BB7BDA] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__17AFA013] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__18A3C44C] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1997E885] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1A8C0CBE] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1B8030F7] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1C745530] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1D687969] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1E5C9DA2] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1F50C1DB] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__2044E614] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__21390A4D] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__222D2E86] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__232152BF] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__241576F8] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__2632C994] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Entit__2726EDCD] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Entit__281B1206] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Payor__290F363F] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Patie__2A035A78] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__2AF77EB1] DEFAULT ((0)) FOR [BudgetLockType]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__2BEBA2EA] DEFAULT ((0)) FOR [BudgetLockFlag]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__2CDFC723] DEFAULT ((0)) FOR [TargetLockType]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__2DD3EB5C] DEFAULT ((0)) FOR [TargetLockFlag]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__2EC80F95] DEFAULT ((0)) FOR [ProjectionLockType]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__2FBC33CE] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__AddDa__30B05807] DEFAULT ('2800-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__IsNew__31A47C40] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3298A079] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__338CC4B2] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3480E8EB] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__35750D24] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3669315D] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__375D5596] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__385179CF] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__39459E08] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3A39C241] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3B2DE67A] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3C220AB3] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3D162EEC] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3E0A5325] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3EFE775E] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3FF29B97] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__40E6BFD0] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__41DAE409] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__42CF0842] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__43C32C7B] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__44B750B4] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__45AB74ED] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__469F9926] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4793BD5F] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4887E198] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__497C05D1] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4A702A0A] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4B644E43] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4C58727C] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4D4C96B5] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4E40BAEE] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4F34DF27] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__50290360] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__511D2799] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__52114BD2] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5305700B] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__53F99444] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__54EDB87D] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__55E1DCB6] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__56D600EF] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__57CA2528] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__58BE4961] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__59B26D9A] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5AA691D3] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5B9AB60C] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5C8EDA45] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5D82FE7E] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5E7722B7] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5F6B46F0] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__605F6B29] DEFAULT ((0)) FOR [TargetAdjusted01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__61538F62] DEFAULT ((0)) FOR [TargetAdjusted02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6247B39B] DEFAULT ((0)) FOR [TargetAdjusted03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__633BD7D4] DEFAULT ((0)) FOR [TargetAdjusted04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__642FFC0D] DEFAULT ((0)) FOR [TargetAdjusted05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__65242046] DEFAULT ((0)) FOR [TargetAdjusted06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6618447F] DEFAULT ((0)) FOR [TargetAdjusted07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__670C68B8] DEFAULT ((0)) FOR [TargetAdjusted08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__68008CF1] DEFAULT ((0)) FOR [TargetAdjusted09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__68F4B12A] DEFAULT ((0)) FOR [TargetAdjusted10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__69E8D563] DEFAULT ((0)) FOR [TargetAdjusted11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6ADCF99C] DEFAULT ((0)) FOR [TargetAdjusted12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6BD11DD5] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6CC5420E] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6DB96647] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6EAD8A80] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6FA1AEB9] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__7095D2F2] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__7189F72B] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__727E1B64] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__73723F9D] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__746663D6] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__755A880F] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__764EAC48] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7742D081] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7836F4BA] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__792B18F3] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7A1F3D2C] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7B136165] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7C07859E] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7CFBA9D7] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7DEFCE10] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7EE3F249] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7FD81682] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO

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

---------------------------------------------
-- fp.ReimbursementGeneralLedgerAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementGeneralLedgerAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [IsCarryForward] bit NOT NULL,
    [AffectedDataCount] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [IsErrored] bit NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentID])
);
GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [FK__Reimburse__Budge__5D4DF454] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_UnitTypeID] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4946FBA7] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4A3B1FE0] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Value__4B2F4419] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__IsCar__4C236852] DEFAULT ((0)) FOR [IsCarryForward]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4D178C8B] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__4E0BB0C4] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4EFFD4FD] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Comme__4FF3F936] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__50E81D6F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__51DC41A8] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__52D065E1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__IsRec__57951AFE] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__DateC__58893F37] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__LastM__597D6370] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Dimen__5A7187A9] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Affec__5B65ABE2] DEFAULT ((0)) FOR [AffectedDataCount]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__IsErr__5C59D01B] DEFAULT ((0)) FOR [IsErrored]; GO

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

---------------------------------------------
-- fp.ReimbursementGeneralLedgerAdjustmentImport ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [Value01] decimal NULL,
    [Value02] decimal NULL,
    [Value03] decimal NULL,
    [Value04] decimal NULL,
    [Value05] decimal NULL,
    [Value06] decimal NULL,
    [Value07] decimal NULL,
    [Value08] decimal NULL,
    [Value09] decimal NULL,
    [Value10] decimal NULL,
    [Value11] decimal NULL,
    [Value12] decimal NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Adjus__602A60FF] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Entit__611E8538] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Payor__6212A971] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Patie__6306CDAA] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__TimeC__63FAF1E3] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Budge__64EF161C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO

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

---------------------------------------------
-- fp.ReimbursementGeneralLedgerAdjustmentRate ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_Clustered_ReimbursementGeneralLedgerAdjustmentRate] ON [fp].[ReimbursementGeneralLedgerAdjustmentRate] ([BudgetConfigID]);
GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Patie__00780057] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__TimeC__016C2490] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__UnitT__026048C9] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__03546D02] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0448913B] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__053CB574] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0630D9AD] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0724FDE6] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0819221F] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__090D4658] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0A016A91] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0AF58ECA] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0BE9B303] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0CDDD73C] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0DD1FB75] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [df_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Adjus__7CA76F73] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Budge__7D9B93AC] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Entit__7E8FB7E5] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Payor__7F83DC1E] DEFAULT ((0)) FOR [PayorGroupID]; GO

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

---------------------------------------------
-- fp.ReimbursementGeneralLedgerChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] (
    [RowID] bigint NOT NULL,
    [ReimbursementGeneralLedgerID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Reimb__6AA7EF72] DEFAULT ((0)) FOR [ReimbursementGeneralLedgerID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__6B9C13AB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__6C9037E4] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Fisca__6D845C1D] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__UnitT__6E788056] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__TimeC__6F6CA48F] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__7060C8C8] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__OldVa__7154ED01] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__NewVa__7249113A] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__733D3573] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__DateC__743159AC] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO

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

---------------------------------------------
-- fp.ReimbursementGeneralLedgerHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementGeneralLedgerHistory] (
    [RowID] int NOT NULL,
    [ReimbursementGeneralLedgerID] int NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge01] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge02] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge03] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge04] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge05] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge06] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge07] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge08] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge09] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge10] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge11] decimal NOT NULL,
    [PriorYearActualValueNetAsPercentOfCharge12] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement01] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement02] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement03] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement04] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement05] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement06] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement07] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement08] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement09] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement10] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement11] decimal NOT NULL,
    [PriorYearActualValueNetReimbursement12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [FK_ReimbursementGeneralLedgerHistory_ReimbursementGeneralLedgerID] FOREIGN KEY ([ReimbursementGeneralLedgerID]) REFERENCES [fp].[ReimbursementGeneralLedger] ([ReimbursementGeneralLedgerID]); GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Reimb__29CE504E] DEFAULT ((0)) FOR [ReimbursementGeneralLedgerID]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2AC27487] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2BB698C0] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2CAABCF9] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2D9EE132] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2E93056B] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2F8729A4] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__307B4DDD] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__316F7216] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3263964F] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3357BA88] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__344BDEC1] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__354002FA] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__36342733] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge01]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__37284B6C] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge02]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__381C6FA5] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge03]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__391093DE] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge04]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3A04B817] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge05]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3AF8DC50] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge06]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3BED0089] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge07]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3CE124C2] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge08]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3DD548FB] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge09]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3EC96D34] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge10]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3FBD916D] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge11]; GO
ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__40B1B5A6] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge12]; GO

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

---------------------------------------------
-- fp.ReimbursementImportLog ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementImportLog] (
    [FileAttachmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [FileName] nvarchar(250) NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [UserName] nvarchar(64) NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [FileData] varbinary(max) NOT NULL,
    PRIMARY KEY ([FileAttachmentGUID])
);
GO
ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__FileN__00D59105] DEFAULT ('') FOR [FileName]; GO
ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__UserG__01C9B53E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO
ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__UserN__02BDD977] DEFAULT ('') FOR [UserName]; GO
ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__DateC__03B1FDB0] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__FileA__7EED4893] DEFAULT (newid()) FOR [FileAttachmentGUID]; GO
ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__Budge__7FE16CCC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO

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

---------------------------------------------
-- fp.ReimbursementNetRevenueModel ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementNetRevenueModel] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [NetRevenueModelID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [FK_ReimbursementNetRevenueModel_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [FK_ReimbursementNetRevenueModel_EntityID] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [DF__Reimburse__Budge__1ACCCF37] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [DF__Reimburse__Entit__1BC0F370] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [DF__Reimburse__NetRe__1CB517A9] DEFAULT ((0)) FOR [NetRevenueModelID]; GO

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

---------------------------------------------
-- fp.ReimbursementProjectionMethod ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementProjectionMethod] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [PayorGroupID] int NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [FK_ReimbursementProjectionMethod_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [FK_ReimbursementProjectionMethod_PayorGroupID] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [DF__Reimburse__Budge__3BB5945A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [DF__Reimburse__Payor__3CA9B893] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [DF__Reimburse__Proje__3D9DDCCC] DEFAULT ((0)) FOR [ProjectionMethodID]; GO

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

---------------------------------------------
-- fp.ReimbursementToGeneralLedgerCrosswalkConfiguration ------------------
---------------------------------------------
CREATE TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [PayorGroupID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [AccountID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ProjectionAllocationPercent] decimal NOT NULL,
    [BudgetAllocationPercent] decimal NOT NULL,
    [EntityID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Entit__23F4B010] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Budge__62710576] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Payor__636529AF] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Patie__64594DE8] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Accou__654D7221] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Depar__6641965A] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Proje__6735BA93] DEFAULT ((1)) FOR [ProjectionAllocationPercent]; GO
ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Budge__6829DECC] DEFAULT ((1)) FOR [BudgetAllocationPercent]; GO

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

---------------------------------------------
-- fp.RevenueExpenseFlexingConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[RevenueExpenseFlexingConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID])
);
GO
ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [FK__RevenueEx__Depar__3FCD10A5] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [DF__RevenueEx__Depar__26EDB926] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [df_RevenueExpenseFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [DF__RevenueEx__FlexM__27E1DD5F] DEFAULT ((0)) FOR [FlexMethodID]; GO

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

---------------------------------------------
-- fp.RevenueFlexingOverrideConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[RevenueFlexingOverrideConfig] (
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    PRIMARY KEY ([OverrideFlexConfigGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [Unique_RevenueFlexingOverrideConfig_EC_Dept_Account] ON [fp].[RevenueFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]);
GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [FK__RevenueFl__Accou__439DA189] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [FK__RevenueFl__Depar__42A97D50] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [df_RevenueFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__Overr__2BB26E43] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__Depar__2D9AB6B5] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__Accou__2E8EDAEE] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__FlexM__2F82FF27] DEFAULT ((0)) FOR [FlexMethodID]; GO

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

---------------------------------------------
-- fp.RevenueFlexingOverrideConfigAssignment ------------------
---------------------------------------------
CREATE TABLE [fp].[RevenueFlexingOverrideConfigAssignment] (
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    [AccountID] int NOT NULL,
    PRIMARY KEY ([OverrideFlexConfigGUID], [AccountID])
);
GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfigAssignment] ADD CONSTRAINT [FK_RevenueFlexingOverrideConfig_OverrideFlexConfigGUID] FOREIGN KEY ([OverrideFlexConfigGUID]) REFERENCES [fp].[RevenueFlexingOverrideConfig] ([OverrideFlexConfigGUID]); GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__RevenueFl__Overr__325F6BD2] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO
ALTER TABLE [fp].[RevenueFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__RevenueFl__Accou__3353900B] DEFAULT ((0)) FOR [AccountID]; GO

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

---------------------------------------------
-- fp.RosterBudgetBasis ------------------
---------------------------------------------
CREATE TABLE [fp].[RosterBudgetBasis] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [InitialDollars] decimal NOT NULL,
    [Dollars] decimal NOT NULL,
    [FTEs] decimal NOT NULL,
    [InitialFTEs] decimal NOT NULL,
    [ProjectedDollars] decimal NOT NULL,
    [ProjectedFTEs] decimal NOT NULL,
    [EmployeeID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    [ActualYTDDollars] decimal NOT NULL,
    [ActualYTDFTEs] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_RosterBudgetBasis] ON [fp].[RosterBudgetBasis] ([BudgetConfigGUID], [EmployeeID], [JobCodeID]);
GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [df_RosterBudgetBasis_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Actua__61B0EE46] DEFAULT ((0)) FOR [ActualYTDDollars]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Actua__639936B8] DEFAULT ((0)) FOR [ActualYTDFTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Emplo__6FAA07E2] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__JobCo__709E2C1B] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Histo__71925054] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_InitialFTEs] DEFAULT ((0)) FOR [InitialFTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_FTEs] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_ProjectedFTEs] DEFAULT ((0)) FOR [ProjectedFTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_InitialDollars] DEFAULT ((0)) FOR [InitialDollars]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_Dollars] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_ProjectedDollars] DEFAULT ((0)) FOR [ProjectedDollars]; GO

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

---------------------------------------------
-- fp.RosterBudgetBasisHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[RosterBudgetBasisHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [UserGuid] uniqueidentifier NOT NULL,
    [Date] datetime NOT NULL,
    [FTEs] decimal NOT NULL,
    [DollarType] varchar(100) NULL,
    [OriginalDollars] decimal NOT NULL,
    [FinalDollars] decimal NOT NULL,
    [HistoryItemGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Histo__03B1008F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [Default_RosterBasisHist_FTEs] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__UserG__0CE16C5B] DEFAULT (newid()) FOR [UserGuid]; GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBudg__Date__0DD59094] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [df_RosterBudgetBasisHistory_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Dolla__5428DD43] DEFAULT ('Budget') FOR [DollarType]; GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Origi__5488CFF6] DEFAULT ((0)) FOR [OriginalDollars]; GO
ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Final__557CF42F] DEFAULT ((0)) FOR [FinalDollars]; GO

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

---------------------------------------------
-- fp.RosterBudgetBasisResult ------------------
---------------------------------------------
CREATE TABLE [fp].[RosterBudgetBasisResult] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [Dollars] decimal NOT NULL,
    [InitialDollars] decimal NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [FTEs] decimal NOT NULL,
    [ProjectedDollars] decimal NOT NULL,
    [ProjectedFTEs] decimal NOT NULL,
    [EmployeeID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ActualYTDDollars] decimal NOT NULL,
    [ActualYTDFTEs] decimal NOT NULL,
    [InitialFTEs] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_RosterBudgetBasisResult] ON [fp].[RosterBudgetBasisResult] ([BudgetConfigGUID], [EmployeeID], [JobCodeID], [DepartmentID], [PayCodeGroupID]);
GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_Dollars] DEFAULT ((0)) FOR [Dollars]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_ProjectedDollars] DEFAULT ((0)) FOR [ProjectedDollars]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [df_RosterBudgetBasisResult_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Actua__60BCCA0D] DEFAULT ((0)) FOR [ActualYTDDollars]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Actua__62A5127F] DEFAULT ((0)) FOR [ActualYTDFTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Comme__6A0D316A] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Initi__73308003] DEFAULT ((0.0)) FOR [InitialFTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Emplo__7933721C] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__JobCo__7A279655] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Depar__7B1BBA8E] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__PayCo__7C0FDEC7] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_FTEs] DEFAULT ((0)) FOR [FTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_ProjectedFTEs] DEFAULT ((0)) FOR [ProjectedFTEs]; GO
ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_InitialDollars] DEFAULT ((0)) FOR [InitialDollars]; GO

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

---------------------------------------------
-- fp.RosterBudgetBasisResultHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[RosterBudgetBasisResultHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [UserGuid] uniqueidentifier NOT NULL,
    [Date] datetime NOT NULL,
    [DollarType] varchar(100) NULL,
    [OriginalDollars] decimal NOT NULL,
    [FinalDollars] decimal NOT NULL,
    [EmployeeID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Emplo__0969D9E5] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__JobCo__0A5DFE1E] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Depar__0B522257] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__UserG__175EFACE] DEFAULT (newid()) FOR [UserGuid]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBudg__Date__18531F07] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [df_RosterBudgetBasisResultHistory_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Dolla__551D017C] DEFAULT ('Budget') FOR [DollarType]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Origi__56711868] DEFAULT ((0)) FOR [OriginalDollars]; GO
ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Final__57653CA1] DEFAULT ((0)) FOR [FinalDollars]; GO

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

---------------------------------------------
-- fp.RosterBudgetHoursMix ------------------
---------------------------------------------
CREATE TABLE [fp].[RosterBudgetHoursMix] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [Value] decimal NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[RosterBudgetHoursMix] ADD CONSTRAINT [df_RosterBudgetHoursMix_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[RosterBudgetHoursMix] ADD CONSTRAINT [DF__RosterBud__Value__6063CB9F] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[RosterBudgetHoursMix] ADD CONSTRAINT [DF__RosterBud__PayCo__66209DA8] DEFAULT ((0)) FOR [PayCodeGroupID]; GO

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

---------------------------------------------
-- fp.RosterBudgetNewEmployee ------------------
---------------------------------------------
CREATE TABLE [fp].[RosterBudgetNewEmployee] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [EmployeeNumber] nvarchar(400) NOT NULL,
    [FiscalYearID] smallint NULL,
    [EmployeeID] int NOT NULL,
    [PositionNumber] nvarchar(100) NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_RosterBudgetNewEmployee] ON [fp].[RosterBudgetNewEmployee] ([BudgetConfigGUID], [EmployeeID]);
GO
ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Fisca__37C1A8BF] DEFAULT (datepart(year,getdate())) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [df_RosterBudgetNewEmployee_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Emplo__663CA086] DEFAULT ('') FOR [EmployeeNumber]; GO
ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Emplo__6808E61A] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Posit__754DD29F] DEFAULT ('') FOR [PositionNumber]; GO
ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Fisca__7A239DA2] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Comme__7B17C1DB] DEFAULT ('') FOR [Comment]; GO

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

---------------------------------------------
-- fp.RosterBudgetRequest ------------------
---------------------------------------------
CREATE TABLE [fp].[RosterBudgetRequest] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [UserGuid] uniqueidentifier NOT NULL,
    [Status] tinyint NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [Date] datetime NOT NULL,
    [Dollars] decimal NOT NULL,
    [DollarType] varchar(100) NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__UserG__20E86508] DEFAULT (newid()) FOR [UserGuid]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Statu__21DC8941] DEFAULT ((0)) FOR [Status]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Comme__22D0AD7A] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBudg__Date__23C4D1B3] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [df_RosterBudgetRequest_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Dolla__5334B90A] DEFAULT ('Budget') FOR [DollarType]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__JobCo__69F12E8C] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__PayCo__6AE552C5] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Depar__6BD976FE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Emplo__6CCD9B37] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [Default_RosterBasisReq_Dollars] DEFAULT ((0)) FOR [Dollars]; GO

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

---------------------------------------------
-- fp.SamplingLog ------------------
---------------------------------------------
CREATE TABLE [fp].[SamplingLog] (
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [PlanSectionID] int NOT NULL,
    [PlanSectionDescription] nvarchar(300) NOT NULL,
    [SourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [DateStartedUTC] datetime NOT NULL,
    [DateEndedUTC] datetime NOT NULL,
    [IsInitialPlanMethod] bit NOT NULL,
    [IsDSSampling] bit NOT NULL,
    [NumberOfRecordsSampled] int NOT NULL,
    [JazzVersion] nvarchar(10) NOT NULL
);
GO
ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__Sourc__11220488] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO
ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__DateS__121628C1] DEFAULT ('1900-01-01T00:00:00') FOR [DateStartedUTC]; GO
ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__DateE__130A4CFA] DEFAULT ('1900-01-01T00:00:00') FOR [DateEndedUTC]; GO
ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__IsIni__13FE7133] DEFAULT ((0)) FOR [IsInitialPlanMethod]; GO
ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__IsDSS__14F2956C] DEFAULT ((0)) FOR [IsDSSampling]; GO
ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__Numbe__15E6B9A5] DEFAULT ((0)) FOR [NumberOfRecordsSampled]; GO
ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__JazzV__52BABDBB] DEFAULT ('') FOR [JazzVersion]; GO

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

---------------------------------------------
-- fp.ScheduledRefreshRequest ------------------
---------------------------------------------
CREATE TABLE [fp].[ScheduledRefreshRequest] (
    [RequestGUID] uniqueidentifier NOT NULL,
    [SourceDimensionalityJSON] nvarchar(max) NOT NULL,
    [SourceActionID] smallint NOT NULL,
    [IsIgnoreTargetingError] bit NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [SamplingJSON] nvarchar(max) NOT NULL,
    [SortOrder] int NOT NULL,
    [IsActive] bit NOT NULL,
    PRIMARY KEY ([RequestGUID])
);
GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Reque__394270AC] DEFAULT (newid()) FOR [RequestGUID]; GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Sourc__3A3694E5] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Sourc__3B2AB91E] DEFAULT ((0)) FOR [SourceActionID]; GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__IsIgn__3C1EDD57] DEFAULT ((0)) FOR [IsIgnoreTargetingError]; GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Entit__3D130190] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__SortO__3EFB4A02] DEFAULT ((0)) FOR [SortOrder]; GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__IsAct__3FEF6E3B] DEFAULT ((0)) FOR [IsActive]; GO
ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [df_SamplingJSON] DEFAULT ('') FOR [SamplingJSON]; GO

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

---------------------------------------------
-- fp.SectionSetup ------------------
---------------------------------------------
CREATE TABLE [fp].[SectionSetup] (
    [SectionSetupGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [PlanSectionID] int NOT NULL,
    [SubSectionID] int NOT NULL,
    [LevelID] varchar(50) NOT NULL,
    [IsHidden] bit NOT NULL,
    PRIMARY KEY ([SectionSetupGUID])
);
GO
ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [FK__SectionSe__Budge__0FD646C5] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [FK__SectionSe__PlanS__10CA6AFE] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO
ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [FK__SectionSe__SubSe__11BE8F37] FOREIGN KEY ([SubSectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO
ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__PlanS__0C05B5E1] DEFAULT ((0)) FOR [PlanSectionID]; GO
ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__SubSe__0CF9DA1A] DEFAULT ((0)) FOR [SubSectionID]; GO
ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__Level__0DEDFE53] DEFAULT ('') FOR [LevelID]; GO
ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__IsHid__0EE2228C] DEFAULT ((0)) FOR [IsHidden]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounter ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounter] (
    [ServiceLineEncounterID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [AddDate] datetime NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [TargetAdjustedTotal] decimal NOT NULL,
    [BudgetAdjustedTotal] decimal NOT NULL,
    [ProjectionAdjustedTotal] decimal NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [TargetAdjusted01] decimal NOT NULL,
    [TargetAdjusted02] decimal NOT NULL,
    [TargetAdjusted03] decimal NOT NULL,
    [TargetAdjusted04] decimal NOT NULL,
    [TargetAdjusted05] decimal NOT NULL,
    [TargetAdjusted06] decimal NOT NULL,
    [TargetAdjusted07] decimal NOT NULL,
    [TargetAdjusted08] decimal NOT NULL,
    [TargetAdjusted09] decimal NOT NULL,
    [TargetAdjusted10] decimal NOT NULL,
    [TargetAdjusted11] decimal NOT NULL,
    [TargetAdjusted12] decimal NOT NULL,
    [BudgetAdjusted01] decimal NOT NULL,
    [BudgetAdjusted02] decimal NOT NULL,
    [BudgetAdjusted03] decimal NOT NULL,
    [BudgetAdjusted04] decimal NOT NULL,
    [BudgetAdjusted05] decimal NOT NULL,
    [BudgetAdjusted06] decimal NOT NULL,
    [BudgetAdjusted07] decimal NOT NULL,
    [BudgetAdjusted08] decimal NOT NULL,
    [BudgetAdjusted09] decimal NOT NULL,
    [BudgetAdjusted10] decimal NOT NULL,
    [BudgetAdjusted11] decimal NOT NULL,
    [BudgetAdjusted12] decimal NOT NULL,
    [ProjectionAdjusted01] decimal NOT NULL,
    [ProjectionAdjusted02] decimal NOT NULL,
    [ProjectionAdjusted03] decimal NOT NULL,
    [ProjectionAdjusted04] decimal NOT NULL,
    [ProjectionAdjusted05] decimal NOT NULL,
    [ProjectionAdjusted06] decimal NOT NULL,
    [ProjectionAdjusted07] decimal NOT NULL,
    [ProjectionAdjusted08] decimal NOT NULL,
    [ProjectionAdjusted09] decimal NOT NULL,
    [ProjectionAdjusted10] decimal NOT NULL,
    [ProjectionAdjusted11] decimal NOT NULL,
    [ProjectionAdjusted12] decimal NOT NULL,
    [IsNew] bit NOT NULL,
    [BudgetLockType] tinyint NOT NULL,
    [BudgetLockFlag] tinyint NOT NULL,
    [TargetLockType] tinyint NOT NULL,
    [TargetLockFlag] tinyint NOT NULL,
    [ProjectionLockType] tinyint NOT NULL,
    [ProjectionLockFlag] tinyint NOT NULL,
    PRIMARY KEY ([ServiceLineEncounterID])
);

CREATE CLUSTERED INDEX [IX_ServiceLineEncounter_Clustered] ON [fp].[ServiceLineEncounter] ([BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineRollupID], [ServiceLineID]);
CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_BudgetConfig] ON [fp].[ServiceLineEncounter] ([BudgetConfigID]) INCLUDE ([ServiceLineEncounterID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_Department] ON [fp].[ServiceLineEncounter] ([DepartmentID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_Entity] ON [fp].[ServiceLineEncounter] ([EntityID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_EntityGroupConfig] ON [fp].[ServiceLineEncounter] ([EntityGroupConfigID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_ServiceLine] ON [fp].[ServiceLineEncounter] ([ServiceLineID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ServiceLineEncounterUnique] ON [fp].[ServiceLineEncounter] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]);
GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__00A15232] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0195766B] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__02899AA4] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__037DBEDD] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0471E316] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0566074F] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__065A2B88] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__074E4FC1] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__084273FA] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__09369833] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0A2ABC6C] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0B1EE0A5] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0C1304DE] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0D072917] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__0DFB4D50] DEFAULT ((0)) FOR [TargetAdjusted01]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__0EEF7189] DEFAULT ((0)) FOR [TargetAdjusted02]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__0FE395C2] DEFAULT ((0)) FOR [TargetAdjusted03]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__10D7B9FB] DEFAULT ((0)) FOR [TargetAdjusted04]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__11CBDE34] DEFAULT ((0)) FOR [TargetAdjusted05]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__12C0026D] DEFAULT ((0)) FOR [TargetAdjusted06]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__13B426A6] DEFAULT ((0)) FOR [TargetAdjusted07]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__14A84ADF] DEFAULT ((0)) FOR [TargetAdjusted08]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__159C6F18] DEFAULT ((0)) FOR [TargetAdjusted09]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__16909351] DEFAULT ((0)) FOR [TargetAdjusted10]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__1784B78A] DEFAULT ((0)) FOR [TargetAdjusted11]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__1878DBC3] DEFAULT ((0)) FOR [TargetAdjusted12]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__196CFFFC] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1A612435] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1B55486E] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1C496CA7] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1D3D90E0] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1E31B519] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1F25D952] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__2019FD8B] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__210E21C4] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__220245FD] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__22F66A36] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__23EA8E6F] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__24DEB2A8] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__25D2D6E1] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__26C6FB1A] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__27BB1F53] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__28AF438C] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__29A367C5] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2A978BFE] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2B8BB037] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2C7FD470] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2D73F8A9] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2E681CE2] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2F5C411B] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__IsNew__30506554] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__3144898D] DEFAULT ((0)) FOR [BudgetLockType]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__3238ADC6] DEFAULT ((0)) FOR [BudgetLockFlag]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__332CD1FF] DEFAULT ((0)) FOR [TargetLockType]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__3420F638] DEFAULT ((0)) FOR [TargetLockFlag]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__35151A71] DEFAULT ((0)) FOR [ProjectionLockType]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__36093EAA] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__4FFE1AD7] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Entit__50F23F10] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Entit__51E66349] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Patie__52DA8782] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Servi__53CEABBB] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Servi__54C2CFF4] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__AgeCo__55B6F42D] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Medic__56AB1866] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Depar__579F3C9F] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Payor__589360D8] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Payor__59878511] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__MSDRG__5A7BA94A] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__CPTID__5B6FCD83] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Provi__5C63F1BC] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Physi__5D5815F5] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__UnitT__5E4C3A2E] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__AddDa__5F405E67] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__603482A0] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6128A6D9] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__621CCB12] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6310EF4B] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__64051384] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__64F937BD] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__65ED5BF6] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__66E1802F] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__67D5A468] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__68C9C8A1] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__69BDECDA] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6AB21113] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6BA6354C] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6C9A5985] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6D8E7DBE] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6E82A1F7] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6F76C630] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__706AEA69] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__715F0EA2] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__725332DB] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__73475714] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__743B7B4D] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__752F9F86] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__7623C3BF] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7717E7F8] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__780C0C31] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7900306A] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__79F454A3] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7AE878DC] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7BDC9D15] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7CD0C14E] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7DC4E587] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7EB909C0] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7FAD2DF9] DEFAULT ((0)) FOR [InitialBudget10]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterAddProviderAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [CLU_SLEAddProvider] ON [fp].[ServiceLineEncounterAddProviderAdjustment] ([BudgetConfigID], [DepartmentID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ServiceLineEncounterAddProviderAdjustment] ([BudgetConfigID], [AdjustmentGUID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [TimeClassID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Budge__1C3B5253] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__1D2F768C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Entit__1E239AC5] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Patie__1F17BEFE] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Servi__200BE337] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Servi__21000770] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__AgeCo__21F42BA9] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Medic__22E84FE2] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Depar__23DC741B] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Payor__24D09854] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Payor__25C4BC8D] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__MSDRG__26B8E0C6] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__CPTID__27AD04FF] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Provi__28A12938] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Physi__29954D71] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__TimeC__2A8971AA] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Budge__2B7D95E3] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__IsRec__2C71BA1C] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__2D65DE55] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__2E5A028E] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__2F4E26C7] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__30424B00] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__31366F39] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__322A9372] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__331EB7AB] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__3412DBE4] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__3507001D] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__35FB2456] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__36EF488F] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__37E36CC8] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [AdjustmentID] int NOT NULL,
    [IsErrored] bit NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [FK__ServiceLi__Budge__5AD44424] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [df_AdjustedProperty] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__TimeC__1715DF2C] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Budge__180A0365] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF_ServiceLineEncounterAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF_ServiceLineEncounterAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__IsErr__49112626] DEFAULT ((0)) FOR [IsErrored]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Group__502C987F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__59E01FEB] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__5BC8685D] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__5CBC8C96] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__5DB0B0CF] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Group__5EA4D508] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Comme__608D1D7A] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Dimen__61057DEC] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Autho__618141B3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Autho__627565EC] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__DateC__6BED20B3] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__LastM__6CE144EC] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__IsRec__6EB3B36E] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterAdjustmentImport ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterAdjustmentImport] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [Version] timestamp NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [AdjustmentID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[ServiceLineEncounterAdjustmentImport] ([AdjustmentID]);
CREATE NONCLUSTERED INDEX [CORE_AdjustmentGUID_EntityID_ServiceLineID] ON [fp].[ServiceLineEncounterAdjustmentImport] ([AdjustmentGUID], [EntityID], [ServiceLineID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Adjus__259A9F5B] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Adjus__3D866C2E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Entit__3E7A9067] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Patie__3F6EB4A0] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Servi__4062D8D9] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Servi__4156FD12] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__AgeCo__424B214B] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Medic__433F4584] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Depar__443369BD] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Payor__45278DF6] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Payor__461BB22F] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__MSDRG__470FD668] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__CPTID__4803FAA1] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Provi__48F81EDA] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Physi__49EC4313] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_UnitTypeID] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_VALUE] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__TimeC__4EB0F830] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Budge__4FA51C69] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__IsRec__7560B0FD] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterAdjustment_backup ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterAdjustment_backup] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [FK__ServiceLi__Budge__5FC3E1CA] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [df_SlBackup_AdjustedProperty] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__TimeC__18FE279E] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Budge__19F24BD7] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Adjus__54522F1E] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Adjus__55465357] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Value__563A7790] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Adjus__572E9BC9] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Group__5822C002] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Comme__5A0B0874] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Autho__5AFF2CAD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Autho__5BF350E6] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__LastM__5CE7751F] DEFAULT (getdate()) FOR [LastModifiedDate]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__DateC__5DDB9958] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Group__5ECFBD91] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterChangeHistory] (
    [RowID] bigint NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    [ServiceLineEncounterID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ServiceLineEncounterChangeHistory] ON [fp].[ServiceLineEncounterChangeHistory] ([ServiceLineEncounterID]);
CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounterChangeHistory_AdjustmentGuid] ON [fp].[ServiceLineEncounterChangeHistory] ([AdjustmentGUID]) INCLUDE ([ServiceLineEncounterID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]);
CREATE NONCLUSTERED INDEX [CORE_ServiceLineEncounterChangeHistory_ImpactReportLoads] ON [fp].[ServiceLineEncounterChangeHistory] ([AdjustmentGUID], [FiscalMonthID], [TimeClassID]) INCLUDE ([ServiceLineEncounterID], [AdjustmentType], [UnitTypeID], [BudgetPhaseID], [OldValue], [NewValue], [BudgetConfigID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Group__003279D4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Adjus__01269E0D] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__DateC__01F1706B] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Fisca__030EE67F] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__UnitT__04030AB8] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__TimeC__04F72EF1] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Budge__05EB532A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__06DF7763] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__07D39B9C] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Budge__5D2A0010] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewSe__7B928452] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Adjus__7F3E559B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterChargeVolumeMapping ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ProviderID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [CLU_SleCV_ndx] ON [fp].[ServiceLineEncounterChargeVolumeMapping] ([BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [ProviderID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ServiceLineEncounterChargeVolumeMapping] ([BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [ProviderID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Budge__2683D69C] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Entit__2777FAD5] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Depar__286C1F0E] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Servi__29604347] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF_ServiceLineEncounterChargeVolumeMapping_Provider] DEFAULT ((0)) FOR [ProviderID]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterHistory] (
    [RowID] int NOT NULL,
    [ServiceLineEncounterID] int NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_ServiceLineEncounterHistory] ON [fp].[ServiceLineEncounterHistory] ([ServiceLineEncounterID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ServiceLineEncounterHistory] ([ServiceLineEncounterID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [FK_ServiceLineEncounterHistory_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ServiceLineEncounter] ([ServiceLineEncounterID]); GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Servi__436339C8] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__44575E01] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__454B823A] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__463FA673] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4733CAAC] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4827EEE5] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__491C131E] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4A103757] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4B045B90] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4BF87FC9] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4CECA402] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4DE0C83B] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4ED4EC74] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__4FC910AD] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__50BD34E6] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__51B1591F] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__52A57D58] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__5399A191] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__548DC5CA] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__5581EA03] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__56760E3C] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__576A3275] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__585E56AE] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__59527AE7] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__5A469F20] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5B3AC359] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5C2EE792] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5D230BCB] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5E173004] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5F0B543D] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5FFF7876] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__60F39CAF] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__61E7C0E8] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__62DBE521] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__63D0095A] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__64C42D93] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__65B851CC] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterPayorGroupMix ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterPayorGroupMix] (
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [TimeClassID] int NOT NULL,
    [MixPercentage] decimal NOT NULL,
    [InitialMixPercentage] decimal NOT NULL,
    [ServiceLineID] int NOT NULL
);

CREATE UNIQUE NONCLUSTERED INDEX [CORE_MixUnique] ON [fp].[ServiceLineEncounterPayorGroupMix] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [PayorGroupID], [TimeClassID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Servi__1B603566] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Budge__5D21751D] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Entit__5E159956] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Entit__5F09BD8F] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Patie__5FFDE1C8] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Payor__60F20601] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__TimeC__61E62A3A] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__MixPe__62DA4E73] DEFAULT ((0)) FOR [MixPercentage]; GO
ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Initi__63CE72AC] DEFAULT ((0)) FOR [InitialMixPercentage]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterSpreads ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterSpreads] (
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [IsInactive] bit NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [GlobalSpreadID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [EntityID], [ServiceLineID], [PatientClassID])
);
GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_FpServiceLineEncounterSpreads_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_FpServiceLineEncounterSpreads_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_FpServiceLineEncounterSpreads_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_ServiceLineEncounterSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Budge__65D5EB58] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Entit__66CA0F91] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Servi__67BE33CA] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Patie__68B25803] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__IsIna__69A67C3C] DEFAULT ((0)) FOR [IsInactive]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6A9AA075] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6B8EC4AE] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6C82E8E7] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6D770D20] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6E6B3159] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6F5F5592] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__705379CB] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__71479E04] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__723BC23D] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__732FE676] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__74240AAF] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__75182EE8] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Total__760C5321] DEFAULT ((0)) FOR [TotalImportedValue]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [df_ServiceLineEncounterSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Globa__77F49B93] DEFAULT ((1)) FOR [GlobalSpreadID]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterSpreadsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] (
    [RowID] bigint NOT NULL,
    [ServiceLineEncounterID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [OldValue01] decimal NOT NULL,
    [OldValue02] decimal NOT NULL,
    [OldValue03] decimal NOT NULL,
    [OldValue04] decimal NOT NULL,
    [OldValue05] decimal NOT NULL,
    [OldValue06] decimal NOT NULL,
    [OldValue07] decimal NOT NULL,
    [OldValue08] decimal NOT NULL,
    [OldValue09] decimal NOT NULL,
    [OldValue10] decimal NOT NULL,
    [OldValue11] decimal NOT NULL,
    [OldValue12] decimal NOT NULL,
    [NewValue01] decimal NOT NULL,
    [NewValue02] decimal NOT NULL,
    [NewValue03] decimal NOT NULL,
    [NewValue04] decimal NOT NULL,
    [NewValue05] decimal NOT NULL,
    [NewValue06] decimal NOT NULL,
    [NewValue07] decimal NOT NULL,
    [NewValue08] decimal NOT NULL,
    [NewValue09] decimal NOT NULL,
    [NewValue10] decimal NOT NULL,
    [NewValue11] decimal NOT NULL,
    [NewValue12] decimal NOT NULL
);

CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[ServiceLineEncounterSpreadsChangeHistory] ([BudgetConfigID], [ServiceLineEncounterID], [RowID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__00D7F30A] DEFAULT ((0)) FOR [NewValue10]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__01CC1743] DEFAULT ((0)) FOR [NewValue11]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__02C03B7C] DEFAULT ((0)) FOR [NewValue12]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Servi__69F48DB2] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Budge__6AE8B1EB] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__DateC__6BDCD624] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6CD0FA5D] DEFAULT ((0)) FOR [OldValue01]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6DC51E96] DEFAULT ((0)) FOR [OldValue02]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6EB942CF] DEFAULT ((0)) FOR [OldValue03]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6FAD6708] DEFAULT ((0)) FOR [OldValue04]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__70A18B41] DEFAULT ((0)) FOR [OldValue05]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__7195AF7A] DEFAULT ((0)) FOR [OldValue06]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__7289D3B3] DEFAULT ((0)) FOR [OldValue07]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__737DF7EC] DEFAULT ((0)) FOR [OldValue08]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__74721C25] DEFAULT ((0)) FOR [OldValue09]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__7566405E] DEFAULT ((0)) FOR [OldValue10]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__765A6497] DEFAULT ((0)) FOR [OldValue11]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__774E88D0] DEFAULT ((0)) FOR [OldValue12]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7842AD09] DEFAULT ((0)) FOR [NewValue01]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7936D142] DEFAULT ((0)) FOR [NewValue02]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7A2AF57B] DEFAULT ((0)) FOR [NewValue03]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7B1F19B4] DEFAULT ((0)) FOR [NewValue04]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7C133DED] DEFAULT ((0)) FOR [NewValue05]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7D076226] DEFAULT ((0)) FOR [NewValue06]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7DFB865F] DEFAULT ((0)) FOR [NewValue07]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7EEFAA98] DEFAULT ((0)) FOR [NewValue08]; GO
ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7FE3CED1] DEFAULT ((0)) FOR [NewValue09]; GO

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

---------------------------------------------
-- fp.ServiceLineEncounterToChargePayorMix ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncounterToChargePayorMix] (
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [InitialMixPercentage] decimal NOT NULL,
    [ProjectionMixPercentage] decimal NOT NULL,
    [BudgetMixPercentage] decimal NOT NULL,
    [ActualYTDMixPercentage] decimal NOT NULL,
    [PriorYearActualMixPercentage] decimal NOT NULL,
    [CurrentYearBudgetMixPercentage] decimal NOT NULL,
    [InitialProjectionMixPercentage] decimal NOT NULL
);

CREATE UNIQUE NONCLUSTERED INDEX [CORE_MixUnique] ON [fp].[ServiceLineEncounterToChargePayorMix] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [MSDRGID], [CPTID], [ProviderID], [PayorGroupID], [PayorID]);
GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Initi__1D52D143] DEFAULT ((0)) FOR [InitialProjectionMixPercentage]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Budge__4BA2AEB7] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Entit__4C96D2F0] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Entit__4D8AF729] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Patie__4E7F1B62] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Servi__4F733F9B] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__AgeCo__506763D4] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Medic__515B880D] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__MSDRG__524FAC46] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__CPTID__5343D07F] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Provi__5437F4B8] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Payor__552C18F1] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Payor__56203D2A] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Initi__57146163] DEFAULT ((0)) FOR [InitialMixPercentage]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Proje__5808859C] DEFAULT ((0)) FOR [ProjectionMixPercentage]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Budge__58FCA9D5] DEFAULT ((0)) FOR [BudgetMixPercentage]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Actua__59F0CE0E] DEFAULT ((0)) FOR [ActualYTDMixPercentage]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Prior__5AE4F247] DEFAULT ((0)) FOR [PriorYearActualMixPercentage]; GO
ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Curre__5BD91680] DEFAULT ((0)) FOR [CurrentYearBudgetMixPercentage]; GO

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

---------------------------------------------
-- fp.ServiceLineEncountersSpreadUnlockData ------------------
---------------------------------------------
CREATE TABLE [fp].[ServiceLineEncountersSpreadUnlockData] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ServiceLineID] int NOT NULL,
    [ServiceLineRollupID] int NOT NULL,
    [AgeCohortID] int NOT NULL,
    [MedicalSurgicalID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PayorGroupID] int NOT NULL,
    [MSDRGID] int NOT NULL,
    [CPTID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [PhysicianSpecialtyID] int NOT NULL,
    [Version] timestamp NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Budge__4AECEAF2] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Adjus__4BE10F2B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Entit__4CD53364] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Patie__4DC9579D] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Servi__4EBD7BD6] DEFAULT ((0)) FOR [ServiceLineID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Servi__4FB1A00F] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__AgeCo__50A5C448] DEFAULT ((0)) FOR [AgeCohortID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Medic__5199E881] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Depar__528E0CBA] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Payor__538230F3] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Payor__5476552C] DEFAULT ((0)) FOR [PayorGroupID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__MSDRG__556A7965] DEFAULT ((0)) FOR [MSDRGID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__CPTID__565E9D9E] DEFAULT ((0)) FOR [CPTID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Provi__5752C1D7] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Physi__5846E610] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__593B0A49] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5A2F2E82] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5B2352BB] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5C1776F4] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5D0B9B2D] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5DFFBF66] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5EF3E39F] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5FE807D8] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__60DC2C11] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__61D0504A] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__62C47483] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__63B898BC] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__IsRec__64ACBCF5] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.SettingCategory ------------------
---------------------------------------------
CREATE TABLE [fp].[SettingCategory] (
    [SettingCategoryID] int NOT NULL,
    [CategoryID] int NOT NULL,
    [SystemSettingID] int NOT NULL,
    [BudgetConfigDefaultSettingID] int NOT NULL
);
GO
ALTER TABLE [fp].[SettingCategory] ADD CONSTRAINT [DF__SettingCa__Categ__64A366AB] DEFAULT ((0)) FOR [CategoryID]; GO
ALTER TABLE [fp].[SettingCategory] ADD CONSTRAINT [DF__SettingCa__Syste__65978AE4] DEFAULT ((0)) FOR [SystemSettingID]; GO
ALTER TABLE [fp].[SettingCategory] ADD CONSTRAINT [DF__SettingCa__Budge__668BAF1D] DEFAULT ((0)) FOR [BudgetConfigDefaultSettingID]; GO

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

---------------------------------------------
-- fp.SpreadHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[SpreadHistory] (
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [Date] datetime NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(max) NOT NULL,
    [ExcelFile] varbinary(max) NULL,
    PRIMARY KEY ([SpreadHistoryGUID])
);
GO
ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [df_SpreadHistory_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO
ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [df_SpreadHistory_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [DF__SpreadHis__Autho__463A1712] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [DF__SpreadHist__Date__55B164CC] DEFAULT (getdate()) FOR [Date]; GO

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

---------------------------------------------
-- fp.Staffing ------------------
---------------------------------------------
CREATE TABLE [fp].[Staffing] (
    [StaffingID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [StaffingWageRateID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [AddDate] datetime NOT NULL,
    [IsNew] bit NOT NULL,
    [SubsectionID] int NOT NULL,
    [FixedVariabilityPercentage] decimal NOT NULL,
    [FlexingTypeID] smallint NOT NULL,
    [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL,
    [SampledBudgetDollarsTotal] decimal NULL,
    [SampledProjectionDollarsTotal] decimal NULL,
    [InitialBudgetDollarsTotal] decimal NULL,
    [InitialProjectionDollarsTotal] decimal NULL,
    [TargetAdjustedDollarsTotal] decimal NULL,
    [BudgetAdjustedDollarsTotal] decimal NULL,
    [ProjectionAdjustedDollarsTotal] decimal NULL,
    [SampledBudgetHoursTotal] decimal NULL,
    [SampledProjectionHoursTotal] decimal NULL,
    [InitialBudgetHoursTotal] decimal NULL,
    [InitialProjectionHoursTotal] decimal NULL,
    [TargetAdjustedHoursTotal] decimal NULL,
    [BudgetAdjustedHoursTotal] decimal NULL,
    [ProjectionAdjustedHoursTotal] decimal NULL,
    [SampledBudgetDollars01] decimal NOT NULL,
    [SampledBudgetDollars02] decimal NOT NULL,
    [SampledBudgetDollars03] decimal NOT NULL,
    [SampledBudgetDollars04] decimal NOT NULL,
    [SampledBudgetDollars05] decimal NOT NULL,
    [SampledBudgetDollars06] decimal NOT NULL,
    [SampledBudgetDollars07] decimal NOT NULL,
    [SampledBudgetDollars08] decimal NOT NULL,
    [SampledBudgetDollars09] decimal NOT NULL,
    [SampledBudgetDollars10] decimal NOT NULL,
    [SampledBudgetDollars11] decimal NOT NULL,
    [SampledBudgetDollars12] decimal NOT NULL,
    [SampledProjectionDollars01] decimal NOT NULL,
    [SampledProjectionDollars02] decimal NOT NULL,
    [SampledProjectionDollars03] decimal NOT NULL,
    [SampledProjectionDollars04] decimal NOT NULL,
    [SampledProjectionDollars05] decimal NOT NULL,
    [SampledProjectionDollars06] decimal NOT NULL,
    [SampledProjectionDollars07] decimal NOT NULL,
    [SampledProjectionDollars08] decimal NOT NULL,
    [SampledProjectionDollars09] decimal NOT NULL,
    [SampledProjectionDollars10] decimal NOT NULL,
    [SampledProjectionDollars11] decimal NOT NULL,
    [SampledProjectionDollars12] decimal NOT NULL,
    [InitialBudgetDollars01] decimal NOT NULL,
    [InitialBudgetDollars02] decimal NOT NULL,
    [InitialBudgetDollars03] decimal NOT NULL,
    [InitialBudgetDollars04] decimal NOT NULL,
    [InitialBudgetDollars05] decimal NOT NULL,
    [InitialBudgetDollars06] decimal NOT NULL,
    [InitialBudgetDollars07] decimal NOT NULL,
    [InitialBudgetDollars08] decimal NOT NULL,
    [InitialBudgetDollars09] decimal NOT NULL,
    [InitialBudgetDollars10] decimal NOT NULL,
    [InitialBudgetDollars11] decimal NOT NULL,
    [InitialBudgetDollars12] decimal NOT NULL,
    [InitialProjectionDollars01] decimal NOT NULL,
    [InitialProjectionDollars02] decimal NOT NULL,
    [InitialProjectionDollars03] decimal NOT NULL,
    [InitialProjectionDollars04] decimal NOT NULL,
    [InitialProjectionDollars05] decimal NOT NULL,
    [InitialProjectionDollars06] decimal NOT NULL,
    [InitialProjectionDollars07] decimal NOT NULL,
    [InitialProjectionDollars08] decimal NOT NULL,
    [InitialProjectionDollars09] decimal NOT NULL,
    [InitialProjectionDollars10] decimal NOT NULL,
    [InitialProjectionDollars11] decimal NOT NULL,
    [InitialProjectionDollars12] decimal NOT NULL,
    [TargetAdjustedDollars01] decimal NOT NULL,
    [TargetAdjustedDollars02] decimal NOT NULL,
    [TargetAdjustedDollars03] decimal NOT NULL,
    [TargetAdjustedDollars04] decimal NOT NULL,
    [TargetAdjustedDollars05] decimal NOT NULL,
    [TargetAdjustedDollars06] decimal NOT NULL,
    [TargetAdjustedDollars07] decimal NOT NULL,
    [TargetAdjustedDollars08] decimal NOT NULL,
    [TargetAdjustedDollars09] decimal NOT NULL,
    [TargetAdjustedDollars10] decimal NOT NULL,
    [TargetAdjustedDollars11] decimal NOT NULL,
    [TargetAdjustedDollars12] decimal NOT NULL,
    [BudgetAdjustedDollars01] decimal NOT NULL,
    [BudgetAdjustedDollars02] decimal NOT NULL,
    [BudgetAdjustedDollars03] decimal NOT NULL,
    [BudgetAdjustedDollars04] decimal NOT NULL,
    [BudgetAdjustedDollars05] decimal NOT NULL,
    [BudgetAdjustedDollars06] decimal NOT NULL,
    [BudgetAdjustedDollars07] decimal NOT NULL,
    [BudgetAdjustedDollars08] decimal NOT NULL,
    [BudgetAdjustedDollars09] decimal NOT NULL,
    [BudgetAdjustedDollars10] decimal NOT NULL,
    [BudgetAdjustedDollars11] decimal NOT NULL,
    [BudgetAdjustedDollars12] decimal NOT NULL,
    [ProjectionAdjustedDollars01] decimal NOT NULL,
    [ProjectionAdjustedDollars02] decimal NOT NULL,
    [ProjectionAdjustedDollars03] decimal NOT NULL,
    [ProjectionAdjustedDollars04] decimal NOT NULL,
    [ProjectionAdjustedDollars05] decimal NOT NULL,
    [ProjectionAdjustedDollars06] decimal NOT NULL,
    [ProjectionAdjustedDollars07] decimal NOT NULL,
    [ProjectionAdjustedDollars08] decimal NOT NULL,
    [ProjectionAdjustedDollars09] decimal NOT NULL,
    [ProjectionAdjustedDollars10] decimal NOT NULL,
    [ProjectionAdjustedDollars11] decimal NOT NULL,
    [ProjectionAdjustedDollars12] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor01] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor02] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor03] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor04] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor05] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor06] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor07] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor08] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor09] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor10] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor11] decimal NOT NULL,
    [TargetDollarsPercentAdjustmentFactor12] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor01] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor02] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor03] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor04] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor05] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor06] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor07] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor08] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor09] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor10] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor11] decimal NOT NULL,
    [BudgetDollarsPercentAdjustmentFactor12] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor01] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor02] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor03] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor04] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor05] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor06] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor07] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor08] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor09] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor10] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor11] decimal NOT NULL,
    [ProjectionDollarsPercentAdjustmentFactor12] decimal NOT NULL,
    [SampledBudgetHours01] decimal NOT NULL,
    [SampledBudgetHours02] decimal NOT NULL,
    [SampledBudgetHours03] decimal NOT NULL,
    [SampledBudgetHours04] decimal NOT NULL,
    [SampledBudgetHours05] decimal NOT NULL,
    [SampledBudgetHours06] decimal NOT NULL,
    [SampledBudgetHours07] decimal NOT NULL,
    [SampledBudgetHours08] decimal NOT NULL,
    [SampledBudgetHours09] decimal NOT NULL,
    [SampledBudgetHours10] decimal NOT NULL,
    [SampledBudgetHours11] decimal NOT NULL,
    [SampledBudgetHours12] decimal NOT NULL,
    [SampledProjectionHours01] decimal NOT NULL,
    [SampledProjectionHours02] decimal NOT NULL,
    [SampledProjectionHours03] decimal NOT NULL,
    [SampledProjectionHours04] decimal NOT NULL,
    [SampledProjectionHours05] decimal NOT NULL,
    [SampledProjectionHours06] decimal NOT NULL,
    [SampledProjectionHours07] decimal NOT NULL,
    [SampledProjectionHours08] decimal NOT NULL,
    [SampledProjectionHours09] decimal NOT NULL,
    [SampledProjectionHours10] decimal NOT NULL,
    [SampledProjectionHours11] decimal NOT NULL,
    [SampledProjectionHours12] decimal NOT NULL,
    [InitialBudgetHours01] decimal NOT NULL,
    [InitialBudgetHours02] decimal NOT NULL,
    [InitialBudgetHours03] decimal NOT NULL,
    [InitialBudgetHours04] decimal NOT NULL,
    [InitialBudgetHours05] decimal NOT NULL,
    [InitialBudgetHours06] decimal NOT NULL,
    [InitialBudgetHours07] decimal NOT NULL,
    [InitialBudgetHours08] decimal NOT NULL,
    [InitialBudgetHours09] decimal NOT NULL,
    [InitialBudgetHours10] decimal NOT NULL,
    [InitialBudgetHours11] decimal NOT NULL,
    [InitialBudgetHours12] decimal NOT NULL,
    [InitialProjectionHours01] decimal NOT NULL,
    [InitialProjectionHours02] decimal NOT NULL,
    [InitialProjectionHours03] decimal NOT NULL,
    [InitialProjectionHours04] decimal NOT NULL,
    [InitialProjectionHours05] decimal NOT NULL,
    [InitialProjectionHours06] decimal NOT NULL,
    [InitialProjectionHours07] decimal NOT NULL,
    [InitialProjectionHours08] decimal NOT NULL,
    [InitialProjectionHours09] decimal NOT NULL,
    [InitialProjectionHours10] decimal NOT NULL,
    [InitialProjectionHours11] decimal NOT NULL,
    [InitialProjectionHours12] decimal NOT NULL,
    [TargetAdjustedHours01] decimal NOT NULL,
    [TargetAdjustedHours02] decimal NOT NULL,
    [TargetAdjustedHours03] decimal NOT NULL,
    [TargetAdjustedHours04] decimal NOT NULL,
    [TargetAdjustedHours05] decimal NOT NULL,
    [TargetAdjustedHours06] decimal NOT NULL,
    [TargetAdjustedHours07] decimal NOT NULL,
    [TargetAdjustedHours08] decimal NOT NULL,
    [TargetAdjustedHours09] decimal NOT NULL,
    [TargetAdjustedHours10] decimal NOT NULL,
    [TargetAdjustedHours11] decimal NOT NULL,
    [TargetAdjustedHours12] decimal NOT NULL,
    [BudgetAdjustedHours01] decimal NOT NULL,
    [BudgetAdjustedHours02] decimal NOT NULL,
    [BudgetAdjustedHours03] decimal NOT NULL,
    [BudgetAdjustedHours04] decimal NOT NULL,
    [BudgetAdjustedHours05] decimal NOT NULL,
    [BudgetAdjustedHours06] decimal NOT NULL,
    [BudgetAdjustedHours07] decimal NOT NULL,
    [BudgetAdjustedHours08] decimal NOT NULL,
    [BudgetAdjustedHours09] decimal NOT NULL,
    [BudgetAdjustedHours10] decimal NOT NULL,
    [BudgetAdjustedHours11] decimal NOT NULL,
    [BudgetAdjustedHours12] decimal NOT NULL,
    [ProjectionAdjustedHours01] decimal NOT NULL,
    [ProjectionAdjustedHours02] decimal NOT NULL,
    [ProjectionAdjustedHours03] decimal NOT NULL,
    [ProjectionAdjustedHours04] decimal NOT NULL,
    [ProjectionAdjustedHours05] decimal NOT NULL,
    [ProjectionAdjustedHours06] decimal NOT NULL,
    [ProjectionAdjustedHours07] decimal NOT NULL,
    [ProjectionAdjustedHours08] decimal NOT NULL,
    [ProjectionAdjustedHours09] decimal NOT NULL,
    [ProjectionAdjustedHours10] decimal NOT NULL,
    [ProjectionAdjustedHours11] decimal NOT NULL,
    [ProjectionAdjustedHours12] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor01] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor02] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor03] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor04] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor05] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor06] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor07] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor08] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor09] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor10] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor11] decimal NOT NULL,
    [TargetHoursPercentAdjustmentFactor12] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor01] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor02] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor03] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor04] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor05] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor06] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor07] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor08] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor09] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor10] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor11] decimal NOT NULL,
    [BudgetHoursPercentAdjustmentFactor12] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor01] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor02] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor03] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor04] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor05] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor06] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor07] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor08] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor09] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor10] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor11] decimal NOT NULL,
    [ProjectionHoursPercentAdjustmentFactor12] decimal NOT NULL,
    [SampledBudgetFTEs01] decimal NOT NULL,
    [SampledBudgetFTEs02] decimal NOT NULL,
    [SampledBudgetFTEs03] decimal NOT NULL,
    [SampledBudgetFTEs04] decimal NOT NULL,
    [SampledBudgetFTEs05] decimal NOT NULL,
    [SampledBudgetFTEs06] decimal NOT NULL,
    [SampledBudgetFTEs07] decimal NOT NULL,
    [SampledBudgetFTEs08] decimal NOT NULL,
    [SampledBudgetFTEs09] decimal NOT NULL,
    [SampledBudgetFTEs10] decimal NOT NULL,
    [SampledBudgetFTEs11] decimal NOT NULL,
    [SampledBudgetFTEs12] decimal NOT NULL,
    [SampledProjectionFTEs01] decimal NOT NULL,
    [SampledProjectionFTEs02] decimal NOT NULL,
    [SampledProjectionFTEs03] decimal NOT NULL,
    [SampledProjectionFTEs04] decimal NOT NULL,
    [SampledProjectionFTEs05] decimal NOT NULL,
    [SampledProjectionFTEs06] decimal NOT NULL,
    [SampledProjectionFTEs07] decimal NOT NULL,
    [SampledProjectionFTEs08] decimal NOT NULL,
    [SampledProjectionFTEs09] decimal NOT NULL,
    [SampledProjectionFTEs10] decimal NOT NULL,
    [SampledProjectionFTEs11] decimal NOT NULL,
    [SampledProjectionFTEs12] decimal NOT NULL,
    [InitialBudgetFTEs01] decimal NOT NULL,
    [InitialBudgetFTEs02] decimal NOT NULL,
    [InitialBudgetFTEs03] decimal NOT NULL,
    [InitialBudgetFTEs04] decimal NOT NULL,
    [InitialBudgetFTEs05] decimal NOT NULL,
    [InitialBudgetFTEs06] decimal NOT NULL,
    [InitialBudgetFTEs07] decimal NOT NULL,
    [InitialBudgetFTEs08] decimal NOT NULL,
    [InitialBudgetFTEs09] decimal NOT NULL,
    [InitialBudgetFTEs10] decimal NOT NULL,
    [InitialBudgetFTEs11] decimal NOT NULL,
    [InitialBudgetFTEs12] decimal NOT NULL,
    [InitialProjectionFTEs01] decimal NOT NULL,
    [InitialProjectionFTEs02] decimal NOT NULL,
    [InitialProjectionFTEs03] decimal NOT NULL,
    [InitialProjectionFTEs04] decimal NOT NULL,
    [InitialProjectionFTEs05] decimal NOT NULL,
    [InitialProjectionFTEs06] decimal NOT NULL,
    [InitialProjectionFTEs07] decimal NOT NULL,
    [InitialProjectionFTEs08] decimal NOT NULL,
    [InitialProjectionFTEs09] decimal NOT NULL,
    [InitialProjectionFTEs10] decimal NOT NULL,
    [InitialProjectionFTEs11] decimal NOT NULL,
    [InitialProjectionFTEs12] decimal NOT NULL,
    [TargetAdjustedFTEs01] decimal NOT NULL,
    [TargetAdjustedFTEs02] decimal NOT NULL,
    [TargetAdjustedFTEs03] decimal NOT NULL,
    [TargetAdjustedFTEs04] decimal NOT NULL,
    [TargetAdjustedFTEs05] decimal NOT NULL,
    [TargetAdjustedFTEs06] decimal NOT NULL,
    [TargetAdjustedFTEs07] decimal NOT NULL,
    [TargetAdjustedFTEs08] decimal NOT NULL,
    [TargetAdjustedFTEs09] decimal NOT NULL,
    [TargetAdjustedFTEs10] decimal NOT NULL,
    [TargetAdjustedFTEs11] decimal NOT NULL,
    [TargetAdjustedFTEs12] decimal NOT NULL,
    [BudgetAdjustedFTEs01] decimal NOT NULL,
    [BudgetAdjustedFTEs02] decimal NOT NULL,
    [BudgetAdjustedFTEs03] decimal NOT NULL,
    [BudgetAdjustedFTEs04] decimal NOT NULL,
    [BudgetAdjustedFTEs05] decimal NOT NULL,
    [BudgetAdjustedFTEs06] decimal NOT NULL,
    [BudgetAdjustedFTEs07] decimal NOT NULL,
    [BudgetAdjustedFTEs08] decimal NOT NULL,
    [BudgetAdjustedFTEs09] decimal NOT NULL,
    [BudgetAdjustedFTEs10] decimal NOT NULL,
    [BudgetAdjustedFTEs11] decimal NOT NULL,
    [BudgetAdjustedFTEs12] decimal NOT NULL,
    [ProjectionAdjustedFTEs01] decimal NOT NULL,
    [ProjectionAdjustedFTEs02] decimal NOT NULL,
    [ProjectionAdjustedFTEs03] decimal NOT NULL,
    [ProjectionAdjustedFTEs04] decimal NOT NULL,
    [ProjectionAdjustedFTEs05] decimal NOT NULL,
    [ProjectionAdjustedFTEs06] decimal NOT NULL,
    [ProjectionAdjustedFTEs07] decimal NOT NULL,
    [ProjectionAdjustedFTEs08] decimal NOT NULL,
    [ProjectionAdjustedFTEs09] decimal NOT NULL,
    [ProjectionAdjustedFTEs10] decimal NOT NULL,
    [ProjectionAdjustedFTEs11] decimal NOT NULL,
    [ProjectionAdjustedFTEs12] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor01] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor02] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor03] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor04] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor05] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor06] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor07] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor08] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor09] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor10] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor11] decimal NOT NULL,
    [TargetFTEsPercentAdjustmentFactor12] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor01] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor02] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor03] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor04] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor05] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor06] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor07] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor08] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor09] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor10] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor11] decimal NOT NULL,
    [BudgetFTEsPercentAdjustmentFactor12] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor01] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor02] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor03] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor04] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor05] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor06] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor07] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor08] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor09] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor10] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor11] decimal NOT NULL,
    [ProjectionFTEsPercentAdjustmentFactor12] decimal NOT NULL,
    [InitialBudgetRate01] decimal NOT NULL,
    [InitialBudgetRate02] decimal NOT NULL,
    [InitialBudgetRate03] decimal NOT NULL,
    [InitialBudgetRate04] decimal NOT NULL,
    [InitialBudgetRate05] decimal NOT NULL,
    [InitialBudgetRate06] decimal NOT NULL,
    [InitialBudgetRate07] decimal NOT NULL,
    [InitialBudgetRate08] decimal NOT NULL,
    [InitialBudgetRate09] decimal NOT NULL,
    [InitialBudgetRate10] decimal NOT NULL,
    [InitialBudgetRate11] decimal NOT NULL,
    [InitialBudgetRate12] decimal NOT NULL,
    [InitialProjectionRate01] decimal NOT NULL,
    [InitialProjectionRate02] decimal NOT NULL,
    [InitialProjectionRate03] decimal NOT NULL,
    [InitialProjectionRate04] decimal NOT NULL,
    [InitialProjectionRate05] decimal NOT NULL,
    [InitialProjectionRate06] decimal NOT NULL,
    [InitialProjectionRate07] decimal NOT NULL,
    [InitialProjectionRate08] decimal NOT NULL,
    [InitialProjectionRate09] decimal NOT NULL,
    [InitialProjectionRate10] decimal NOT NULL,
    [InitialProjectionRate11] decimal NOT NULL,
    [InitialProjectionRate12] decimal NOT NULL,
    [TargetAdjustedRate01] decimal NOT NULL,
    [TargetAdjustedRate02] decimal NOT NULL,
    [TargetAdjustedRate03] decimal NOT NULL,
    [TargetAdjustedRate04] decimal NOT NULL,
    [TargetAdjustedRate05] decimal NOT NULL,
    [TargetAdjustedRate06] decimal NOT NULL,
    [TargetAdjustedRate07] decimal NOT NULL,
    [TargetAdjustedRate08] decimal NOT NULL,
    [TargetAdjustedRate09] decimal NOT NULL,
    [TargetAdjustedRate10] decimal NOT NULL,
    [TargetAdjustedRate11] decimal NOT NULL,
    [TargetAdjustedRate12] decimal NOT NULL,
    [BudgetAdjustedRate01] decimal NOT NULL,
    [BudgetAdjustedRate02] decimal NOT NULL,
    [BudgetAdjustedRate03] decimal NOT NULL,
    [BudgetAdjustedRate04] decimal NOT NULL,
    [BudgetAdjustedRate05] decimal NOT NULL,
    [BudgetAdjustedRate06] decimal NOT NULL,
    [BudgetAdjustedRate07] decimal NOT NULL,
    [BudgetAdjustedRate08] decimal NOT NULL,
    [BudgetAdjustedRate09] decimal NOT NULL,
    [BudgetAdjustedRate10] decimal NOT NULL,
    [BudgetAdjustedRate11] decimal NOT NULL,
    [BudgetAdjustedRate12] decimal NOT NULL,
    [ProjectionAdjustedRate01] decimal NOT NULL,
    [ProjectionAdjustedRate02] decimal NOT NULL,
    [ProjectionAdjustedRate03] decimal NOT NULL,
    [ProjectionAdjustedRate04] decimal NOT NULL,
    [ProjectionAdjustedRate05] decimal NOT NULL,
    [ProjectionAdjustedRate06] decimal NOT NULL,
    [ProjectionAdjustedRate07] decimal NOT NULL,
    [ProjectionAdjustedRate08] decimal NOT NULL,
    [ProjectionAdjustedRate09] decimal NOT NULL,
    [ProjectionAdjustedRate10] decimal NOT NULL,
    [ProjectionAdjustedRate11] decimal NOT NULL,
    [ProjectionAdjustedRate12] decimal NOT NULL,
    [BudgetDollarsLockType] tinyint NOT NULL,
    [BudgetDollarsLockFlag] tinyint NOT NULL,
    [TargetDollarsLockType] tinyint NOT NULL,
    [TargetDollarsLockFlag] tinyint NOT NULL,
    [ProjectionDollarsLockType] tinyint NOT NULL,
    [ProjectionDollarsLockFlag] tinyint NOT NULL,
    [BudgetHoursLockType] tinyint NOT NULL,
    [BudgetHoursLockFlag] tinyint NOT NULL,
    [TargetHoursLockType] tinyint NOT NULL,
    [TargetHoursLockFlag] tinyint NOT NULL,
    [ProjectionHoursLockType] tinyint NOT NULL,
    [ProjectionHoursLockFlag] tinyint NOT NULL,
    [BudgetFTEsLockType] tinyint NOT NULL,
    [BudgetFTEsLockFlag] tinyint NOT NULL,
    [TargetFTEsLockType] tinyint NOT NULL,
    [TargetFTEsLockFlag] tinyint NOT NULL,
    [ProjectionFTEsLockType] tinyint NOT NULL,
    [ProjectionFTEsLockFlag] tinyint NOT NULL,
    PRIMARY KEY ([StaffingID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[Staffing] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [EmployeeID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [SubsectionID]) INCLUDE ([IsNew]);
CREATE NONCLUSTERED INDEX [IX_Staffing_JobCode] ON [fp].[Staffing] ([JobCodeID]) INCLUDE ([StaffingID], [BudgetConfigID], [DepartmentID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]);
CREATE NONCLUSTERED INDEX [IX_Staffing_Department] ON [fp].[Staffing] ([DepartmentID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]);
CREATE NONCLUSTERED INDEX [IX_Staffing_Entity] ON [fp].[Staffing] ([EntityID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]);
CREATE NONCLUSTERED INDEX [IX_Staffing_EntityGroupConfig] ON [fp].[Staffing] ([EntityGroupConfigID]) INCLUDE ([StaffingID], [BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]);
CREATE NONCLUSTERED INDEX [IX_ESC44532] ON [fp].[Staffing] ([FlexingTypeID], [EntityGroupConfigID], [JobCodeID]) INCLUDE ([DepartmentID]);
GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_ProductiveClass] FOREIGN KEY ([ProductiveClassID]) REFERENCES [fw].[DimProductiveClass] ([ProductiveClassID]); GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__00E214AB] DEFAULT ((0)) FOR [InitialBudgetRate08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__01D638E4] DEFAULT ((0)) FOR [InitialBudgetRate09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__02CA5D1D] DEFAULT ((0)) FOR [InitialBudgetRate10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__03BE8156] DEFAULT ((0)) FOR [InitialBudgetRate11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__04B2A58F] DEFAULT ((0)) FOR [InitialBudgetRate12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__05A6C9C8] DEFAULT ((0)) FOR [InitialProjectionRate01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__069AEE01] DEFAULT ((0)) FOR [InitialProjectionRate02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__078F123A] DEFAULT ((0)) FOR [InitialProjectionRate03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__07C41C64] DEFAULT ((0)) FOR [SampledBudgetFTEs01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__08833673] DEFAULT ((0)) FOR [InitialProjectionRate04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__08B8409D] DEFAULT ((0)) FOR [SampledBudgetFTEs02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__09775AAC] DEFAULT ((0)) FOR [InitialProjectionRate05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__09AC64D6] DEFAULT ((0)) FOR [SampledBudgetFTEs03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0A6B7EE5] DEFAULT ((0)) FOR [InitialProjectionRate06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0AA0890F] DEFAULT ((0)) FOR [SampledBudgetFTEs04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0B5FA31E] DEFAULT ((0)) FOR [InitialProjectionRate07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0B94AD48] DEFAULT ((0)) FOR [SampledBudgetFTEs05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0C53C757] DEFAULT ((0)) FOR [InitialProjectionRate08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0C88D181] DEFAULT ((0)) FOR [SampledBudgetFTEs06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0D47EB90] DEFAULT ((0)) FOR [InitialProjectionRate09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0D7CF5BA] DEFAULT ((0)) FOR [SampledBudgetFTEs07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0E3C0FC9] DEFAULT ((0)) FOR [InitialProjectionRate10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0E7119F3] DEFAULT ((0)) FOR [SampledBudgetFTEs08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0F303402] DEFAULT ((0)) FOR [InitialProjectionRate11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0F653E2C] DEFAULT ((0)) FOR [SampledBudgetFTEs09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__0FCF5280] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__1024583B] DEFAULT ((0)) FOR [InitialProjectionRate12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__10596265] DEFAULT ((0)) FOR [SampledBudgetFTEs10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Entity__10C376B9] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__11187C74] DEFAULT ((0)) FOR [TargetAdjustedRate01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__114D869E] DEFAULT ((0)) FOR [SampledBudgetFTEs11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Staffi__11B79AF2] DEFAULT ((0)) FOR [StaffingWageRateID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__120CA0AD] DEFAULT ((0)) FOR [TargetAdjustedRate02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1241AAD7] DEFAULT ((0)) FOR [SampledBudgetFTEs12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Entity__12ABBF2B] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__1300C4E6] DEFAULT ((0)) FOR [TargetAdjustedRate03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1335CF10] DEFAULT ((0)) FOR [SampledProjectionFTEs01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Depart__139FE364] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__13F4E91F] DEFAULT ((0)) FOR [TargetAdjustedRate04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1429F349] DEFAULT ((0)) FOR [SampledProjectionFTEs02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__14E90D58] DEFAULT ((0)) FOR [TargetAdjustedRate05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__151E1782] DEFAULT ((0)) FOR [SampledProjectionFTEs03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__155321AC] DEFAULT ((0)) FOR [SampledBudgetHours01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__PayCod__15882BD6] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__15DD3191] DEFAULT ((0)) FOR [TargetAdjustedRate06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__16123BBB] DEFAULT ((0)) FOR [SampledProjectionFTEs04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__164745E5] DEFAULT ((0)) FOR [SampledBudgetHours02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Produc__167C500F] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__16D155CA] DEFAULT ((0)) FOR [TargetAdjustedRate07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__17065FF4] DEFAULT ((0)) FOR [SampledProjectionFTEs05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__173B6A1E] DEFAULT ((0)) FOR [SampledBudgetHours03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__17707448] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__17C57A03] DEFAULT ((0)) FOR [TargetAdjustedRate08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__17FA842D] DEFAULT ((0)) FOR [SampledProjectionFTEs06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__182F8E57] DEFAULT ((0)) FOR [SampledBudgetHours04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__18649881] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__18B99E3C] DEFAULT ((0)) FOR [TargetAdjustedRate09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__18EEA866] DEFAULT ((0)) FOR [SampledProjectionFTEs07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1923B290] DEFAULT ((0)) FOR [SampledBudgetHours05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__1958BCBA] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__19ADC275] DEFAULT ((0)) FOR [TargetAdjustedRate10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__19E2CC9F] DEFAULT ((0)) FOR [SampledProjectionFTEs08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1A17D6C9] DEFAULT ((0)) FOR [SampledBudgetHours06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__1A4CE0F3] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__1AA1E6AE] DEFAULT ((0)) FOR [TargetAdjustedRate11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1AD6F0D8] DEFAULT ((0)) FOR [SampledProjectionFTEs09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1B0BFB02] DEFAULT ((0)) FOR [SampledBudgetHours07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Employ__1B41052C] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__1B960AE7] DEFAULT ((0)) FOR [TargetAdjustedRate12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1BCB1511] DEFAULT ((0)) FOR [SampledProjectionFTEs10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1C001F3B] DEFAULT ((0)) FOR [SampledBudgetHours08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Variab__1C352965] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1C8A2F20] DEFAULT ((0)) FOR [BudgetAdjustedRate01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1CBF394A] DEFAULT ((0)) FOR [SampledProjectionFTEs11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1CF44374] DEFAULT ((0)) FOR [SampledBudgetHours09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__AddDat__1D294D9E] DEFAULT ('1900-01-01') FOR [AddDate]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1D7E5359] DEFAULT ((0)) FOR [BudgetAdjustedRate02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1DB35D83] DEFAULT ((0)) FOR [SampledProjectionFTEs12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1DE867AD] DEFAULT ((0)) FOR [SampledBudgetHours10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__IsNew__1E1D71D7] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1E727792] DEFAULT ((0)) FOR [BudgetAdjustedRate03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__1EA781BC] DEFAULT ((0)) FOR [InitialBudgetFTEs01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1EDC8BE6] DEFAULT ((0)) FOR [SampledBudgetHours11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Subsec__1F119610] DEFAULT ('3') FOR [SubsectionID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1F669BCB] DEFAULT ((0)) FOR [BudgetAdjustedRate04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__1F9BA5F5] DEFAULT ((0)) FOR [InitialBudgetFTEs02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1FD0B01F] DEFAULT ((0)) FOR [SampledBudgetHours12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__FixedV__2005BA49] DEFAULT ((1)) FOR [FixedVariabilityPercentage]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__205AC004] DEFAULT ((0)) FOR [BudgetAdjustedRate05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__208FCA2E] DEFAULT ((0)) FOR [InitialBudgetFTEs03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__20C4D458] DEFAULT ((0)) FOR [SampledProjectionHours01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Flexin__20F9DE82] DEFAULT ((0)) FOR [FlexingTypeID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__214EE43D] DEFAULT ((0)) FOR [BudgetAdjustedRate06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2183EE67] DEFAULT ((0)) FOR [InitialBudgetFTEs04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__21B8F891] DEFAULT ((0)) FOR [SampledProjectionHours02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Change__21EE02BB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__22430876] DEFAULT ((0)) FOR [BudgetAdjustedRate07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__227812A0] DEFAULT ((0)) FOR [InitialBudgetFTEs05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__22AD1CCA] DEFAULT ((0)) FOR [SampledProjectionHours03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__22E226F4] DEFAULT ((0)) FOR [SampledBudgetDollars01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__23372CAF] DEFAULT ((0)) FOR [BudgetAdjustedRate08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__236C36D9] DEFAULT ((0)) FOR [InitialBudgetFTEs06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__23A14103] DEFAULT ((0)) FOR [SampledProjectionHours04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__23D64B2D] DEFAULT ((0)) FOR [SampledBudgetDollars02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__242B50E8] DEFAULT ((0)) FOR [BudgetAdjustedRate09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__24605B12] DEFAULT ((0)) FOR [InitialBudgetFTEs07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2495653C] DEFAULT ((0)) FOR [SampledProjectionHours05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__24CA6F66] DEFAULT ((0)) FOR [SampledBudgetDollars03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__251F7521] DEFAULT ((0)) FOR [BudgetAdjustedRate10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__25547F4B] DEFAULT ((0)) FOR [InitialBudgetFTEs08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__25898975] DEFAULT ((0)) FOR [SampledProjectionHours06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__25BE939F] DEFAULT ((0)) FOR [SampledBudgetDollars04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__2613995A] DEFAULT ((0)) FOR [BudgetAdjustedRate11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2648A384] DEFAULT ((0)) FOR [InitialBudgetFTEs09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__267DADAE] DEFAULT ((0)) FOR [SampledProjectionHours07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__26B2B7D8] DEFAULT ((0)) FOR [SampledBudgetDollars05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__2707BD93] DEFAULT ((0)) FOR [BudgetAdjustedRate12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__273CC7BD] DEFAULT ((0)) FOR [InitialBudgetFTEs10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2771D1E7] DEFAULT ((0)) FOR [SampledProjectionHours08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__27A6DC11] DEFAULT ((0)) FOR [SampledBudgetDollars06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__27FBE1CC] DEFAULT ((0)) FOR [ProjectionAdjustedRate01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2830EBF6] DEFAULT ((0)) FOR [InitialBudgetFTEs11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2865F620] DEFAULT ((0)) FOR [SampledProjectionHours09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__289B004A] DEFAULT ((0)) FOR [SampledBudgetDollars07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__28F00605] DEFAULT ((0)) FOR [ProjectionAdjustedRate02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2925102F] DEFAULT ((0)) FOR [InitialBudgetFTEs12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__295A1A59] DEFAULT ((0)) FOR [SampledProjectionHours10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__298F2483] DEFAULT ((0)) FOR [SampledBudgetDollars08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__29E42A3E] DEFAULT ((0)) FOR [ProjectionAdjustedRate03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2A193468] DEFAULT ((0)) FOR [InitialProjectionFTEs01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2A4E3E92] DEFAULT ((0)) FOR [SampledProjectionHours11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2A8348BC] DEFAULT ((0)) FOR [SampledBudgetDollars09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2AD84E77] DEFAULT ((0)) FOR [ProjectionAdjustedRate04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2B0D58A1] DEFAULT ((0)) FOR [InitialProjectionFTEs02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2B4262CB] DEFAULT ((0)) FOR [SampledProjectionHours12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2B776CF5] DEFAULT ((0)) FOR [SampledBudgetDollars10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2BCC72B0] DEFAULT ((0)) FOR [ProjectionAdjustedRate05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2C017CDA] DEFAULT ((0)) FOR [InitialProjectionFTEs03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2C368704] DEFAULT ((0)) FOR [InitialBudgetHours01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2C6B912E] DEFAULT ((0)) FOR [SampledBudgetDollars11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2CC096E9] DEFAULT ((0)) FOR [ProjectionAdjustedRate06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2CF5A113] DEFAULT ((0)) FOR [InitialProjectionFTEs04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2D2AAB3D] DEFAULT ((0)) FOR [InitialBudgetHours02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2D5FB567] DEFAULT ((0)) FOR [SampledBudgetDollars12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2DB4BB22] DEFAULT ((0)) FOR [ProjectionAdjustedRate07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2DE9C54C] DEFAULT ((0)) FOR [InitialProjectionFTEs05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2E1ECF76] DEFAULT ((0)) FOR [InitialBudgetHours03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2E53D9A0] DEFAULT ((0)) FOR [SampledProjectionDollars01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2EA8DF5B] DEFAULT ((0)) FOR [ProjectionAdjustedRate08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2EDDE985] DEFAULT ((0)) FOR [InitialProjectionFTEs06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2F12F3AF] DEFAULT ((0)) FOR [InitialBudgetHours04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2F47FDD9] DEFAULT ((0)) FOR [SampledProjectionDollars02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2F9D0394] DEFAULT ((0)) FOR [ProjectionAdjustedRate09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2FD20DBE] DEFAULT ((0)) FOR [InitialProjectionFTEs07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__300717E8] DEFAULT ((0)) FOR [InitialBudgetHours05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__303C2212] DEFAULT ((0)) FOR [SampledProjectionDollars03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__309127CD] DEFAULT ((0)) FOR [ProjectionAdjustedRate10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__30C631F7] DEFAULT ((0)) FOR [InitialProjectionFTEs08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__30FB3C21] DEFAULT ((0)) FOR [InitialBudgetHours06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__3130464B] DEFAULT ((0)) FOR [SampledProjectionDollars04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__31854C06] DEFAULT ((0)) FOR [ProjectionAdjustedRate11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__31BA5630] DEFAULT ((0)) FOR [InitialProjectionFTEs09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__31EF605A] DEFAULT ((0)) FOR [InitialBudgetHours07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__32246A84] DEFAULT ((0)) FOR [SampledProjectionDollars05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__3279703F] DEFAULT ((0)) FOR [ProjectionAdjustedRate12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__32AE7A69] DEFAULT ((0)) FOR [InitialProjectionFTEs10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__32E38493] DEFAULT ((0)) FOR [InitialBudgetHours08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__33188EBD] DEFAULT ((0)) FOR [SampledProjectionDollars06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__336D9478] DEFAULT ((0)) FOR [BudgetDollarsLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__33A29EA2] DEFAULT ((0)) FOR [InitialProjectionFTEs11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__33D7A8CC] DEFAULT ((0)) FOR [InitialBudgetHours09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__340CB2F6] DEFAULT ((0)) FOR [SampledProjectionDollars07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3461B8B1] DEFAULT ((0)) FOR [BudgetDollarsLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3496C2DB] DEFAULT ((0)) FOR [InitialProjectionFTEs12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__34CBCD05] DEFAULT ((0)) FOR [InitialBudgetHours10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__3500D72F] DEFAULT ((0)) FOR [SampledProjectionDollars08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3555DCEA] DEFAULT ((0)) FOR [TargetDollarsLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__358AE714] DEFAULT ((0)) FOR [TargetAdjustedFTEs01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__35BFF13E] DEFAULT ((0)) FOR [InitialBudgetHours11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__35F4FB68] DEFAULT ((0)) FOR [SampledProjectionDollars09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__364A0123] DEFAULT ((0)) FOR [TargetDollarsLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__367F0B4D] DEFAULT ((0)) FOR [TargetAdjustedFTEs02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__36B41577] DEFAULT ((0)) FOR [InitialBudgetHours12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__36E91FA1] DEFAULT ((0)) FOR [SampledProjectionDollars10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__373E255C] DEFAULT ((0)) FOR [ProjectionDollarsLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__37732F86] DEFAULT ((0)) FOR [TargetAdjustedFTEs03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__37A839B0] DEFAULT ((0)) FOR [InitialProjectionHours01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__37DD43DA] DEFAULT ((0)) FOR [SampledProjectionDollars11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__38324995] DEFAULT ((0)) FOR [ProjectionDollarsLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__386753BF] DEFAULT ((0)) FOR [TargetAdjustedFTEs04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__389C5DE9] DEFAULT ((0)) FOR [InitialProjectionHours02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__38D16813] DEFAULT ((0)) FOR [SampledProjectionDollars12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__39266DCE] DEFAULT ((0)) FOR [BudgetHoursLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__395B77F8] DEFAULT ((0)) FOR [TargetAdjustedFTEs05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__39908222] DEFAULT ((0)) FOR [InitialProjectionHours03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__39C58C4C] DEFAULT ((0)) FOR [InitialBudgetDollars01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3A1A9207] DEFAULT ((0)) FOR [BudgetHoursLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3A4F9C31] DEFAULT ((0)) FOR [TargetAdjustedFTEs06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3A84A65B] DEFAULT ((0)) FOR [InitialProjectionHours04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3AB9B085] DEFAULT ((0)) FOR [InitialBudgetDollars02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3B0EB640] DEFAULT ((0)) FOR [TargetHoursLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3B43C06A] DEFAULT ((0)) FOR [TargetAdjustedFTEs07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3B78CA94] DEFAULT ((0)) FOR [InitialProjectionHours05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3BADD4BE] DEFAULT ((0)) FOR [InitialBudgetDollars03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3C02DA79] DEFAULT ((0)) FOR [TargetHoursLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3C37E4A3] DEFAULT ((0)) FOR [TargetAdjustedFTEs08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3C6CEECD] DEFAULT ((0)) FOR [InitialProjectionHours06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3CA1F8F7] DEFAULT ((0)) FOR [InitialBudgetDollars04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__3CF6FEB2] DEFAULT ((0)) FOR [ProjectionHoursLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3D2C08DC] DEFAULT ((0)) FOR [TargetAdjustedFTEs09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3D611306] DEFAULT ((0)) FOR [InitialProjectionHours07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3D961D30] DEFAULT ((0)) FOR [InitialBudgetDollars05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__3DEB22EB] DEFAULT ((0)) FOR [ProjectionHoursLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3E202D15] DEFAULT ((0)) FOR [TargetAdjustedFTEs10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3E55373F] DEFAULT ((0)) FOR [InitialProjectionHours08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3E8A4169] DEFAULT ((0)) FOR [InitialBudgetDollars06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3EDF4724] DEFAULT ((0)) FOR [BudgetFTEsLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3F14514E] DEFAULT ((0)) FOR [TargetAdjustedFTEs11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3F495B78] DEFAULT ((0)) FOR [InitialProjectionHours09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3F7E65A2] DEFAULT ((0)) FOR [InitialBudgetDollars07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3FD36B5D] DEFAULT ((0)) FOR [BudgetFTEsLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__40087587] DEFAULT ((0)) FOR [TargetAdjustedFTEs12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__403D7FB1] DEFAULT ((0)) FOR [InitialProjectionHours10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__407289DB] DEFAULT ((0)) FOR [InitialBudgetDollars08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__40C78F96] DEFAULT ((0)) FOR [TargetFTEsLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__40FC99C0] DEFAULT ((0)) FOR [BudgetAdjustedFTEs01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4131A3EA] DEFAULT ((0)) FOR [InitialProjectionHours11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4166AE14] DEFAULT ((0)) FOR [InitialBudgetDollars09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__41BBB3CF] DEFAULT ((0)) FOR [TargetFTEsLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__41F0BDF9] DEFAULT ((0)) FOR [BudgetAdjustedFTEs02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4225C823] DEFAULT ((0)) FOR [InitialProjectionHours12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__425AD24D] DEFAULT ((0)) FOR [InitialBudgetDollars10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__42AFD808] DEFAULT ((0)) FOR [ProjectionFTEsLockType]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__42E4E232] DEFAULT ((0)) FOR [BudgetAdjustedFTEs03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4319EC5C] DEFAULT ((0)) FOR [TargetAdjustedHours01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__434EF686] DEFAULT ((0)) FOR [InitialBudgetDollars11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__43A3FC41] DEFAULT ((0)) FOR [ProjectionFTEsLockFlag]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__43D9066B] DEFAULT ((0)) FOR [BudgetAdjustedFTEs04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__440E1095] DEFAULT ((0)) FOR [TargetAdjustedHours02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__44431ABF] DEFAULT ((0)) FOR [InitialBudgetDollars12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__44CD2AA4] DEFAULT ((0)) FOR [BudgetAdjustedFTEs05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__450234CE] DEFAULT ((0)) FOR [TargetAdjustedHours03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__45373EF8] DEFAULT ((0)) FOR [InitialProjectionDollars01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__45C14EDD] DEFAULT ((0)) FOR [BudgetAdjustedFTEs06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__45F65907] DEFAULT ((0)) FOR [TargetAdjustedHours04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__462B6331] DEFAULT ((0)) FOR [InitialProjectionDollars02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__46B57316] DEFAULT ((0)) FOR [BudgetAdjustedFTEs07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__46EA7D40] DEFAULT ((0)) FOR [TargetAdjustedHours05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__471F876A] DEFAULT ((0)) FOR [InitialProjectionDollars03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__47A9974F] DEFAULT ((0)) FOR [BudgetAdjustedFTEs08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__47DEA179] DEFAULT ((0)) FOR [TargetAdjustedHours06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4813ABA3] DEFAULT ((0)) FOR [InitialProjectionDollars04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__489DBB88] DEFAULT ((0)) FOR [BudgetAdjustedFTEs09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__48D2C5B2] DEFAULT ((0)) FOR [TargetAdjustedHours07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4907CFDC] DEFAULT ((0)) FOR [InitialProjectionDollars05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4991DFC1] DEFAULT ((0)) FOR [BudgetAdjustedFTEs10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__49C6E9EB] DEFAULT ((0)) FOR [TargetAdjustedHours08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__49FBF415] DEFAULT ((0)) FOR [InitialProjectionDollars06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4A8603FA] DEFAULT ((0)) FOR [BudgetAdjustedFTEs11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4ABB0E24] DEFAULT ((0)) FOR [TargetAdjustedHours09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4AF0184E] DEFAULT ((0)) FOR [InitialProjectionDollars07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4B7A2833] DEFAULT ((0)) FOR [BudgetAdjustedFTEs12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4BAF325D] DEFAULT ((0)) FOR [TargetAdjustedHours10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4BE43C87] DEFAULT ((0)) FOR [InitialProjectionDollars08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4C6E4C6C] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4CA35696] DEFAULT ((0)) FOR [TargetAdjustedHours11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4CD860C0] DEFAULT ((0)) FOR [InitialProjectionDollars09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4D6270A5] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4D977ACF] DEFAULT ((0)) FOR [TargetAdjustedHours12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4DCC84F9] DEFAULT ((0)) FOR [InitialProjectionDollars10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4E5694DE] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4E8B9F08] DEFAULT ((0)) FOR [BudgetAdjustedHours01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4EC0A932] DEFAULT ((0)) FOR [InitialProjectionDollars11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4F4AB917] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4F7FC341] DEFAULT ((0)) FOR [BudgetAdjustedHours02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4FB4CD6B] DEFAULT ((0)) FOR [InitialProjectionDollars12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__JobCod__4FFFB185] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__503EDD50] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5073E77A] DEFAULT ((0)) FOR [BudgetAdjustedHours03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__50A8F1A4] DEFAULT ((0)) FOR [TargetAdjustedDollars01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__51330189] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__51680BB3] DEFAULT ((0)) FOR [BudgetAdjustedHours04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__519D15DD] DEFAULT ((0)) FOR [TargetAdjustedDollars02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__522725C2] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__525C2FEC] DEFAULT ((0)) FOR [BudgetAdjustedHours05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__52913A16] DEFAULT ((0)) FOR [TargetAdjustedDollars03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__531B49FB] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__53505425] DEFAULT ((0)) FOR [BudgetAdjustedHours06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__53855E4F] DEFAULT ((0)) FOR [TargetAdjustedDollars04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__540F6E34] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5444785E] DEFAULT ((0)) FOR [BudgetAdjustedHours07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__54798288] DEFAULT ((0)) FOR [TargetAdjustedDollars05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5503926D] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__55389C97] DEFAULT ((0)) FOR [BudgetAdjustedHours08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__556DA6C1] DEFAULT ((0)) FOR [TargetAdjustedDollars06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__55F7B6A6] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__562CC0D0] DEFAULT ((0)) FOR [BudgetAdjustedHours09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5661CAFA] DEFAULT ((0)) FOR [TargetAdjustedDollars07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__56EBDADF] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5720E509] DEFAULT ((0)) FOR [BudgetAdjustedHours10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5755EF33] DEFAULT ((0)) FOR [TargetAdjustedDollars08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__58150942] DEFAULT ((0)) FOR [BudgetAdjustedHours11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__584A136C] DEFAULT ((0)) FOR [TargetAdjustedDollars09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__59092D7B] DEFAULT ((0)) FOR [BudgetAdjustedHours12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__593E37A5] DEFAULT ((0)) FOR [TargetAdjustedDollars10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__59FD51B4] DEFAULT ((0)) FOR [ProjectionAdjustedHours01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5A325BDE] DEFAULT ((0)) FOR [TargetAdjustedDollars11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5AF175ED] DEFAULT ((0)) FOR [ProjectionAdjustedHours02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5B268017] DEFAULT ((0)) FOR [TargetAdjustedDollars12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5BE59A26] DEFAULT ((0)) FOR [ProjectionAdjustedHours03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5C1AA450] DEFAULT ((0)) FOR [BudgetAdjustedDollars01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5CD9BE5F] DEFAULT ((0)) FOR [ProjectionAdjustedHours04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5D0EC889] DEFAULT ((0)) FOR [BudgetAdjustedDollars02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5DCDE298] DEFAULT ((0)) FOR [ProjectionAdjustedHours05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5E02ECC2] DEFAULT ((0)) FOR [BudgetAdjustedDollars03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5EC206D1] DEFAULT ((0)) FOR [ProjectionAdjustedHours06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5EF710FB] DEFAULT ((0)) FOR [BudgetAdjustedDollars04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5FB62B0A] DEFAULT ((0)) FOR [ProjectionAdjustedHours07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5FEB3534] DEFAULT ((0)) FOR [BudgetAdjustedDollars05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__60AA4F43] DEFAULT ((0)) FOR [ProjectionAdjustedHours08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__60DF596D] DEFAULT ((0)) FOR [BudgetAdjustedDollars06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__619E737C] DEFAULT ((0)) FOR [ProjectionAdjustedHours09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__61D37DA6] DEFAULT ((0)) FOR [BudgetAdjustedDollars07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__629297B5] DEFAULT ((0)) FOR [ProjectionAdjustedHours10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__62C7A1DF] DEFAULT ((0)) FOR [BudgetAdjustedDollars08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6386BBEE] DEFAULT ((0)) FOR [ProjectionAdjustedHours11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__63BBC618] DEFAULT ((0)) FOR [BudgetAdjustedDollars09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__647AE027] DEFAULT ((0)) FOR [ProjectionAdjustedHours12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__64AFEA51] DEFAULT ((0)) FOR [BudgetAdjustedDollars10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__65A40E8A] DEFAULT ((0)) FOR [BudgetAdjustedDollars11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__669832C3] DEFAULT ((0)) FOR [BudgetAdjustedDollars12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__678C56FC] DEFAULT ((0)) FOR [ProjectionAdjustedDollars01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__68807B35] DEFAULT ((0)) FOR [ProjectionAdjustedDollars02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__69749F6E] DEFAULT ((0)) FOR [ProjectionAdjustedDollars03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6A68C3A7] DEFAULT ((0)) FOR [ProjectionAdjustedDollars04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6B5CE7E0] DEFAULT ((0)) FOR [ProjectionAdjustedDollars05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6C510C19] DEFAULT ((0)) FOR [ProjectionAdjustedDollars06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6D453052] DEFAULT ((0)) FOR [ProjectionAdjustedDollars07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6E39548B] DEFAULT ((0)) FOR [ProjectionAdjustedDollars08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6F2D78C4] DEFAULT ((0)) FOR [ProjectionAdjustedDollars09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__70219CFD] DEFAULT ((0)) FOR [ProjectionAdjustedDollars10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__7115C136] DEFAULT ((0)) FOR [ProjectionAdjustedDollars11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__7209E56F] DEFAULT ((0)) FOR [ProjectionAdjustedDollars12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7A35171C] DEFAULT ((0)) FOR [InitialBudgetRate01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7B293B55] DEFAULT ((0)) FOR [InitialBudgetRate02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7C1D5F8E] DEFAULT ((0)) FOR [InitialBudgetRate03]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7D1183C7] DEFAULT ((0)) FOR [InitialBudgetRate04]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7E05A800] DEFAULT ((0)) FOR [InitialBudgetRate05]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7EF9CC39] DEFAULT ((0)) FOR [InitialBudgetRate06]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7FEDF072] DEFAULT ((0)) FOR [InitialBudgetRate07]; GO

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

---------------------------------------------
-- fp.StaffingAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [ParentFilterJSON] nvarchar(max) NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [AdjustmentID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    [IsErrored] bit NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);

CREATE NONCLUSTERED INDEX [JAZZ_7301_GroupingGUID] ON [fp].[StaffingAdjustment] ([GroupingGUID]) INCLUDE ([AdjustmentType], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AuthorGUID], [AuthorFullName], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted], [DateCreatedUtc], [LastModifiedDateUtc]);
GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [FK__PayrollBu__Budge__28348115] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [FK_StaffingAdjustment_SubsectionID] FOREIGN KEY ([SubsectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_SubsectionID] DEFAULT ((0)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2928A54E] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2A1CC987] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Value__2B10EDC0] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2C0511F9] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Group__2CF93632] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2DED5A6B] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Comme__2EE17EA4] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Autho__2FD5A2DD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Autho__30C9C716] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__UnitT__33A633C1] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Group__349A57FA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Paren__4A20501C] DEFAULT ('{}') FOR [ParentFilterJSON]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__IsErr__4AF96E98] DEFAULT ((0)) FOR [IsErrored]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__Dimen__63E1EA97] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__DateC__681C8FCF] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__LastM__6910B408] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__TimeC__6B169606] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__IsRec__6FA7D7A7] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.StaffingAdjustmentImport ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingAdjustmentImport] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [Version] timestamp NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [EntityID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [EmployeeID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [OriginalUnitTypeID] tinyint NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[StaffingAdjustmentImport] ([AdjustmentID]);
GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_StaffingAdjustmentImport_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_INTPayrollAdjImportINGVALUE] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_PayrollAdjImport_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Produ__7712F224] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Emplo__0478D75B] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Varia__14F85AC6] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Adjus__268EC394] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__30981C12] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__318C404B] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__32806484] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__337488BD] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Entit__35652A58] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Adjus__6F71D05C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__JobCo__2D57C830] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_StaffingAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__IsRec__7378688B] DEFAULT ((0)) FOR [IsRecordDeleted]; GO

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

---------------------------------------------
-- fp.StaffingAdjustment_backup ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingAdjustment_backup] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [ParentFilterJSON] nvarchar(max) NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [FK__PayrollBu__Budge__0C575C76] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__00E5A9CA] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Value__01D9CE03] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__02CDF23C] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Group__03C21675] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__04B63AAE] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Comme__05AA5EE7] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Autho__069E8320] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Autho__0792A759] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__LastM__0886CB92] DEFAULT (getdate()) FOR [LastModifiedDate]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__DateC__097AEFCB] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__UnitT__0A6F1404] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Group__0B63383D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Paren__0FFF66D6] DEFAULT ('') FOR [ParentFilterJSON]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF_StaffingAdjustmentBackup_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__StaffingA__TimeC__6C0ABA3F] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__7FF18591] DEFAULT (newid()) FOR [AdjustmentGUID]; GO

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

---------------------------------------------
-- fp.StaffingBasisFlexRate ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingBasisFlexRate] (
    [RowID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [UnitTypeID] int NOT NULL,
    [FlexRate01] decimal NOT NULL,
    [FlexRate02] decimal NOT NULL,
    [FlexRate03] decimal NOT NULL,
    [FlexRate04] decimal NOT NULL,
    [FlexRate05] decimal NOT NULL,
    [FlexRate06] decimal NOT NULL,
    [FlexRate07] decimal NOT NULL,
    [FlexRate08] decimal NOT NULL,
    [FlexRate09] decimal NOT NULL,
    [FlexRate10] decimal NOT NULL,
    [FlexRate11] decimal NOT NULL,
    [FlexRate12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[StaffingBasisFlexRate] ([BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [ProviderID], [ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], [FiscalYearID], [TimeClassID], [AdjustmentGUID]);
GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [FK_StaffingBasisFlexRate_AdjustmentGUID] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[StaffingAdjustment] ([AdjustmentGUID]); GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Entit__5971AB21] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Depar__5A65CF5A] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__JobCo__5B59F393] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__PayCo__5C4E17CC] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Produ__5D423C05] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Fisca__5E36603E] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__TimeC__5F2A8477] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Budge__601EA8B0] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Adjus__6112CCE9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Emplo__6206F122] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__62FB155B] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__63EF3994] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__64E35DCD] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__65D78206] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__UnitT__66CBA63F] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__67BFCA78] DEFAULT ((0)) FOR [FlexRate01]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__68B3EEB1] DEFAULT ((0)) FOR [FlexRate02]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__69A812EA] DEFAULT ((0)) FOR [FlexRate03]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6A9C3723] DEFAULT ((0)) FOR [FlexRate04]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6B905B5C] DEFAULT ((0)) FOR [FlexRate05]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6C847F95] DEFAULT ((0)) FOR [FlexRate06]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6D78A3CE] DEFAULT ((0)) FOR [FlexRate07]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6E6CC807] DEFAULT ((0)) FOR [FlexRate08]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6F60EC40] DEFAULT ((0)) FOR [FlexRate09]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__70551079] DEFAULT ((0)) FOR [FlexRate10]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__714934B2] DEFAULT ((0)) FOR [FlexRate11]; GO
ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__723D58EB] DEFAULT ((0)) FOR [FlexRate12]; GO

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

---------------------------------------------
-- fp.StaffingChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingChangeHistory] (
    [RowID] bigint NOT NULL,
    [StaffingID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    [SubsectionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_StaffingChangeHistory] ON [fp].[StaffingChangeHistory] ([StaffingID]);
CREATE NONCLUSTERED INDEX [IX_StaffingChangeHistory_AdjustmentGuid] ON [fp].[StaffingChangeHistory] ([AdjustmentGUID]) INCLUDE ([StaffingID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [FK_StaffingChangeHistory_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[Staffing] ([StaffingID]); GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Staff__61E95796] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Adjus__62DD7BCF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Group__63D1A008] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Adjus__64C5C441] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Fisca__65B9E87A] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__UnitT__66AE0CB3] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__TimeC__67A230EC] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Budge__68965525] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__OldVa__698A795E] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__NewVa__6A7E9D97] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Budge__6B72C1D0] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__DateC__6C66E609] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Subse__6D5B0A42] DEFAULT ((0)) FOR [SubsectionID]; GO

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

---------------------------------------------
-- fp.StaffingChangeHistory_OLD ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingChangeHistory_OLD] (
    [RowID] bigint NOT NULL,
    [StaffingID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    [SubsectionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__DateC__04CDDD16] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Staff__17A54CA8] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Subse__17D75B40] DEFAULT ((3)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Adjus__189970E1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Group__198D951A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Adjus__1A81B953] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Fisca__1C6A01C5] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__UnitT__1D5E25FE] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__TimeC__1E524A37] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Budge__1F466E70] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__OldVa__203A92A9] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__NewVa__212EB6E2] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Budge__60066CBB] DEFAULT ((0)) FOR [BudgetConfigID]; GO

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

---------------------------------------------
-- fp.StaffingExpenseFlexingConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingExpenseFlexingConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    [RowID] int NOT NULL,
    [ProductivityTarget] decimal NOT NULL,
    [IsUsingProductivityTarget] bit NOT NULL,
    [IsUsingEmployeeBudgeting] bit NOT NULL,
    [ProjectionProductivityTarget] decimal NOT NULL,
    [IsUsingProjectionProductivityTarget] bit NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID])
);
GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [FK__StaffingE__Depar__40C134DE] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__Produ__023135C3] DEFAULT ((0)) FOR [ProductivityTarget]; GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__IsUsi__0A930848] DEFAULT ((0)) FOR [IsUsingProductivityTarget]; GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [df_StaffingExpenseFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__Depar__3D071777] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__FlexM__3DFB3BB0] DEFAULT ((0)) FOR [FlexMethodID]; GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF_StaffingExpenseFlexingConfig_ProjectionProductivityTarget] DEFAULT ((0)) FOR [ProjectionProductivityTarget]; GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF_StaffingExpenseFlexingConfig_IsUsingProjectionProductivityTarget] DEFAULT ((0)) FOR [IsUsingProjectionProductivityTarget]; GO
ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__IsUsi__727A22B1] DEFAULT ((0)) FOR [IsUsingEmployeeBudgeting]; GO

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

---------------------------------------------
-- fp.StaffingFlexingOverrideConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingFlexingOverrideConfig] (
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    PRIMARY KEY ([OverrideFlexConfigGUID])
);

CREATE UNIQUE NONCLUSTERED INDEX [Unique_StaffingFlexingOverrideConfig_EC_Dept_Account] ON [fp].[StaffingFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [JobCodeID]);
GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [FK__StaffingF__Depar__486256A6] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [df_StaffingFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__Overr__42BFF0CD] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__Depar__44A8393F] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__JobCo__459C5D78] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__FlexM__469081B1] DEFAULT ((0)) FOR [FlexMethodID]; GO

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

---------------------------------------------
-- fp.StaffingFlexingOverrideConfigAssignment ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingFlexingOverrideConfigAssignment] (
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    [AccountID] int NOT NULL,
    PRIMARY KEY ([OverrideFlexConfigGUID], [AccountID])
);
GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfigAssignment] ADD CONSTRAINT [FK_OverrideFlexConfigGUID] FOREIGN KEY ([OverrideFlexConfigGUID]) REFERENCES [fp].[StaffingFlexingOverrideConfig] ([OverrideFlexConfigGUID]); GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__StaffingF__Overr__496CEE5C] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO
ALTER TABLE [fp].[StaffingFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__StaffingF__Accou__4A611295] DEFAULT ((0)) FOR [AccountID]; GO

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

---------------------------------------------
-- fp.StaffingHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingHistory] (
    [StaffingID] int NOT NULL,
    [ActualYTDDollars01] decimal NOT NULL,
    [ActualYTDDollars02] decimal NOT NULL,
    [ActualYTDDollars03] decimal NOT NULL,
    [ActualYTDDollars04] decimal NOT NULL,
    [ActualYTDDollars05] decimal NOT NULL,
    [ActualYTDDollars06] decimal NOT NULL,
    [ActualYTDDollars07] decimal NOT NULL,
    [ActualYTDDollars08] decimal NOT NULL,
    [ActualYTDDollars09] decimal NOT NULL,
    [ActualYTDDollars10] decimal NOT NULL,
    [ActualYTDDollars11] decimal NOT NULL,
    [ActualYTDDollars12] decimal NOT NULL,
    [ActualYTDDollarsTotal] decimal NULL,
    [PriorYearActualDollars01] decimal NOT NULL,
    [PriorYearActualDollars02] decimal NOT NULL,
    [PriorYearActualDollars03] decimal NOT NULL,
    [PriorYearActualDollars04] decimal NOT NULL,
    [PriorYearActualDollars05] decimal NOT NULL,
    [PriorYearActualDollars06] decimal NOT NULL,
    [PriorYearActualDollars07] decimal NOT NULL,
    [PriorYearActualDollars08] decimal NOT NULL,
    [PriorYearActualDollars09] decimal NOT NULL,
    [PriorYearActualDollars10] decimal NOT NULL,
    [PriorYearActualDollars11] decimal NOT NULL,
    [PriorYearActualDollars12] decimal NOT NULL,
    [PriorYearActualDollarsTotal] decimal NULL,
    [CurrentYearBudgetDollars01] decimal NOT NULL,
    [CurrentYearBudgetDollars02] decimal NOT NULL,
    [CurrentYearBudgetDollars03] decimal NOT NULL,
    [CurrentYearBudgetDollars04] decimal NOT NULL,
    [CurrentYearBudgetDollars05] decimal NOT NULL,
    [CurrentYearBudgetDollars06] decimal NOT NULL,
    [CurrentYearBudgetDollars07] decimal NOT NULL,
    [CurrentYearBudgetDollars08] decimal NOT NULL,
    [CurrentYearBudgetDollars09] decimal NOT NULL,
    [CurrentYearBudgetDollars10] decimal NOT NULL,
    [CurrentYearBudgetDollars11] decimal NOT NULL,
    [CurrentYearBudgetDollars12] decimal NOT NULL,
    [CurrentYearBudgetDollarsTotal] decimal NULL,
    [ActualYTDHours01] decimal NOT NULL,
    [ActualYTDHours02] decimal NOT NULL,
    [ActualYTDHours03] decimal NOT NULL,
    [ActualYTDHours04] decimal NOT NULL,
    [ActualYTDHours05] decimal NOT NULL,
    [ActualYTDHours06] decimal NOT NULL,
    [ActualYTDHours07] decimal NOT NULL,
    [ActualYTDHours08] decimal NOT NULL,
    [ActualYTDHours09] decimal NOT NULL,
    [ActualYTDHours10] decimal NOT NULL,
    [ActualYTDHours11] decimal NOT NULL,
    [ActualYTDHours12] decimal NOT NULL,
    [ActualYTDHoursTotal] decimal NULL,
    [PriorYearActualHours01] decimal NOT NULL,
    [PriorYearActualHours02] decimal NOT NULL,
    [PriorYearActualHours03] decimal NOT NULL,
    [PriorYearActualHours04] decimal NOT NULL,
    [PriorYearActualHours05] decimal NOT NULL,
    [PriorYearActualHours06] decimal NOT NULL,
    [PriorYearActualHours07] decimal NOT NULL,
    [PriorYearActualHours08] decimal NOT NULL,
    [PriorYearActualHours09] decimal NOT NULL,
    [PriorYearActualHours10] decimal NOT NULL,
    [PriorYearActualHours11] decimal NOT NULL,
    [PriorYearActualHours12] decimal NOT NULL,
    [PriorYearActualHoursTotal] decimal NULL,
    [CurrentYearBudgetHours01] decimal NOT NULL,
    [CurrentYearBudgetHours02] decimal NOT NULL,
    [CurrentYearBudgetHours03] decimal NOT NULL,
    [CurrentYearBudgetHours04] decimal NOT NULL,
    [CurrentYearBudgetHours05] decimal NOT NULL,
    [CurrentYearBudgetHours06] decimal NOT NULL,
    [CurrentYearBudgetHours07] decimal NOT NULL,
    [CurrentYearBudgetHours08] decimal NOT NULL,
    [CurrentYearBudgetHours09] decimal NOT NULL,
    [CurrentYearBudgetHours10] decimal NOT NULL,
    [CurrentYearBudgetHours11] decimal NOT NULL,
    [CurrentYearBudgetHours12] decimal NOT NULL,
    [CurrentYearBudgetHoursTotal] decimal NULL,
    [ActualYTDFTEs01] decimal NOT NULL,
    [ActualYTDFTEs02] decimal NOT NULL,
    [ActualYTDFTEs03] decimal NOT NULL,
    [ActualYTDFTEs04] decimal NOT NULL,
    [ActualYTDFTEs05] decimal NOT NULL,
    [ActualYTDFTEs06] decimal NOT NULL,
    [ActualYTDFTEs07] decimal NOT NULL,
    [ActualYTDFTEs08] decimal NOT NULL,
    [ActualYTDFTEs09] decimal NOT NULL,
    [ActualYTDFTEs10] decimal NOT NULL,
    [ActualYTDFTEs11] decimal NOT NULL,
    [ActualYTDFTEs12] decimal NOT NULL,
    [ActualYTDFTEsTotal] decimal NOT NULL,
    [PriorYearActualFTEs01] decimal NOT NULL,
    [PriorYearActualFTEs02] decimal NOT NULL,
    [PriorYearActualFTEs03] decimal NOT NULL,
    [PriorYearActualFTEs04] decimal NOT NULL,
    [PriorYearActualFTEs05] decimal NOT NULL,
    [PriorYearActualFTEs06] decimal NOT NULL,
    [PriorYearActualFTEs07] decimal NOT NULL,
    [PriorYearActualFTEs08] decimal NOT NULL,
    [PriorYearActualFTEs09] decimal NOT NULL,
    [PriorYearActualFTEs10] decimal NOT NULL,
    [PriorYearActualFTEs11] decimal NOT NULL,
    [PriorYearActualFTEs12] decimal NOT NULL,
    [PriorYearActualFTEsTotal] decimal NOT NULL,
    [CurrentYearBudgetFTEs01] decimal NOT NULL,
    [CurrentYearBudgetFTEs02] decimal NOT NULL,
    [CurrentYearBudgetFTEs03] decimal NOT NULL,
    [CurrentYearBudgetFTEs04] decimal NOT NULL,
    [CurrentYearBudgetFTEs05] decimal NOT NULL,
    [CurrentYearBudgetFTEs06] decimal NOT NULL,
    [CurrentYearBudgetFTEs07] decimal NOT NULL,
    [CurrentYearBudgetFTEs08] decimal NOT NULL,
    [CurrentYearBudgetFTEs09] decimal NOT NULL,
    [CurrentYearBudgetFTEs10] decimal NOT NULL,
    [CurrentYearBudgetFTEs11] decimal NOT NULL,
    [CurrentYearBudgetFTEs12] decimal NOT NULL,
    [CurrentYearBudgetFTEsTotal] decimal NOT NULL,
    PRIMARY KEY ([StaffingID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[StaffingHistory] ([StaffingID]);
GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__000DEC03] DEFAULT ((0)) FOR [ActualYTDDollars12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0102103C] DEFAULT ((0)) FOR [PriorYearActualDollars01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__01F63475] DEFAULT ((0)) FOR [PriorYearActualDollars02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__02EA58AE] DEFAULT ((0)) FOR [PriorYearActualDollars03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__03DE7CE7] DEFAULT ((0)) FOR [PriorYearActualDollars04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__04D2A120] DEFAULT ((0)) FOR [PriorYearActualDollars05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__05C6C559] DEFAULT ((0)) FOR [PriorYearActualDollars06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__06BAE992] DEFAULT ((0)) FOR [PriorYearActualDollars07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__07AF0DCB] DEFAULT ((0)) FOR [PriorYearActualDollars08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__08A33204] DEFAULT ((0)) FOR [PriorYearActualDollars09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0997563D] DEFAULT ((0)) FOR [PriorYearActualDollars10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0A8B7A76] DEFAULT ((0)) FOR [PriorYearActualDollars11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0B7F9EAF] DEFAULT ((0)) FOR [PriorYearActualDollars12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0C73C2E8] DEFAULT ((0)) FOR [CurrentYearBudgetDollars01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0D67E721] DEFAULT ((0)) FOR [CurrentYearBudgetDollars02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0E5C0B5A] DEFAULT ((0)) FOR [CurrentYearBudgetDollars03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0F502F93] DEFAULT ((0)) FOR [CurrentYearBudgetDollars04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__104453CC] DEFAULT ((0)) FOR [CurrentYearBudgetDollars05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__11387805] DEFAULT ((0)) FOR [CurrentYearBudgetDollars06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__122C9C3E] DEFAULT ((0)) FOR [CurrentYearBudgetDollars07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__1320C077] DEFAULT ((0)) FOR [CurrentYearBudgetDollars08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__1414E4B0] DEFAULT ((0)) FOR [CurrentYearBudgetDollars09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__150908E9] DEFAULT ((0)) FOR [CurrentYearBudgetDollars10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__15FD2D22] DEFAULT ((0)) FOR [CurrentYearBudgetDollars11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__16F1515B] DEFAULT ((0)) FOR [CurrentYearBudgetDollars12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__17E57594] DEFAULT ((0)) FOR [ActualYTDHours01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__18D999CD] DEFAULT ((0)) FOR [ActualYTDHours02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__19CDBE06] DEFAULT ((0)) FOR [ActualYTDHours03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1AC1E23F] DEFAULT ((0)) FOR [ActualYTDHours04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1BB60678] DEFAULT ((0)) FOR [ActualYTDHours05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1CAA2AB1] DEFAULT ((0)) FOR [ActualYTDHours06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1D9E4EEA] DEFAULT ((0)) FOR [ActualYTDHours07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1E927323] DEFAULT ((0)) FOR [ActualYTDHours08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1F86975C] DEFAULT ((0)) FOR [ActualYTDHours09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__207ABB95] DEFAULT ((0)) FOR [ActualYTDHours10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__216EDFCE] DEFAULT ((0)) FOR [ActualYTDHours11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__22630407] DEFAULT ((0)) FOR [ActualYTDHours12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__23572840] DEFAULT ((0)) FOR [PriorYearActualHours01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__244B4C79] DEFAULT ((0)) FOR [PriorYearActualHours02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__253F70B2] DEFAULT ((0)) FOR [PriorYearActualHours03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__263394EB] DEFAULT ((0)) FOR [PriorYearActualHours04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2727B924] DEFAULT ((0)) FOR [PriorYearActualHours05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__281BDD5D] DEFAULT ((0)) FOR [PriorYearActualHours06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__29100196] DEFAULT ((0)) FOR [PriorYearActualHours07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2A0425CF] DEFAULT ((0)) FOR [PriorYearActualHours08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2AF84A08] DEFAULT ((0)) FOR [PriorYearActualHours09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2BEC6E41] DEFAULT ((0)) FOR [PriorYearActualHours10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2CE0927A] DEFAULT ((0)) FOR [PriorYearActualHours11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2DD4B6B3] DEFAULT ((0)) FOR [PriorYearActualHours12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__2EC8DAEC] DEFAULT ((0)) FOR [CurrentYearBudgetHours01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__2FBCFF25] DEFAULT ((0)) FOR [CurrentYearBudgetHours02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__30B1235E] DEFAULT ((0)) FOR [CurrentYearBudgetHours03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__31A54797] DEFAULT ((0)) FOR [CurrentYearBudgetHours04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__32996BD0] DEFAULT ((0)) FOR [CurrentYearBudgetHours05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__338D9009] DEFAULT ((0)) FOR [CurrentYearBudgetHours06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3481B442] DEFAULT ((0)) FOR [CurrentYearBudgetHours07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3575D87B] DEFAULT ((0)) FOR [CurrentYearBudgetHours08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3669FCB4] DEFAULT ((0)) FOR [CurrentYearBudgetHours09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__375E20ED] DEFAULT ((0)) FOR [CurrentYearBudgetHours10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__38524526] DEFAULT ((0)) FOR [CurrentYearBudgetHours11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3946695F] DEFAULT ((0)) FOR [CurrentYearBudgetHours12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3A3A8D98] DEFAULT ((0)) FOR [ActualYTDFTEs01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3B2EB1D1] DEFAULT ((0)) FOR [ActualYTDFTEs02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3C22D60A] DEFAULT ((0)) FOR [ActualYTDFTEs03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3D16FA43] DEFAULT ((0)) FOR [ActualYTDFTEs04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3E0B1E7C] DEFAULT ((0)) FOR [ActualYTDFTEs05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3EFF42B5] DEFAULT ((0)) FOR [ActualYTDFTEs06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3FF366EE] DEFAULT ((0)) FOR [ActualYTDFTEs07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__40E78B27] DEFAULT ((0)) FOR [ActualYTDFTEs08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__41DBAF60] DEFAULT ((0)) FOR [ActualYTDFTEs09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__42CFD399] DEFAULT ((0)) FOR [ActualYTDFTEs10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__43C3F7D2] DEFAULT ((0)) FOR [ActualYTDFTEs11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__44B81C0B] DEFAULT ((0)) FOR [ActualYTDFTEs12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__45AC4044] DEFAULT ((0)) FOR [ActualYTDFTEsTotal]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__46A0647D] DEFAULT ((0)) FOR [PriorYearActualFTEs01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__479488B6] DEFAULT ((0)) FOR [PriorYearActualFTEs02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4888ACEF] DEFAULT ((0)) FOR [PriorYearActualFTEs03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__497CD128] DEFAULT ((0)) FOR [PriorYearActualFTEs04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4A70F561] DEFAULT ((0)) FOR [PriorYearActualFTEs05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4B65199A] DEFAULT ((0)) FOR [PriorYearActualFTEs06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4C593DD3] DEFAULT ((0)) FOR [PriorYearActualFTEs07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4D4D620C] DEFAULT ((0)) FOR [PriorYearActualFTEs08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4E418645] DEFAULT ((0)) FOR [PriorYearActualFTEs09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4F35AA7E] DEFAULT ((0)) FOR [PriorYearActualFTEs10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__5029CEB7] DEFAULT ((0)) FOR [PriorYearActualFTEs11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__511DF2F0] DEFAULT ((0)) FOR [PriorYearActualFTEs12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__52121729] DEFAULT ((0)) FOR [PriorYearActualFTEsTotal]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__53063B62] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__53FA5F9B] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__54EE83D4] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__55E2A80D] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__56D6CC46] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__57CAF07F] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__58BF14B8] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__59B338F1] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5AA75D2A] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5B9B8163] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5C8FA59C] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs11]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5D83C9D5] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs12]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5E77EE0E] DEFAULT ((0)) FOR [CurrentYearBudgetFTEsTotal]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Staff__749C3957] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__75905D90] DEFAULT ((0)) FOR [ActualYTDDollars01]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__768481C9] DEFAULT ((0)) FOR [ActualYTDDollars02]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7778A602] DEFAULT ((0)) FOR [ActualYTDDollars03]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__786CCA3B] DEFAULT ((0)) FOR [ActualYTDDollars04]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7960EE74] DEFAULT ((0)) FOR [ActualYTDDollars05]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7A5512AD] DEFAULT ((0)) FOR [ActualYTDDollars06]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7B4936E6] DEFAULT ((0)) FOR [ActualYTDDollars07]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7C3D5B1F] DEFAULT ((0)) FOR [ActualYTDDollars08]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7D317F58] DEFAULT ((0)) FOR [ActualYTDDollars09]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7E25A391] DEFAULT ((0)) FOR [ActualYTDDollars10]; GO
ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7F19C7CA] DEFAULT ((0)) FOR [ActualYTDDollars11]; GO

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

---------------------------------------------
-- fp.StaffingInitialPlanConfigDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingInitialPlanConfigDetail] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [VersionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [FK__StaffingI__Budge__77ADB02C] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [FK__StaffingI__Versi__4C8F1354] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Versi__4B9AEF1B] DEFAULT ((0)) FOR [VersionID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Budge__686B6C9C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Budge__695F90D5] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Depar__6A53B50E] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__JobCo__6B47D947] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Produ__6C3BFD80] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__PayCo__6D3021B9] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Varia__6E2445F2] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__TimeC__6F186A2B] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__UnitT__700C8E64] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Emplo__7100B29D] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__71F4D6D6] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__72E8FB0F] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__73DD1F48] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__74D14381] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Proje__75C567BA] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Trail__76B98BF3] DEFAULT ((0)) FOR [TrailingMonths]; GO

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

---------------------------------------------
-- fp.StaffingInitialPlanConfigDetailHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingInitialPlanConfigDetailHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [VersionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK_Staffing_Budget_Config] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Budge__1F8762B3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Budge__207B86EC] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Depar__216FAB25] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__JobCo__2263CF5E] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Produ__2357F397] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__PayCo__244C17D0] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Varia__25403C09] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__TimeC__26346042] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__UnitT__2728847B] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Emplo__281CA8B4] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2910CCED] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2A04F126] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2AF9155F] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2BED3998] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Proje__2CE15DD1] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Trail__2DD5820A] DEFAULT ((0)) FOR [TrailingMonths]; GO
ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Versi__2EC9A643] DEFAULT ((0)) FOR [VersionID]; GO

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

---------------------------------------------
-- fp.StaffingManagerAdjustmentComment ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingManagerAdjustmentComment] (
    [CommentGUID] uniqueidentifier NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [UnitTypeID] int NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [InitialValue] decimal NOT NULL,
    [DeltaValue] decimal NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [EmployeeID] int NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [DateModifiedUtc] datetime NOT NULL,
    PRIMARY KEY ([CommentGUID])
);
GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Autho__00006B3C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Autho__00F48F75] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Emplo__07554406] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateC__35711471] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateM__366538AA] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__TimeC__4017F4BF] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Comme__739A9457] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Adjus__748EB890] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Budge__7582DCC9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Depar__76770102] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__JobCo__776B253B] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Fisca__7A4791E6] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__UnitT__7B3BB61F] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Comme__7C2FDA58] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Initi__7D23FE91] DEFAULT ((0)) FOR [InitialValue]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Delta__7E1822CA] DEFAULT ((0)) FOR [DeltaValue]; GO

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

---------------------------------------------
-- fp.StaffingManagerAdjustmentData ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingManagerAdjustmentData] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [EntityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FiscalYearID] int NOT NULL,
    [FiscalMonthID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value] decimal NULL,
    [EmployeeID] int NOT NULL,
    [IsSetZero] bit NOT NULL,
    [VariabilityID] int NOT NULL
);

CREATE NONCLUSTERED INDEX [NCNU_AdjustmentGUID] ON [fp].[StaffingManagerAdjustmentData] ([AdjustmentGUID]) INCLUDE ([DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], [EntityID], [Value], [TimeClassID], [EmployeeID]);
GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Emplo__06611FCD] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [Default_PRManagerAdj_UT] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [Default_PRManagerAdj_TC] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Varia__421184E1] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Adjus__66409939] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Depar__6734BD72] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__JobCo__6828E1AB] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__PayCo__691D05E4] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Produ__6A112A1D] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Entit__6B054E56] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Fisca__6DE1BB01] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Fisca__6ED5DF3A] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Value__70BE27AC] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__StaffingM__IsSet__7BE6BEB6] DEFAULT ((0)) FOR [IsSetZero]; GO

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

---------------------------------------------
-- fp.StaffingManagerSetAdjustmentComment ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingManagerSetAdjustmentComment] (
    [CommentID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FiscalYearID] int NOT NULL,
    [InitialValue] decimal NOT NULL,
    [Value] decimal NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [DateModifiedUtc] datetime NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AdjustedLevelInfoJSON] nvarchar(max) NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [TabVariabilityID] int NOT NULL,
    PRIMARY KEY ([CommentID])
);
GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_TimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Emplo__00373DDE] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__TimeC__012B6217] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__UnitT__021F8650] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Fisca__0313AA89] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Initi__0407CEC2] DEFAULT ((0)) FOR [InitialValue]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Value__04FBF2FB] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Autho__05F01734] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Autho__06E43B6D] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateC__07D85FA6] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateM__08CC83DF] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Comme__09C0A818] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Adjus__0AB4CC51] DEFAULT ('') FOR [AdjustedLevelInfoJSON]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Budge__3B5803AC] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__TabVa__3C4C27E5] DEFAULT ((0)) FOR [TabVariabilityID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Adjus__7B7288C1] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Depar__7D5AD133] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Varia__7E4EF56C] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__JobCo__7F4319A5] DEFAULT ((0)) FOR [JobCodeID]; GO

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

---------------------------------------------
-- fp.StaffingManagerSetAdjustmentData ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingManagerSetAdjustmentData] (
    [RowID] int NOT NULL,
    [AdjustmentID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [EntityID] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [FiscalYearID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_ProductiveClass] FOREIGN KEY ([ProductiveClassID]) REFERENCES [fw].[DimProductiveClass] ([ProductiveClassID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Adjus__4051C2F3] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Depar__4145E72C] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__JobCo__423A0B65] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__PayCo__432E2F9E] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Produ__442253D7] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Entit__45167810] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Emplo__460A9C49] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Varia__46FEC082] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__UnitT__47F2E4BB] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Fisca__48E708F4] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__TimeC__49DB2D2D] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4ACF5166] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4BC3759F] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4CB799D8] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4DABBE11] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4E9FE24A] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4F940683] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__50882ABC] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__517C4EF5] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__5270732E] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__53649767] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__5458BBA0] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__554CDFD9] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.StaffingMixAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingMixAdjustment] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [Value] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_BudgetConfig] ON [fp].[StaffingMixAdjustment] ([BudgetConfigID]);
GO
ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Adjus__2E64EF86] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Budge__2F5913BF] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Adjus__304D37F8] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Value__31415C31] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.StaffingSpreadUnlockData ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingSpreadUnlockData] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [ProductiveClassID] int NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Version] timestamp NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__IsRec__02BAAC1B] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Emplo__056CFB94] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Budge__115218DE] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Entit__133A6150] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Depar__142E8589] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__JobCo__1522A9C2] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__PayCo__1616CDFB] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Produ__170AF234] DEFAULT ((0)) FOR [ProductiveClassID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__UnitT__17FF166D] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__18F33AA6] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__19E75EDF] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1ADB8318] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1BCFA751] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1CC3CB8A] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1DB7EFC3] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1EAC13FC] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1FA03835] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__20945C6E] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__218880A7] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__227CA4E0] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__2370C919] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__3468ACF6] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__355CD12F] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__3650F568] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__374519A1] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [df_StaffingSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO

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

---------------------------------------------
-- fp.StaffingSpreads ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingSpreads] (
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [PayCodeGroupID] int NOT NULL,
    [IsInactive] bit NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [GlobalSpreadID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID])
);
GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_FpStaffingSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_FpStaffingSpreads_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_FpStaffingSpreads_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_StaffingSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__00C6AB5A] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__01BACF93] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__02AEF3CC] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__03A31805] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__04973C3E] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__058B6077] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__067F84B0] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__0773A8E9] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__0867CD22] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__095BF15B] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Total__0A501594] DEFAULT ((0)) FOR [TotalImportedValue]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Globa__17CA0C43] DEFAULT ((1)) FOR [GlobalSpreadID]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [df_StaffingSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Budge__773D4120] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Depar__78316559] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__JobCo__7A19ADCB] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__PayCo__7C01F63D] DEFAULT ((0)) FOR [PayCodeGroupID]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__IsIna__7DEA3EAF] DEFAULT ((0)) FOR [IsInactive]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__7EDE62E8] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__7FD28721] DEFAULT ((0)) FOR [SpreadPercentage02]; GO

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

---------------------------------------------
-- fp.StaffingSpreadsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingSpreadsChangeHistory] (
    [RowID] bigint NOT NULL,
    [StaffingID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    [UnitTypeID] smallint NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [OldValue01] decimal NOT NULL,
    [OldValue02] decimal NOT NULL,
    [OldValue03] decimal NOT NULL,
    [OldValue04] decimal NOT NULL,
    [OldValue05] decimal NOT NULL,
    [OldValue06] decimal NOT NULL,
    [OldValue07] decimal NOT NULL,
    [OldValue08] decimal NOT NULL,
    [OldValue09] decimal NOT NULL,
    [OldValue10] decimal NOT NULL,
    [OldValue11] decimal NOT NULL,
    [OldValue12] decimal NOT NULL,
    [NewValue01] decimal NOT NULL,
    [NewValue02] decimal NOT NULL,
    [NewValue03] decimal NOT NULL,
    [NewValue04] decimal NOT NULL,
    [NewValue05] decimal NOT NULL,
    [NewValue06] decimal NOT NULL,
    [NewValue07] decimal NOT NULL,
    [NewValue08] decimal NOT NULL,
    [NewValue09] decimal NOT NULL,
    [NewValue10] decimal NOT NULL,
    [NewValue11] decimal NOT NULL,
    [NewValue12] decimal NOT NULL
);

CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[StaffingSpreadsChangeHistory] ([BudgetConfigID], [SubsectionID], [StaffingID], [UnitTypeID], [RowID]);
GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__Staff__3BEDCBE0] DEFAULT ((0)) FOR [StaffingID]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__Budge__3CE1F019] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__Subse__3DD61452] DEFAULT ((3)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__UnitT__3ECA388B] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__DateC__3FBE5CC4] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__40B280FD] DEFAULT ((0)) FOR [OldValue01]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__41A6A536] DEFAULT ((0)) FOR [OldValue02]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__429AC96F] DEFAULT ((0)) FOR [OldValue03]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__438EEDA8] DEFAULT ((0)) FOR [OldValue04]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__448311E1] DEFAULT ((0)) FOR [OldValue05]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4577361A] DEFAULT ((0)) FOR [OldValue06]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__466B5A53] DEFAULT ((0)) FOR [OldValue07]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__475F7E8C] DEFAULT ((0)) FOR [OldValue08]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4853A2C5] DEFAULT ((0)) FOR [OldValue09]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4947C6FE] DEFAULT ((0)) FOR [OldValue10]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4A3BEB37] DEFAULT ((0)) FOR [OldValue11]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4B300F70] DEFAULT ((0)) FOR [OldValue12]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4C2433A9] DEFAULT ((0)) FOR [NewValue01]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4D1857E2] DEFAULT ((0)) FOR [NewValue02]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4E0C7C1B] DEFAULT ((0)) FOR [NewValue03]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4F00A054] DEFAULT ((0)) FOR [NewValue04]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4FF4C48D] DEFAULT ((0)) FOR [NewValue05]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__50E8E8C6] DEFAULT ((0)) FOR [NewValue06]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__51DD0CFF] DEFAULT ((0)) FOR [NewValue07]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__52D13138] DEFAULT ((0)) FOR [NewValue08]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__53C55571] DEFAULT ((0)) FOR [NewValue09]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__54B979AA] DEFAULT ((0)) FOR [NewValue10]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__55AD9DE3] DEFAULT ((0)) FOR [NewValue11]; GO
ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__56A1C21C] DEFAULT ((0)) FOR [NewValue12]; GO

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

---------------------------------------------
-- fp.StaffingVariabilityOverrideConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingVariabilityOverrideConfig] (
    [RowID] int NOT NULL,
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [JobCodeID] int NOT NULL,
    [Variability] decimal NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID], [JobCodeID])
);
GO
ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [FK_StaffingVariabilityOverrideConfig_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO
ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [DF__StaffingV__Depar__35B27077] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [DF__StaffingV__JobCo__36A694B0] DEFAULT ((0)) FOR [JobCodeID]; GO
ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [DF__StaffingV__Varia__379AB8E9] DEFAULT ((0)) FOR [Variability]; GO
ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [df_StaffingVariabilityOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO

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

---------------------------------------------
-- fp.StaffingWageRate ------------------
---------------------------------------------
CREATE TABLE [fp].[StaffingWageRate] (
    [StaffingWageRateID] int NOT NULL,
    [BudgetWageRateLockType] tinyint NOT NULL,
    [BudgetWageRateLockFlag] tinyint NOT NULL,
    [TargetWageRateLockType] tinyint NOT NULL,
    [TargetWageRateLockFlag] tinyint NOT NULL,
    [ProjectionWageRateLockType] tinyint NOT NULL,
    [ProjectionWageRateLockFlag] tinyint NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [TargetAdjusted01] decimal NOT NULL,
    [TargetAdjusted02] decimal NOT NULL,
    [TargetAdjusted03] decimal NOT NULL,
    [TargetAdjusted04] decimal NOT NULL,
    [TargetAdjusted05] decimal NOT NULL,
    [TargetAdjusted06] decimal NOT NULL,
    [TargetAdjusted07] decimal NOT NULL,
    [TargetAdjusted08] decimal NOT NULL,
    [TargetAdjusted09] decimal NOT NULL,
    [TargetAdjusted10] decimal NOT NULL,
    [TargetAdjusted11] decimal NOT NULL,
    [TargetAdjusted12] decimal NOT NULL,
    [BudgetAdjusted01] decimal NOT NULL,
    [BudgetAdjusted02] decimal NOT NULL,
    [BudgetAdjusted03] decimal NOT NULL,
    [BudgetAdjusted04] decimal NOT NULL,
    [BudgetAdjusted05] decimal NOT NULL,
    [BudgetAdjusted06] decimal NOT NULL,
    [BudgetAdjusted07] decimal NOT NULL,
    [BudgetAdjusted08] decimal NOT NULL,
    [BudgetAdjusted09] decimal NOT NULL,
    [BudgetAdjusted10] decimal NOT NULL,
    [BudgetAdjusted11] decimal NOT NULL,
    [BudgetAdjusted12] decimal NOT NULL,
    [ProjectionAdjusted01] decimal NOT NULL,
    [ProjectionAdjusted02] decimal NOT NULL,
    [ProjectionAdjusted03] decimal NOT NULL,
    [ProjectionAdjusted04] decimal NOT NULL,
    [ProjectionAdjusted05] decimal NOT NULL,
    [ProjectionAdjusted06] decimal NOT NULL,
    [ProjectionAdjusted07] decimal NOT NULL,
    [ProjectionAdjusted08] decimal NOT NULL,
    [ProjectionAdjusted09] decimal NOT NULL,
    [ProjectionAdjusted10] decimal NOT NULL,
    [ProjectionAdjusted11] decimal NOT NULL,
    [ProjectionAdjusted12] decimal NOT NULL,
    [TargetPercentAdjustmentFactor01] decimal NOT NULL,
    [TargetPercentAdjustmentFactor02] decimal NOT NULL,
    [TargetPercentAdjustmentFactor03] decimal NOT NULL,
    [TargetPercentAdjustmentFactor04] decimal NOT NULL,
    [TargetPercentAdjustmentFactor05] decimal NOT NULL,
    [TargetPercentAdjustmentFactor06] decimal NOT NULL,
    [TargetPercentAdjustmentFactor07] decimal NOT NULL,
    [TargetPercentAdjustmentFactor08] decimal NOT NULL,
    [TargetPercentAdjustmentFactor09] decimal NOT NULL,
    [TargetPercentAdjustmentFactor10] decimal NOT NULL,
    [TargetPercentAdjustmentFactor11] decimal NOT NULL,
    [TargetPercentAdjustmentFactor12] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor01] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor02] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor03] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor04] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor05] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor06] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor07] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor08] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor09] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor10] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor11] decimal NOT NULL,
    [BudgetPercentAdjustmentFactor12] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor01] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor02] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor03] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor04] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor05] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor06] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor07] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor08] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor09] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor10] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor11] decimal NOT NULL,
    [ProjectionPercentAdjustmentFactor12] decimal NOT NULL,
    PRIMARY KEY ([StaffingWageRateID])
);
GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__15BD3600] DEFAULT ((0)) FOR [BudgetWageRateLockType]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__16B15A39] DEFAULT ((0)) FOR [BudgetWageRateLockFlag]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__17A57E72] DEFAULT ((0)) FOR [TargetWageRateLockType]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__1899A2AB] DEFAULT ((0)) FOR [TargetWageRateLockFlag]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__198DC6E4] DEFAULT ((0)) FOR [ProjectionWageRateLockType]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__1A81EB1D] DEFAULT ((0)) FOR [ProjectionWageRateLockFlag]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1B760F56] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1C6A338F] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1D5E57C8] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1E527C01] DEFAULT ((0)) FOR [SampledBudget04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1F46A03A] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__203AC473] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__212EE8AC] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__22230CE5] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2317311E] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__240B5557] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__24FF7990] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__25F39DC9] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__26E7C202] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__27DBE63B] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__28D00A74] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__29C42EAD] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2AB852E6] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2BAC771F] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2CA09B58] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2D94BF91] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2E88E3CA] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2F7D0803] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__30712C3C] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__31655075] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__325974AE] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__334D98E7] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3441BD20] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3535E159] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__362A0592] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__371E29CB] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__38124E04] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3906723D] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__39FA9676] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3AEEBAAF] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3BE2DEE8] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3CD70321] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3DCB275A] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3EBF4B93] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3FB36FCC] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__40A79405] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__419BB83E] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__428FDC77] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__438400B0] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__447824E9] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__456C4922] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__46606D5B] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__47549194] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__4848B5CD] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__493CDA06] DEFAULT ((0)) FOR [TargetAdjusted01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4A30FE3F] DEFAULT ((0)) FOR [TargetAdjusted02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4B252278] DEFAULT ((0)) FOR [TargetAdjusted03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4C1946B1] DEFAULT ((0)) FOR [TargetAdjusted04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4D0D6AEA] DEFAULT ((0)) FOR [TargetAdjusted05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4E018F23] DEFAULT ((0)) FOR [TargetAdjusted06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4EF5B35C] DEFAULT ((0)) FOR [TargetAdjusted07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4FE9D795] DEFAULT ((0)) FOR [TargetAdjusted08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__50DDFBCE] DEFAULT ((0)) FOR [TargetAdjusted09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__51D22007] DEFAULT ((0)) FOR [TargetAdjusted10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__52C64440] DEFAULT ((0)) FOR [TargetAdjusted11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__53BA6879] DEFAULT ((0)) FOR [TargetAdjusted12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__54AE8CB2] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__55A2B0EB] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5696D524] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__578AF95D] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__587F1D96] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__597341CF] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5A676608] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5B5B8A41] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5C4FAE7A] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5D43D2B3] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5E37F6EC] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5F2C1B25] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__60203F5E] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__61146397] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__620887D0] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__62FCAC09] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__63F0D042] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__64E4F47B] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__65D918B4] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__66CD3CED] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__67C16126] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__68B5855F] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__69A9A998] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO
ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__6A9DCDD1] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO

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

---------------------------------------------
-- fp.StatisticAddProviderAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticAddProviderAdjustment] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [SubsectionID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [FK_FpStatisticAddProviderAdjustment_AdjustmentGuid] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[StatisticsAdjustment] ([AdjustmentGUID]); GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Finan__009FBB84] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Payor__0193DFBD] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Patie__028803F6] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__037C282F] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__04704C68] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__056470A1] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__065894DA] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__TimeC__074CB913] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Budge__0840DD4C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Subse__09350185] DEFAULT ((0)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__IsRec__0A2925BE] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0B1D49F7] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0C116E30] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0D059269] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0DF9B6A2] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0EEDDADB] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0FE1FF14] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__10D6234D] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__11CA4786] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__12BE6BBF] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__13B28FF8] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__14A6B431] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__159AD86A] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Budge__7BDB0667] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__7CCF2AA0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Entit__7DC34ED9] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Depar__7EB77312] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Accou__7FAB974B] DEFAULT ((0)) FOR [AccountID]; GO

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

---------------------------------------------
-- fp.StatisticAddProviderSummary ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticAddProviderSummary] (
    [SummaryID] int NOT NULL,
    [DriverAdjustmentGUID] uniqueidentifier NOT NULL,
    [DependentAdjustmentGUID] uniqueidentifier NOT NULL,
    [EmployeeType] int NOT NULL,
    [EmployeeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [SpecialtyID] int NOT NULL,
    [StartDate] datetime2 NOT NULL,
    [BenchmarkProvidersJSON] varchar(1000) NOT NULL,
    [Comment] varchar(1000) NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [StaffingAdjustmentGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([SummaryID])
);
GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [FK_FP_StatAddProviderSummary_DriverAdjustmentGUID] FOREIGN KEY ([DriverAdjustmentGUID]) REFERENCES [fp].[StatisticsAdjustment] ([AdjustmentGUID]); GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [FK_FP_StatAddProviderSummary_EmployeeID] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [FK_FP_StatAddProviderSummary_ProviderID] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Staff__0CA73664] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StaffingAdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Drive__713E47BA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DriverAdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Depen__72326BF3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DependentAdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Emplo__7326902C] DEFAULT ((0)) FOR [EmployeeType]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Emplo__741AB465] DEFAULT ((0)) FOR [EmployeeID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Provi__750ED89E] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Provi__7602FCD7] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Speci__76F72110] DEFAULT ((0)) FOR [SpecialtyID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Start__77EB4549] DEFAULT (getdate()) FOR [StartDate]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Bench__78DF6982] DEFAULT ('') FOR [BenchmarkProvidersJSON]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Comme__79D38DBB] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Class__7AC7B1F4] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Class__7BBBD62D] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO

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

---------------------------------------------
-- fp.StatisticAddProviderSummaryDetails ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticAddProviderSummaryDetails] (
    [RowID] int NOT NULL,
    [SummaryID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [ProjectionImpact] decimal NOT NULL,
    [BudgetImpact] decimal NOT NULL,
    [TargetImpact] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [FK_FP_StatisticAddProviderSummaryDetails_SummaryID] FOREIGN KEY ([SummaryID]) REFERENCES [fp].[StatisticAddProviderSummary] ([SummaryID]); GO
ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Summa__0174AF83] DEFAULT ((0)) FOR [SummaryID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Provi__0268D3BC] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Depar__035CF7F5] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Proje__04511C2E] DEFAULT ((0)) FOR [ProjectionImpact]; GO
ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Budge__05454067] DEFAULT ((0)) FOR [BudgetImpact]; GO
ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF_StatisticAddProviderSummaryDetails_TargetImpact] DEFAULT ((0)) FOR [TargetImpact]; GO

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

---------------------------------------------
-- fp.Statistics ------------------
---------------------------------------------
CREATE TABLE [fp].[Statistics] (
    [StatisticsID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityGroupConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [AddDate] datetime NOT NULL,
    [IsNew] bit NOT NULL,
    [SubsectionID] int NOT NULL,
    [BudgetLockType] tinyint NOT NULL,
    [BudgetLockFlag] tinyint NOT NULL,
    [TargetLockType] tinyint NOT NULL,
    [TargetLockFlag] tinyint NOT NULL,
    [ProjectionLockType] tinyint NOT NULL,
    [ProjectionLockFlag] tinyint NOT NULL,
    [SampledBudgetTotal] decimal NOT NULL,
    [SampledProjectionTotal] decimal NOT NULL,
    [InitialBudgetTotal] decimal NOT NULL,
    [InitialProjectionTotal] decimal NOT NULL,
    [BudgetAdjustedTotal] decimal NOT NULL,
    [TargetAdjustedTotal] decimal NOT NULL,
    [ProjectionAdjustedTotal] decimal NOT NULL,
    [SampledBudget01] decimal NOT NULL,
    [SampledBudget02] decimal NOT NULL,
    [SampledBudget03] decimal NOT NULL,
    [SampledBudget04] decimal NOT NULL,
    [SampledBudget05] decimal NOT NULL,
    [SampledBudget06] decimal NOT NULL,
    [SampledBudget07] decimal NOT NULL,
    [SampledBudget08] decimal NOT NULL,
    [SampledBudget09] decimal NOT NULL,
    [SampledBudget10] decimal NOT NULL,
    [SampledBudget11] decimal NOT NULL,
    [SampledBudget12] decimal NOT NULL,
    [SampledProjection01] decimal NOT NULL,
    [SampledProjection02] decimal NOT NULL,
    [SampledProjection03] decimal NOT NULL,
    [SampledProjection04] decimal NOT NULL,
    [SampledProjection05] decimal NOT NULL,
    [SampledProjection06] decimal NOT NULL,
    [SampledProjection07] decimal NOT NULL,
    [SampledProjection08] decimal NOT NULL,
    [SampledProjection09] decimal NOT NULL,
    [SampledProjection10] decimal NOT NULL,
    [SampledProjection11] decimal NOT NULL,
    [SampledProjection12] decimal NOT NULL,
    [InitialBudget01] decimal NOT NULL,
    [InitialBudget02] decimal NOT NULL,
    [InitialBudget03] decimal NOT NULL,
    [InitialBudget04] decimal NOT NULL,
    [InitialBudget05] decimal NOT NULL,
    [InitialBudget06] decimal NOT NULL,
    [InitialBudget07] decimal NOT NULL,
    [InitialBudget08] decimal NOT NULL,
    [InitialBudget09] decimal NOT NULL,
    [InitialBudget10] decimal NOT NULL,
    [InitialBudget11] decimal NOT NULL,
    [InitialBudget12] decimal NOT NULL,
    [InitialProjection01] decimal NOT NULL,
    [InitialProjection02] decimal NOT NULL,
    [InitialProjection03] decimal NOT NULL,
    [InitialProjection04] decimal NOT NULL,
    [InitialProjection05] decimal NOT NULL,
    [InitialProjection06] decimal NOT NULL,
    [InitialProjection07] decimal NOT NULL,
    [InitialProjection08] decimal NOT NULL,
    [InitialProjection09] decimal NOT NULL,
    [InitialProjection10] decimal NOT NULL,
    [InitialProjection11] decimal NOT NULL,
    [InitialProjection12] decimal NOT NULL,
    [InitialBudgetRate01] decimal NOT NULL,
    [InitialBudgetRate02] decimal NOT NULL,
    [InitialBudgetRate03] decimal NOT NULL,
    [InitialBudgetRate04] decimal NOT NULL,
    [InitialBudgetRate05] decimal NOT NULL,
    [InitialBudgetRate06] decimal NOT NULL,
    [InitialBudgetRate07] decimal NOT NULL,
    [InitialBudgetRate08] decimal NOT NULL,
    [InitialBudgetRate09] decimal NOT NULL,
    [InitialBudgetRate10] decimal NOT NULL,
    [InitialBudgetRate11] decimal NOT NULL,
    [InitialBudgetRate12] decimal NOT NULL,
    [InitialProjectionRate01] decimal NOT NULL,
    [InitialProjectionRate02] decimal NOT NULL,
    [InitialProjectionRate03] decimal NOT NULL,
    [InitialProjectionRate04] decimal NOT NULL,
    [InitialProjectionRate05] decimal NOT NULL,
    [InitialProjectionRate06] decimal NOT NULL,
    [InitialProjectionRate07] decimal NOT NULL,
    [InitialProjectionRate08] decimal NOT NULL,
    [InitialProjectionRate09] decimal NOT NULL,
    [InitialProjectionRate10] decimal NOT NULL,
    [InitialProjectionRate11] decimal NOT NULL,
    [InitialProjectionRate12] decimal NOT NULL,
    [BudgetAdjusted01] decimal NOT NULL,
    [BudgetAdjusted02] decimal NOT NULL,
    [BudgetAdjusted03] decimal NOT NULL,
    [BudgetAdjusted04] decimal NOT NULL,
    [BudgetAdjusted05] decimal NOT NULL,
    [BudgetAdjusted06] decimal NOT NULL,
    [BudgetAdjusted07] decimal NOT NULL,
    [BudgetAdjusted08] decimal NOT NULL,
    [BudgetAdjusted09] decimal NOT NULL,
    [BudgetAdjusted10] decimal NOT NULL,
    [BudgetAdjusted11] decimal NOT NULL,
    [BudgetAdjusted12] decimal NOT NULL,
    [TargetAdjusted01] decimal NOT NULL,
    [TargetAdjusted02] decimal NOT NULL,
    [TargetAdjusted03] decimal NOT NULL,
    [TargetAdjusted04] decimal NOT NULL,
    [TargetAdjusted05] decimal NOT NULL,
    [TargetAdjusted06] decimal NOT NULL,
    [TargetAdjusted07] decimal NOT NULL,
    [TargetAdjusted08] decimal NOT NULL,
    [TargetAdjusted09] decimal NOT NULL,
    [TargetAdjusted10] decimal NOT NULL,
    [TargetAdjusted11] decimal NOT NULL,
    [TargetAdjusted12] decimal NOT NULL,
    [BudgetRateAdjusted01] decimal NOT NULL,
    [BudgetRateAdjusted02] decimal NOT NULL,
    [BudgetRateAdjusted03] decimal NOT NULL,
    [BudgetRateAdjusted04] decimal NOT NULL,
    [BudgetRateAdjusted05] decimal NOT NULL,
    [BudgetRateAdjusted06] decimal NOT NULL,
    [BudgetRateAdjusted07] decimal NOT NULL,
    [BudgetRateAdjusted08] decimal NOT NULL,
    [BudgetRateAdjusted09] decimal NOT NULL,
    [BudgetRateAdjusted10] decimal NOT NULL,
    [BudgetRateAdjusted11] decimal NOT NULL,
    [BudgetRateAdjusted12] decimal NOT NULL,
    [TargetRateAdjusted01] decimal NOT NULL,
    [TargetRateAdjusted02] decimal NOT NULL,
    [TargetRateAdjusted03] decimal NOT NULL,
    [TargetRateAdjusted04] decimal NOT NULL,
    [TargetRateAdjusted05] decimal NOT NULL,
    [TargetRateAdjusted06] decimal NOT NULL,
    [TargetRateAdjusted07] decimal NOT NULL,
    [TargetRateAdjusted08] decimal NOT NULL,
    [TargetRateAdjusted09] decimal NOT NULL,
    [TargetRateAdjusted10] decimal NOT NULL,
    [TargetRateAdjusted11] decimal NOT NULL,
    [TargetRateAdjusted12] decimal NOT NULL,
    [ProjectionAdjusted01] decimal NOT NULL,
    [ProjectionAdjusted02] decimal NOT NULL,
    [ProjectionAdjusted03] decimal NOT NULL,
    [ProjectionAdjusted04] decimal NOT NULL,
    [ProjectionAdjusted05] decimal NOT NULL,
    [ProjectionAdjusted06] decimal NOT NULL,
    [ProjectionAdjusted07] decimal NOT NULL,
    [ProjectionAdjusted08] decimal NOT NULL,
    [ProjectionAdjusted09] decimal NOT NULL,
    [ProjectionAdjusted10] decimal NOT NULL,
    [ProjectionAdjusted11] decimal NOT NULL,
    [ProjectionAdjusted12] decimal NOT NULL,
    [ProjectionRateAdjusted01] decimal NOT NULL,
    [ProjectionRateAdjusted02] decimal NOT NULL,
    [ProjectionRateAdjusted03] decimal NOT NULL,
    [ProjectionRateAdjusted04] decimal NOT NULL,
    [ProjectionRateAdjusted05] decimal NOT NULL,
    [ProjectionRateAdjusted06] decimal NOT NULL,
    [ProjectionRateAdjusted07] decimal NOT NULL,
    [ProjectionRateAdjusted08] decimal NOT NULL,
    [ProjectionRateAdjusted09] decimal NOT NULL,
    [ProjectionRateAdjusted10] decimal NOT NULL,
    [ProjectionRateAdjusted11] decimal NOT NULL,
    [ProjectionRateAdjusted12] decimal NOT NULL,
    PRIMARY KEY ([StatisticsID])
);

CREATE NONCLUSTERED INDEX [IX_Statistics_Account] ON [fp].[Statistics] ([AccountID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [PayorID], [PatientClassID]);
CREATE NONCLUSTERED INDEX [IX_Statistics_BudgetConfig] ON [fp].[Statistics] ([BudgetConfigID]) INCLUDE ([StatisticsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID]);
CREATE NONCLUSTERED INDEX [IX_Statistics_Department] ON [fp].[Statistics] ([DepartmentID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID]);
CREATE NONCLUSTERED INDEX [IX_Statistics_Entity] ON [fp].[Statistics] ([EntityID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID]);
CREATE NONCLUSTERED INDEX [IX_Statistics_FinancialReporting] ON [fp].[Statistics] ([FinancialReportingID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [PayorID], [PatientClassID]);
CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[Statistics] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PatientClassID], [PayorID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID]);
GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__00425CA0] DEFAULT ((0)) FOR [ProjectionRateAdjusted07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__007766CA] DEFAULT ((0)) FOR [SampledBudget05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__013680D9] DEFAULT ((0)) FOR [ProjectionRateAdjusted08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__016B8B03] DEFAULT ((0)) FOR [SampledBudget06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__022AA512] DEFAULT ((0)) FOR [ProjectionRateAdjusted09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__025FAF3C] DEFAULT ((0)) FOR [SampledBudget07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__031EC94B] DEFAULT ((0)) FOR [ProjectionRateAdjusted10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0353D375] DEFAULT ((0)) FOR [SampledBudget08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__0412ED84] DEFAULT ((0)) FOR [ProjectionRateAdjusted11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0447F7AE] DEFAULT ((0)) FOR [SampledBudget09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__050711BD] DEFAULT ((0)) FOR [ProjectionRateAdjusted12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__053C1BE7] DEFAULT ((0)) FOR [SampledBudget10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__06304020] DEFAULT ((0)) FOR [SampledBudget11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__07246459] DEFAULT ((0)) FOR [SampledBudget12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__08188892] DEFAULT ((0)) FOR [SampledProjection01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__090CACCB] DEFAULT ((0)) FOR [SampledProjection02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0A00D104] DEFAULT ((0)) FOR [SampledProjection03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0AF4F53D] DEFAULT ((0)) FOR [SampledProjection04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0BE91976] DEFAULT ((0)) FOR [SampledProjection05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0CDD3DAF] DEFAULT ((0)) FOR [SampledProjection06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0DD161E8] DEFAULT ((0)) FOR [SampledProjection07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0EC58621] DEFAULT ((0)) FOR [SampledProjection08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0FB9AA5A] DEFAULT ((0)) FOR [SampledProjection09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__10ADCE93] DEFAULT ((0)) FOR [SampledProjection10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__11A1F2CC] DEFAULT ((0)) FOR [SampledProjection11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__12961705] DEFAULT ((0)) FOR [SampledProjection12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__138A3B3E] DEFAULT ((0)) FOR [InitialBudget01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__147E5F77] DEFAULT ((0)) FOR [InitialBudget02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__157283B0] DEFAULT ((0)) FOR [InitialBudget03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1666A7E9] DEFAULT ((0)) FOR [InitialBudget04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__175ACC22] DEFAULT ((0)) FOR [InitialBudget05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__184EF05B] DEFAULT ((0)) FOR [InitialBudget06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__19431494] DEFAULT ((0)) FOR [InitialBudget07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1A3738CD] DEFAULT ((0)) FOR [InitialBudget08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1B2B5D06] DEFAULT ((0)) FOR [InitialBudget09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1C1F813F] DEFAULT ((0)) FOR [InitialBudget10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1D13A578] DEFAULT ((0)) FOR [InitialBudget11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1E07C9B1] DEFAULT ((0)) FOR [InitialBudget12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1EFBEDEA] DEFAULT ((0)) FOR [InitialProjection01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1FF01223] DEFAULT ((0)) FOR [InitialProjection02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__20E4365C] DEFAULT ((0)) FOR [InitialProjection03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__21D85A95] DEFAULT ((0)) FOR [InitialProjection04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__22CC7ECE] DEFAULT ((0)) FOR [InitialProjection05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__23C0A307] DEFAULT ((0)) FOR [InitialProjection06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__24B4C740] DEFAULT ((0)) FOR [InitialProjection07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__25A8EB79] DEFAULT ((0)) FOR [InitialProjection08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__269D0FB2] DEFAULT ((0)) FOR [InitialProjection09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__279133EB] DEFAULT ((0)) FOR [InitialProjection10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__28855824] DEFAULT ((0)) FOR [InitialProjection11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__29797C5D] DEFAULT ((0)) FOR [InitialProjection12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2A6DA096] DEFAULT ((0)) FOR [InitialBudgetRate01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2B61C4CF] DEFAULT ((0)) FOR [InitialBudgetRate02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2C55E908] DEFAULT ((0)) FOR [InitialBudgetRate03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2D4A0D41] DEFAULT ((0)) FOR [InitialBudgetRate04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2E3E317A] DEFAULT ((0)) FOR [InitialBudgetRate05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2F3255B3] DEFAULT ((0)) FOR [InitialBudgetRate06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__302679EC] DEFAULT ((0)) FOR [InitialBudgetRate07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__311A9E25] DEFAULT ((0)) FOR [InitialBudgetRate08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__320EC25E] DEFAULT ((0)) FOR [InitialBudgetRate09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3302E697] DEFAULT ((0)) FOR [InitialBudgetRate10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__33F70AD0] DEFAULT ((0)) FOR [InitialBudgetRate11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__34EB2F09] DEFAULT ((0)) FOR [InitialBudgetRate12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__35DF5342] DEFAULT ((0)) FOR [InitialProjectionRate01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__36D3777B] DEFAULT ((0)) FOR [InitialProjectionRate02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__37C79BB4] DEFAULT ((0)) FOR [InitialProjectionRate03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__38BBBFED] DEFAULT ((0)) FOR [InitialProjectionRate04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__39AFE426] DEFAULT ((0)) FOR [InitialProjectionRate05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3AA4085F] DEFAULT ((0)) FOR [InitialProjectionRate06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3B982C98] DEFAULT ((0)) FOR [InitialProjectionRate07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3C8C50D1] DEFAULT ((0)) FOR [InitialProjectionRate08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3D80750A] DEFAULT ((0)) FOR [InitialProjectionRate09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3E749943] DEFAULT ((0)) FOR [InitialProjectionRate10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3F68BD7C] DEFAULT ((0)) FOR [InitialProjectionRate11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__405CE1B5] DEFAULT ((0)) FOR [InitialProjectionRate12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__415105EE] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__42452A27] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__43394E60] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__442D7299] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__452196D2] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4615BB0B] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4709DF44] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__47FE037D] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__48F227B6] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__49E64BEF] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4ADA7028] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4BCE9461] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4CC2B89A] DEFAULT ((0)) FOR [TargetAdjusted01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4DB6DCD3] DEFAULT ((0)) FOR [TargetAdjusted02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4EAB010C] DEFAULT ((0)) FOR [TargetAdjusted03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4F9F2545] DEFAULT ((0)) FOR [TargetAdjusted04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5093497E] DEFAULT ((0)) FOR [TargetAdjusted05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__51876DB7] DEFAULT ((0)) FOR [TargetAdjusted06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__527B91F0] DEFAULT ((0)) FOR [TargetAdjusted07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__536FB629] DEFAULT ((0)) FOR [TargetAdjusted08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5463DA62] DEFAULT ((0)) FOR [TargetAdjusted09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5557FE9B] DEFAULT ((0)) FOR [TargetAdjusted10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__564C22D4] DEFAULT ((0)) FOR [TargetAdjusted11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5740470D] DEFAULT ((0)) FOR [TargetAdjusted12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__58346B46] DEFAULT ((0)) FOR [BudgetRateAdjusted01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__59288F7F] DEFAULT ((0)) FOR [BudgetRateAdjusted02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5A1CB3B8] DEFAULT ((0)) FOR [BudgetRateAdjusted03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5B10D7F1] DEFAULT ((0)) FOR [BudgetRateAdjusted04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5C04FC2A] DEFAULT ((0)) FOR [BudgetRateAdjusted05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5CF92063] DEFAULT ((0)) FOR [BudgetRateAdjusted06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5DED449C] DEFAULT ((0)) FOR [BudgetRateAdjusted07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5EE168D5] DEFAULT ((0)) FOR [BudgetRateAdjusted08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5FD58D0E] DEFAULT ((0)) FOR [BudgetRateAdjusted09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__60C9B147] DEFAULT ((0)) FOR [BudgetRateAdjusted10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__61BDD580] DEFAULT ((0)) FOR [BudgetRateAdjusted11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__62B1F9B9] DEFAULT ((0)) FOR [BudgetRateAdjusted12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__63A61DF2] DEFAULT ((0)) FOR [TargetRateAdjusted01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__649A422B] DEFAULT ((0)) FOR [TargetRateAdjusted02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__658E6664] DEFAULT ((0)) FOR [TargetRateAdjusted03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__66828A9D] DEFAULT ((0)) FOR [TargetRateAdjusted04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6776AED6] DEFAULT ((0)) FOR [TargetRateAdjusted05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__686AD30F] DEFAULT ((0)) FOR [TargetRateAdjusted06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__689FDD39] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__695EF748] DEFAULT ((0)) FOR [TargetRateAdjusted07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Entit__69940172] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6A531B81] DEFAULT ((0)) FOR [TargetRateAdjusted08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Entit__6A8825AB] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6B473FBA] DEFAULT ((0)) FOR [TargetRateAdjusted09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Depar__6B7C49E4] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6C3B63F3] DEFAULT ((0)) FOR [TargetRateAdjusted10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Accou__6C706E1D] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6D2F882C] DEFAULT ((0)) FOR [TargetRateAdjusted11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Finan__6D649256] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6E23AC65] DEFAULT ((0)) FOR [TargetRateAdjusted12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Payor__6E58B68F] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__6F17D09E] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Patie__6F4CDAC8] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__700BF4D7] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__7040FF01] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__71001910] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__7135233A] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__71F43D49] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__72294773] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__72E86182] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__731D6BAC] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__73DC85BB] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__AddDa__74118FE5] DEFAULT (getdate()) FOR [AddDate]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__74D0A9F4] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__IsNew__7505B41E] DEFAULT ((0)) FOR [IsNew]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__75C4CE2D] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [df_Stats_SubsectionID] DEFAULT ('1') FOR [SubsectionID]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__76B8F266] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__76EDFC90] DEFAULT ((0)) FOR [BudgetLockType]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__77AD169F] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__77E220C9] DEFAULT ((0)) FOR [BudgetLockFlag]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__78A13AD8] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__78D64502] DEFAULT ((0)) FOR [TargetLockType]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__79955F11] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__79CA693B] DEFAULT ((0)) FOR [TargetLockFlag]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7A89834A] DEFAULT ((0)) FOR [ProjectionRateAdjusted01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7ABE8D74] DEFAULT ((0)) FOR [ProjectionLockType]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7B7DA783] DEFAULT ((0)) FOR [ProjectionRateAdjusted02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7BB2B1AD] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7C71CBBC] DEFAULT ((0)) FOR [ProjectionRateAdjusted03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7CA6D5E6] DEFAULT ((0)) FOR [SampledBudget01]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7D65EFF5] DEFAULT ((0)) FOR [ProjectionRateAdjusted04]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7D9AFA1F] DEFAULT ((0)) FOR [SampledBudget02]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7E5A142E] DEFAULT ((0)) FOR [ProjectionRateAdjusted05]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7E8F1E58] DEFAULT ((0)) FOR [SampledBudget03]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7F4E3867] DEFAULT ((0)) FOR [ProjectionRateAdjusted06]; GO
ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7F834291] DEFAULT ((0)) FOR [SampledBudget04]; GO

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

---------------------------------------------
-- fp.StatisticsAdjustment ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsAdjustment] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [ParentFilterJSON] nvarchar(max) NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [ClassificationGroupID] int NOT NULL,
    [ClassificationCategoryID] int NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [LastModifiedDateUtc] datetime NOT NULL,
    [DimensionMemberJson] nvarchar(max) NOT NULL,
    [AdjustmentID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    [IsErrored] bit NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [FK__Statistic__Budge__6B17FAEA] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF_StatisticsAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF_StatisticsAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Subse__31422788] DEFAULT ((1)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Budge__3890A59A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__IsErr__481D01ED] DEFAULT ((0)) FOR [IsErrored]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Dimen__62EDC65E] DEFAULT ('') FOR [DimensionMemberJson]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__DateC__6A04D841] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__LastM__6AF8FC7A] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__6C0C1F23] DEFAULT (newid()) FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF_StatisticsAdjustment] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__6D00435C] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Value__6DF46795] DEFAULT ((0)) FOR [Value]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__6EE88BCE] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Group__6FDCB007] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__IsRec__709BFBE0] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__70D0D440] DEFAULT ('') FOR [AdjustedProperty]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Comme__71C4F879] DEFAULT ('') FOR [Comment]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Autho__72B91CB2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Autho__73AD40EB] DEFAULT ('') FOR [AuthorFullName]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Group__7689AD96] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Paren__777DD1CF] DEFAULT ('{}') FOR [ParentFilterJSON]; GO

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

---------------------------------------------
-- fp.StatisticsAdjustmentImport ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsAdjustmentImport] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [EntityID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [FiscalYearID] smallint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [Version] timestamp NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [AdjustmentID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[StatisticsAdjustmentImport] ([AdjustmentID]);
GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Entit__001317D0] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Accou__01073C09] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Payor__01FB6042] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Patie__02EF847B] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Finan__03E3A8B4] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__TimeC__1016D774] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Adjus__2782E7CD] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF_StatisticsAdjustmentImport_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6C22F634] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6D171A6D] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6E0B3EA6] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6EFF62DF] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__IsRec__746C8CC4] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Adjus__7A5A3E7A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF_INTStatisticsAdjImportINGVALUE] DEFAULT ((0)) FOR [Value]; GO

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

---------------------------------------------
-- fp.StatisticsAdjustmentRate ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsAdjustmentRate] (
    [RowID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [AdjustmentID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_Clustered_StatisticsAdjustmentRate] ON [fp].[StatisticsAdjustmentRate] ([BudgetConfigID]);
GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Adjus__16840FAB] DEFAULT ((0)) FOR [AdjustmentID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Budge__177833E4] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Entit__186C581D] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Depar__19607C56] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Accou__1A54A08F] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Finan__1B48C4C8] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Payor__1C3CE901] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Patie__1D310D3A] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__1E253173] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__1F1955AC] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__200D79E5] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__21019E1E] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Subse__21F5C257] DEFAULT ((0)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__TimeC__22E9E690] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__23DE0AC9] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__24D22F02] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__25C6533B] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__26BA7774] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__27AE9BAD] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__28A2BFE6] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2996E41F] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2A8B0858] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2B7F2C91] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2C7350CA] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2D677503] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2E5B993C] DEFAULT ((0)) FOR [Value12]; GO
ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Budge__3984C9D3] DEFAULT ((0)) FOR [BudgetPhaseID]; GO

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

---------------------------------------------
-- fp.StatisticsAdjustment_backup ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsAdjustment_backup] (
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [Value] decimal NOT NULL,
    [AdjustmentFilterJSON] nvarchar(max) NOT NULL,
    [GroupingHierarchyJSON] nvarchar(max) NOT NULL,
    [AdjustedProperty] nvarchar(100) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [AuthorGUID] uniqueidentifier NOT NULL,
    [AuthorFullName] nvarchar(260) NOT NULL,
    [LastModifiedDate] datetime NOT NULL,
    [DateCreatedUTC] datetime NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [ParentFilterJSON] nvarchar(max) NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    PRIMARY KEY ([AdjustmentGUID])
);
GO
ALTER TABLE [fp].[StatisticsAdjustment_backup] ADD CONSTRAINT [DF_StatisticsAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO

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

---------------------------------------------
-- fp.StatisticsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsChangeHistory] (
    [RowID] bigint NOT NULL,
    [StatisticsID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [GroupingGUID] uniqueidentifier NOT NULL,
    [AdjustmentType] tinyint NOT NULL,
    [FiscalMonthID] tinyint NOT NULL,
    [UnitTypeID] tinyint NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [BudgetPhaseID] tinyint NOT NULL,
    [OldValue] decimal NOT NULL,
    [NewValue] decimal NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [DateCreatedUTC] datetime2 NOT NULL,
    [SubsectionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE CLUSTERED INDEX [IX_StatisticsChangeHistory] ON [fp].[StatisticsChangeHistory] ([StatisticsID]);
CREATE NONCLUSTERED INDEX [IX_StatisticsChangeHistory_AdjustmentGuid] ON [fp].[StatisticsChangeHistory] ([AdjustmentGUID]) INCLUDE ([StatisticsID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]);
GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [FK_StatisticsChangeHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__DateC__03D9B8DD] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Stati__1453DEB1] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Adjus__154802EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Group__163C2723] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Adjus__17304B5C] DEFAULT ((0)) FOR [AdjustmentType]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Subse__18CB7F79] DEFAULT ((1)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Fisca__191893CE] DEFAULT ((0)) FOR [FiscalMonthID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__UnitT__1A0CB807] DEFAULT ((0)) FOR [UnitTypeID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__TimeC__1B00DC40] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Budge__1BF50079] DEFAULT ((0)) FOR [BudgetPhaseID]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__1CE924B2] DEFAULT ((0)) FOR [OldValue]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1DDD48EB] DEFAULT ((0)) FOR [NewValue]; GO
ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Budge__5F124882] DEFAULT ((0)) FOR [BudgetConfigID]; GO

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

---------------------------------------------
-- fp.StatisticsFlexingConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsFlexingConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [AccountID] int NOT NULL,
    [FlexMethodID] int NOT NULL,
    PRIMARY KEY ([EntityGroupConfigGUID], [AccountID])
);
GO
ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [FK__Statistic__Accou__41B55917] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [DF__Statistic__Accou__0DA2E86F] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [DF__Statistic__FlexM__0E970CA8] DEFAULT ((6)) FOR [FlexMethodID]; GO
ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [df_StatisticsFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO

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

---------------------------------------------
-- fp.StatisticsFlexingOverrideConfig ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsFlexingOverrideConfig] (
    [EntityGroupConfigGUID] uniqueidentifier NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FlexMethodID] smallint NOT NULL,
    [RowID] int NOT NULL,
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [UQ__Statisti__173FA2A63EB2A0A8] ON [fp].[StatisticsFlexingOverrideConfig] ([OverrideFlexConfigGUID]);
CREATE UNIQUE NONCLUSTERED INDEX [Unique_StatisticsFlexingOverrideConfig_EC_Dept_Account] ON [fp].[StatisticsFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]);
GO
ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [FK__Statistic__Accou__476E326D] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [FK__Statistic__Depar__467A0E34] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [DF__Statistic__Depar__2F8DEC1F] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [DF__Statistic__Accou__30821058] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [DF__Statistic__FlexM__31763491] DEFAULT ((6)) FOR [FlexMethodID]; GO
ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [df_StatisticsFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO
ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [df_StatisticsFlexingOverrideConfig_OverrideFlexConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OverrideFlexConfigGUID]; GO

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

---------------------------------------------
-- fp.StatisticsFlexingOverrideConfigAssignment ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsFlexingOverrideConfigAssignment] (
    [OverrideFlexConfigGUID] uniqueidentifier NOT NULL,
    [ChargeCodeID] int NOT NULL,
    [RowID] int NOT NULL,
    PRIMARY KEY ([RowID])
);

CREATE UNIQUE NONCLUSTERED INDEX [Unique_StatisticsFlexingOverrideConfigAssignment_Account_FlexGUID] ON [fp].[StatisticsFlexingOverrideConfigAssignment] ([OverrideFlexConfigGUID], [ChargeCodeID]);
GO

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

---------------------------------------------
-- fp.StatisticsHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsHistory] (
    [RowID] int NOT NULL,
    [StatisticsID] int NOT NULL,
    [PriorYearActualValue01] decimal NOT NULL,
    [PriorYearActualValue02] decimal NOT NULL,
    [PriorYearActualValue03] decimal NOT NULL,
    [PriorYearActualValue04] decimal NOT NULL,
    [PriorYearActualValue05] decimal NOT NULL,
    [PriorYearActualValue06] decimal NOT NULL,
    [PriorYearActualValue07] decimal NOT NULL,
    [PriorYearActualValue08] decimal NOT NULL,
    [PriorYearActualValue09] decimal NOT NULL,
    [PriorYearActualValue10] decimal NOT NULL,
    [PriorYearActualValue11] decimal NOT NULL,
    [PriorYearActualValue12] decimal NOT NULL,
    [ActualYTDValue01] decimal NOT NULL,
    [ActualYTDValue02] decimal NOT NULL,
    [ActualYTDValue03] decimal NOT NULL,
    [ActualYTDValue04] decimal NOT NULL,
    [ActualYTDValue05] decimal NOT NULL,
    [ActualYTDValue06] decimal NOT NULL,
    [ActualYTDValue07] decimal NOT NULL,
    [ActualYTDValue08] decimal NOT NULL,
    [ActualYTDValue09] decimal NOT NULL,
    [ActualYTDValue10] decimal NOT NULL,
    [ActualYTDValue11] decimal NOT NULL,
    [ActualYTDValue12] decimal NOT NULL,
    [CurrentYearBudget01] decimal NOT NULL,
    [CurrentYearBudget02] decimal NOT NULL,
    [CurrentYearBudget03] decimal NOT NULL,
    [CurrentYearBudget04] decimal NOT NULL,
    [CurrentYearBudget05] decimal NOT NULL,
    [CurrentYearBudget06] decimal NOT NULL,
    [CurrentYearBudget07] decimal NOT NULL,
    [CurrentYearBudget08] decimal NOT NULL,
    [CurrentYearBudget09] decimal NOT NULL,
    [CurrentYearBudget10] decimal NOT NULL,
    [CurrentYearBudget11] decimal NOT NULL,
    [CurrentYearBudget12] decimal NOT NULL,
    [PriorYearActualValueTotal] decimal NOT NULL,
    [ActualYTDValueTotal] decimal NOT NULL,
    [CurrentYearBudgetTotal] decimal NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [FK_StatisticsHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[Statistics] ([StatisticsID]); GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Stati__0D9C57BE] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__0E907BF7] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__0F84A030] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1078C469] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__116CE8A2] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__12610CDB] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__13553114] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1449554D] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__153D7986] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__16319DBF] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1725C1F8] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1819E631] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__190E0A6A] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1A022EA3] DEFAULT ((0)) FOR [ActualYTDValue01]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1AF652DC] DEFAULT ((0)) FOR [ActualYTDValue02]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1BEA7715] DEFAULT ((0)) FOR [ActualYTDValue03]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1CDE9B4E] DEFAULT ((0)) FOR [ActualYTDValue04]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1DD2BF87] DEFAULT ((0)) FOR [ActualYTDValue05]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1EC6E3C0] DEFAULT ((0)) FOR [ActualYTDValue06]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1FBB07F9] DEFAULT ((0)) FOR [ActualYTDValue07]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__20AF2C32] DEFAULT ((0)) FOR [ActualYTDValue08]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__21A3506B] DEFAULT ((0)) FOR [ActualYTDValue09]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__229774A4] DEFAULT ((0)) FOR [ActualYTDValue10]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__238B98DD] DEFAULT ((0)) FOR [ActualYTDValue11]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__247FBD16] DEFAULT ((0)) FOR [ActualYTDValue12]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2573E14F] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__26680588] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__275C29C1] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__28504DFA] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__29447233] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2A38966C] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2B2CBAA5] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2C20DEDE] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2D150317] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2E092750] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2EFD4B89] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO
ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2FF16FC2] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO

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

---------------------------------------------
-- fp.StatisticsInitialPlanConfigDetail ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsInitialPlanConfigDetail] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [VersionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [FK__Statistic__Budge__5E247F01] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [FK__Statistic__Versi__5F18A33A] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Budge__4DEE1738] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Budge__4EE23B71] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Entit__4FD65FAA] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Depar__50CA83E3] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Accou__51BEA81C] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Patie__52B2CC55] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__TimeC__53A6F08E] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Finan__549B14C7] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Payor__558F3900] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__56835D39] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__57778172] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__586BA5AB] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__595FC9E4] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Varia__5A53EE1D] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Proje__5B481256] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Trail__5C3C368F] DEFAULT ((0)) FOR [TrailingMonths]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Versi__5D305AC8] DEFAULT ((0)) FOR [VersionID]; GO

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

---------------------------------------------
-- fp.StatisticsInitialPlanConfigDetailHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] (
    [RowID] int NOT NULL,
    [BudgetConfigGUID] uniqueidentifier NOT NULL,
    [BudgetConfigID] smallint NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [TimeClassID] tinyint NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [VariabilityID] int NOT NULL,
    [ProjectionMethodID] int NOT NULL,
    [TrailingMonths] tinyint NOT NULL,
    [VersionID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__Statistic__Budge__722B77AE] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__Statistic__Versi__731F9BE7] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Budge__61F50FE5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Budge__62E9341E] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Entit__63DD5857] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Depar__64D17C90] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Accou__65C5A0C9] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Patie__66B9C502] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__TimeC__67ADE93B] DEFAULT ((0)) FOR [TimeClassID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Finan__68A20D74] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Payor__699631AD] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6A8A55E6] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6B7E7A1F] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6C729E58] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6D66C291] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Varia__6E5AE6CA] DEFAULT ((0)) FOR [VariabilityID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Proje__6F4F0B03] DEFAULT ((0)) FOR [ProjectionMethodID]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Trail__70432F3C] DEFAULT ((0)) FOR [TrailingMonths]; GO
ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Versi__71375375] DEFAULT ((0)) FOR [VersionID]; GO

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

---------------------------------------------
-- fp.StatisticsSpreadUnlockData ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsSpreadUnlockData] (
    [RowID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [AdjustmentGUID] uniqueidentifier NOT NULL,
    [EntityID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [FinancialReportingID] int NOT NULL,
    [PayorID] int NOT NULL,
    [PatientClassID] int NOT NULL,
    [Version] timestamp NOT NULL,
    [Value01] decimal NOT NULL,
    [Value02] decimal NOT NULL,
    [Value03] decimal NOT NULL,
    [Value04] decimal NOT NULL,
    [Value05] decimal NOT NULL,
    [Value06] decimal NOT NULL,
    [Value07] decimal NOT NULL,
    [Value08] decimal NOT NULL,
    [Value09] decimal NOT NULL,
    [Value10] decimal NOT NULL,
    [Value11] decimal NOT NULL,
    [Value12] decimal NOT NULL,
    [IsRecordDeleted] bit NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderTypeID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    [ProviderSpecialtyID] int NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__IsRec__03AED054] DEFAULT ((0)) FOR [IsRecordDeleted]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [df_StatisticsSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Budge__5D9D6AAE] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Entit__5F85B320] DEFAULT ((0)) FOR [EntityID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Depar__6079D759] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Accou__616DFB92] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Finan__62621FCB] DEFAULT ((0)) FOR [FinancialReportingID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Payor__63564404] DEFAULT ((0)) FOR [PayorID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Patie__644A683D] DEFAULT ((0)) FOR [PatientClassID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__653E8C76] DEFAULT ((0)) FOR [Value01]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6632B0AF] DEFAULT ((0)) FOR [Value02]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6726D4E8] DEFAULT ((0)) FOR [Value03]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__681AF921] DEFAULT ((0)) FOR [Value04]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__690F1D5A] DEFAULT ((0)) FOR [Value05]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6A034193] DEFAULT ((0)) FOR [Value06]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6AF765CC] DEFAULT ((0)) FOR [Value07]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6B6EC91D] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6BEB8A05] DEFAULT ((0)) FOR [Value08]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6C62ED56] DEFAULT ((0)) FOR [ProviderTypeID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6CDFAE3E] DEFAULT ((0)) FOR [Value09]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6D57118F] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6DD3D277] DEFAULT ((0)) FOR [Value10]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6E4B35C8] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6EC7F6B0] DEFAULT ((0)) FOR [Value11]; GO
ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6FBC1AE9] DEFAULT ((0)) FOR [Value12]; GO

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

---------------------------------------------
-- fp.StatisticsSpreads ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsSpreads] (
    [BudgetConfigID] int NOT NULL,
    [DepartmentID] int NOT NULL,
    [AccountID] int NOT NULL,
    [IsInactive] bit NOT NULL,
    [SpreadPercentage01] decimal NULL,
    [SpreadPercentage02] decimal NULL,
    [SpreadPercentage03] decimal NULL,
    [SpreadPercentage04] decimal NULL,
    [SpreadPercentage05] decimal NULL,
    [SpreadPercentage06] decimal NULL,
    [SpreadPercentage07] decimal NULL,
    [SpreadPercentage08] decimal NULL,
    [SpreadPercentage09] decimal NULL,
    [SpreadPercentage10] decimal NULL,
    [SpreadPercentage11] decimal NULL,
    [SpreadPercentage12] decimal NULL,
    [TotalImportedValue] decimal NULL,
    [SpreadHistoryGUID] uniqueidentifier NOT NULL,
    [GlobalSpreadID] int NOT NULL,
    [ProviderID] int NOT NULL,
    [ProviderLineItemID] int NOT NULL,
    PRIMARY KEY ([BudgetConfigID], [DepartmentID], [AccountID], [ProviderID], [ProviderLineItemID])
);
GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_Provider] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_ProviderLineItem] FOREIGN KEY ([ProviderLineItemID]) REFERENCES [fp].[ProviderLineItem] ([ProviderLineItemID]); GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_StatisticsSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Provi__1BF466EC] DEFAULT ((0)) FOR [ProviderID]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Provi__1CE88B25] DEFAULT ((0)) FOR [ProviderLineItemID]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Globa__3B533FA2] DEFAULT ((1)) FOR [GlobalSpreadID]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Budge__43DD98AB] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Depar__44D1BCE4] DEFAULT ((0)) FOR [DepartmentID]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Accou__46BA0556] DEFAULT ((0)) FOR [AccountID]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__IsIna__48A24DC8] DEFAULT ((0)) FOR [IsInactive]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__49967201] DEFAULT ((0)) FOR [SpreadPercentage01]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4A8A963A] DEFAULT ((0)) FOR [SpreadPercentage02]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4B7EBA73] DEFAULT ((0)) FOR [SpreadPercentage03]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4C72DEAC] DEFAULT ((0)) FOR [SpreadPercentage04]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4D6702E5] DEFAULT ((0)) FOR [SpreadPercentage05]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4E5B271E] DEFAULT ((0)) FOR [SpreadPercentage06]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [df_StatisticsSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4F4F4B57] DEFAULT ((0)) FOR [SpreadPercentage07]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__50436F90] DEFAULT ((0)) FOR [SpreadPercentage08]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__513793C9] DEFAULT ((0)) FOR [SpreadPercentage09]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__522BB802] DEFAULT ((0)) FOR [SpreadPercentage10]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__531FDC3B] DEFAULT ((0)) FOR [SpreadPercentage11]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__54140074] DEFAULT ((0)) FOR [SpreadPercentage12]; GO
ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Total__550824AD] DEFAULT ((0)) FOR [TotalImportedValue]; GO

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

---------------------------------------------
-- fp.StatisticsSpreadsChangeHistory ------------------
---------------------------------------------
CREATE TABLE [fp].[StatisticsSpreadsChangeHistory] (
    [RowID] bigint NOT NULL,
    [StatisticsID] int NOT NULL,
    [BudgetConfigID] int NOT NULL,
    [SubsectionID] int NOT NULL,
    [DateCreatedUtc] datetime NOT NULL,
    [OldValue01] decimal NOT NULL,
    [OldValue02] decimal NOT NULL,
    [OldValue03] decimal NOT NULL,
    [OldValue04] decimal NOT NULL,
    [OldValue05] decimal NOT NULL,
    [OldValue06] decimal NOT NULL,
    [OldValue07] decimal NOT NULL,
    [OldValue08] decimal NOT NULL,
    [OldValue09] decimal NOT NULL,
    [OldValue10] decimal NOT NULL,
    [OldValue11] decimal NOT NULL,
    [OldValue12] decimal NOT NULL,
    [NewValue01] decimal NOT NULL,
    [NewValue02] decimal NOT NULL,
    [NewValue03] decimal NOT NULL,
    [NewValue04] decimal NOT NULL,
    [NewValue05] decimal NOT NULL,
    [NewValue06] decimal NOT NULL,
    [NewValue07] decimal NOT NULL,
    [NewValue08] decimal NOT NULL,
    [NewValue09] decimal NOT NULL,
    [NewValue10] decimal NOT NULL,
    [NewValue11] decimal NOT NULL,
    [NewValue12] decimal NOT NULL
);

CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[StatisticsSpreadsChangeHistory] ([BudgetConfigID], [SubsectionID], [StatisticsID], [RowID]);
GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__Stati__04A883EE] DEFAULT ((0)) FOR [StatisticsID]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__Budge__059CA827] DEFAULT ((0)) FOR [BudgetConfigID]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__Subse__0690CC60] DEFAULT ((1)) FOR [SubsectionID]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__DateC__0784F099] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__087914D2] DEFAULT ((0)) FOR [OldValue01]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__096D390B] DEFAULT ((0)) FOR [OldValue02]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0A615D44] DEFAULT ((0)) FOR [OldValue03]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0B55817D] DEFAULT ((0)) FOR [OldValue04]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0C49A5B6] DEFAULT ((0)) FOR [OldValue05]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0D3DC9EF] DEFAULT ((0)) FOR [OldValue06]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0E31EE28] DEFAULT ((0)) FOR [OldValue07]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0F261261] DEFAULT ((0)) FOR [OldValue08]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__101A369A] DEFAULT ((0)) FOR [OldValue09]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__110E5AD3] DEFAULT ((0)) FOR [OldValue10]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__12027F0C] DEFAULT ((0)) FOR [OldValue11]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__12F6A345] DEFAULT ((0)) FOR [OldValue12]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__13EAC77E] DEFAULT ((0)) FOR [NewValue01]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__14DEEBB7] DEFAULT ((0)) FOR [NewValue02]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__15D30FF0] DEFAULT ((0)) FOR [NewValue03]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__16C73429] DEFAULT ((0)) FOR [NewValue04]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__17BB5862] DEFAULT ((0)) FOR [NewValue05]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__18AF7C9B] DEFAULT ((0)) FOR [NewValue06]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__19A3A0D4] DEFAULT ((0)) FOR [NewValue07]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1A97C50D] DEFAULT ((0)) FOR [NewValue08]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1B8BE946] DEFAULT ((0)) FOR [NewValue09]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1C800D7F] DEFAULT ((0)) FOR [NewValue10]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1D7431B8] DEFAULT ((0)) FOR [NewValue11]; GO
ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1E6855F1] DEFAULT ((0)) FOR [NewValue12]; GO

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

---------------------------------------------
-- fp.SystemSetting ------------------
---------------------------------------------
CREATE TABLE [fp].[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,
    [IsFeatureFlag] bit NOT NULL,
    [DateCreated] date NOT NULL,
    PRIMARY KEY ([SystemSettingID])
);

CREATE UNIQUE NONCLUSTERED INDEX [IX_SystemSetting_Unique] ON [fp].[SystemSetting] ([Name]);
GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__DateC__03739D3C] DEFAULT (getdate()) FOR [DateCreated]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsFea__1127FBAC] DEFAULT ((0)) FOR [IsFeatureFlag]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSett__Name__555D2A68] DEFAULT ('') FOR [Name]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Descr__56514EA1] DEFAULT ('') FOR [Description]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF_SYSTEMSETTING_VALUE] DEFAULT ('') FOR [Value]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEdi__58399713] DEFAULT ((0)) FOR [IsEditable]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Colum__592DBB4C] DEFAULT ((0)) FOR [ColumnType]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Defau__5A21DF85] DEFAULT ('') FOR [DefaultValue]; GO
ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEnc__5B1603BE] DEFAULT ((0)) FOR [IsEncrypted]; GO

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

---------------------------------------------
-- fp.TempProcTable ------------------
---------------------------------------------
CREATE TABLE [fp].[TempProcTable] (
    [ProcName] nvarchar(max) NULL,
    [SchemaName] nvarchar(50) NULL,
    [Schema_ID] int NULL,
    [ProcText] nvarchar(max) NULL,
    [type_desc] nvarchar(100) NULL,
    [DateAdded] datetime NULL
);
GO

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

---------------------------------------------
-- fp.ViewedGeneralLedgerItemizationComment ------------------
---------------------------------------------
CREATE TABLE [fp].[ViewedGeneralLedgerItemizationComment] (
    [RowID] int NOT NULL,
    [CommentGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ViewedGeneralLedgerItemizationComment] ADD CONSTRAINT [DF__ViewedGen__Comme__705D9B6C] DEFAULT (newid()) FOR [CommentGUID]; GO
ALTER TABLE [fp].[ViewedGeneralLedgerItemizationComment] ADD CONSTRAINT [DF__ViewedGen__UserG__7151BFA5] DEFAULT (newid()) FOR [UserGUID]; GO

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

---------------------------------------------
-- fp.ViewedManagerAdjustmentComment ------------------
---------------------------------------------
CREATE TABLE [fp].[ViewedManagerAdjustmentComment] (
    [ViewedManagerAdjustmentCommentID] int NOT NULL,
    [CommentGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ViewedManagerAdjustmentCommentID])
);
GO
ALTER TABLE [fp].[ViewedManagerAdjustmentComment] ADD CONSTRAINT [FK_ViewedManagerAdjustmentComment_GeneralLedgerManagerAdjustmentComment] FOREIGN KEY ([CommentGUID]) REFERENCES [fp].[GeneralLedgerManagerAdjustmentComment] ([CommentGUID]); GO
ALTER TABLE [fp].[ViewedManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedManagerAdjustmentComment_CommentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO
ALTER TABLE [fp].[ViewedManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedManagerAdjustmentComment_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO

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

---------------------------------------------
-- fp.ViewedStaffingManagerAdjustmentComment ------------------
---------------------------------------------
CREATE TABLE [fp].[ViewedStaffingManagerAdjustmentComment] (
    [ViewedStaffingManagerAdjustmentCommentID] int NOT NULL,
    [CommentGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([ViewedStaffingManagerAdjustmentCommentID])
);
GO
ALTER TABLE [fp].[ViewedStaffingManagerAdjustmentComment] ADD CONSTRAINT [FK_ViewedStaffingManagerAdjustmentComment_StaffingManagerAdjustmentComment] FOREIGN KEY ([CommentGUID]) REFERENCES [fp].[StaffingManagerAdjustmentComment] ([CommentGUID]); GO
ALTER TABLE [fp].[ViewedStaffingManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedStaffingManagerAdjustmentComment_CommentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO
ALTER TABLE [fp].[ViewedStaffingManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedStaffingManagerAdjustmentComment_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO

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

---------------------------------------------
-- fp.ViewedStaffingManagerSetAdjustmentComment ------------------
---------------------------------------------
CREATE TABLE [fp].[ViewedStaffingManagerSetAdjustmentComment] (
    [RowID] int NOT NULL,
    [CommentID] int NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    PRIMARY KEY ([RowID])
);
GO
ALTER TABLE [fp].[ViewedStaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__ViewedSta__Comme__45E215C5] DEFAULT ((0)) FOR [CommentID]; GO
ALTER TABLE [fp].[ViewedStaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__ViewedSta__UserG__46D639FE] DEFAULT (newid()) FOR [UserGUID]; GO

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

---------------------------------------------
-- fp.WorkflowDepartmentMoveTaskInfo ------------------
---------------------------------------------
CREATE TABLE [fp].[WorkflowDepartmentMoveTaskInfo] (
    [MoveTaskInfoGUID] uniqueidentifier NOT NULL,
    [UserGUID] uniqueidentifier NOT NULL,
    [StepName] nvarchar(200) NOT NULL,
    [Comment] nvarchar(max) NOT NULL,
    [DepartmentsForMove] nvarchar(max) NOT NULL,
    PRIMARY KEY ([MoveTaskInfoGUID])
);
GO

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

-- fp.viewABBDeptChargeVolumesByMonth
CREATE VIEW [fp].[viewABBDeptChargeVolumesByMonth]
as
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2022-10-06  JB          JAZZ-44368      Remove PayorID and PayorGroupID
** 2    2023-03-22  BK          JAZZ-52162      Update for new data structure
*************************************************************/
SELECT
	vol.BudgetConfigID,
	vol.EntityGroupConfigID,
	vol.EntityID,
	vol.DepartmentID,
	vol.ServiceLineID,
	vol.PatientClassID,
	vol.AgeCohortID,
	vol.MedicalSurgicalID,
	vol.ChargeCodeID,
	vol.UnitTypeID, 
	vol.ServiceEntityID,
	vol.MSDRGID,
	vol.UBRevCodeID,
	vol.PrimaryCPTID,
	vol.BillingCPTID,
	vol.ServiceProviderID,
	vol.ServiceProviderSpecialtyID,
	vol.PerformingProviderID,
	vol.PerformingProviderSpecialtyID,
	2 as TimeClassID,
	bc.FiscalYearID,
	m.FiscalMonthID,
	vol.Value as Volume
From
	(
	SELECT
		   cv.ChargeVolumeID,
			cv.BudgetConfigID,
			cv.EntityGroupConfigID,
			cv.EntityID,
			cv.DepartmentID,
			cv.ServiceLineID,
			cv.PatientClassID,
			cv.AgeCohortID,
			cv.MedicalSurgicalID,
			cv.ChargeCodeID,
			cv.UnitTypeID,
			cv.ServiceEntityID,
			cv.MSDRGID,
			cv.UBRevCodeID,
			cv.PrimaryCPTID,
			cv.BillingCPTID,
			cv.ServiceProviderID,
			cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID,
			cv.PerformingProviderSpecialtyID,
			TargetLockType,
			TargetAdjusted01 AS 'Month01',
			TargetAdjusted02 AS 'Month02',
			TargetAdjusted03 AS 'Month03',
			TargetAdjusted04 AS 'Month04',
			TargetAdjusted05 AS 'Month05',
			TargetAdjusted06 AS 'Month06',
			TargetAdjusted07 AS 'Month07',
			TargetAdjusted08 AS 'Month08',
			TargetAdjusted09 AS 'Month09',
			TargetAdjusted10 AS 'Month10',
			TargetAdjusted11 AS 'Month11',
			TargetAdjusted12 AS 'Month12'
	FROM
		fp.ChargeVolume cv
	WHERE  cv.UnitTypeID = 145 -- We only want the units (aka volume)
		) cv 
		UNPIVOT (Value FOR FiscalMonth IN (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as vol
LEFT JOIN fw.DimFiscalMonth m ON
	m.MonthColumnName = vol.FiscalMonth
INNER JOIN fp.BudgetConfig bc ON
	vol.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewABBDeptChargeVolumesByMonth_Initials
CREATE VIEW [fp].[viewABBDeptChargeVolumesByMonth_Initials]
as
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2022-07-12  MD          JAZZ-38981      Initial
** 2    2022-10-06  JB          JAZZ-44368      Remove PayorID and PayorGroupID
** 3    2023-03-22  BK          JAZZ-52162      Update for new data structure
*********************************************************************/
SELECT
	vol.BudgetConfigID,
	vol.EntityGroupConfigID,
	vol.EntityID,
	vol.DepartmentID,
	vol.ServiceLineID,
	vol.PatientClassID,
	vol.AgeCohortID,
	vol.MedicalSurgicalID,
	vol.ChargeCodeID,
	vol.UnitTypeID, 
	vol.ServiceEntityID,
	vol.MSDRGID,
	vol.UBRevCodeID,
	vol.PrimaryCPTID,
	vol.BillingCPTID,
	vol.ServiceProviderID,
	vol.ServiceProviderSpecialtyID,
	vol.PerformingProviderID,
	vol.PerformingProviderSpecialtyID,
	TimeClassID,
	bc.FiscalYearID,
	m.FiscalMonthID,
	vol.Value as Volume
From
	(
	SELECT
		cv.ChargeVolumeID,
		cv.BudgetConfigID,
		cv.EntityGroupConfigID,
		cv.EntityID,
		cv.DepartmentID,
		cv.ServiceLineID,
		cv.PatientClassID,
		cv.AgeCohortID,
		cv.MedicalSurgicalID,
		cv.ChargeCodeID,
		cv.UnitTypeID,
		cv.ServiceEntityID,
		cv.MSDRGID,
		cv.UBRevCodeID,
		cv.PrimaryCPTID,
		cv.BillingCPTID,
		cv.ServiceProviderID,
		cv.ServiceProviderSpecialtyID,
		cv.PerformingProviderID,		
		cv.PerformingProviderSpecialtyID,
		CAST(2 AS TINYINT) AS TimeClassID,
		cv.InitialBudget01 AS 'Month01',
		cv.InitialBudget02 AS 'Month02',
		cv.InitialBudget03 AS 'Month03',
		cv.InitialBudget04 AS 'Month04',
		cv.InitialBudget05 AS 'Month05',
		cv.InitialBudget06 AS 'Month06',
		cv.InitialBudget07 AS 'Month07',
		cv.InitialBudget08 AS 'Month08',
		cv.InitialBudget09 AS 'Month09',
		cv.InitialBudget10 AS 'Month10',
		cv.InitialBudget11 AS 'Month11',
		cv.InitialBudget12 AS 'Month12'
	FROM
		fp.ChargeVolume cv
	WHERE
		cv.UnitTypeID = 145 -- We only want the units (aka volume)
	) cv
 
		UNPIVOT (Value FOR FiscalMonth IN (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as vol
LEFT JOIN fw.DimFiscalMonth m ON
	m.MonthColumnName = vol.FiscalMonth
INNER JOIN fp.BudgetConfig bc 
ON
	vol.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewABBDeptChargeVolumesByMonth_Projection
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2022-07-21  MD			JAZZ-38981		Initial
** 2    2022-10-06  JB          JAZZ-44368      Remove PayorID and PayorGroupID
** 3    2023-03-22  BK          JAZZ-52162      Update for new data structure
** 4    2023-08-31  MY          JAZZ-59674      Update Projection FiscalYear
*********************************************************************/

CREATE   VIEW [fp].[viewABBDeptChargeVolumesByMonth_Projection]
as
SELECT
	vol.BudgetConfigID,
	vol.EntityGroupConfigID,
	vol.EntityID,
	vol.DepartmentID,
	vol.ServiceLineID,
	vol.PatientClassID,
	vol.AgeCohortID,
	vol.MedicalSurgicalID,
	vol.ChargeCodeID,
	vol.UnitTypeID, 
	vol.ServiceEntityID,
	vol.MSDRGID,
	vol.UBRevCodeID,
	vol.PrimaryCPTID,
	vol.BillingCPTID,
	vol.ServiceProviderID,
	vol.ServiceProviderSpecialtyID,
	vol.PerformingProviderID,
	vol.PerformingProviderSpecialtyID,
	12 as TimeClassID,
	bc.FiscalYearID as FiscalYearID, -- Normally, we would want this to be FiscalYear - 1, but in this case we want to use the Budget Cost Per RVU
	m.FiscalMonthID,
	vol.Value as Volume
From
	(
	SELECT
		   cv.ChargeVolumeID,
			cv.BudgetConfigID,
			cv.EntityGroupConfigID,
			cv.EntityID,
			cv.DepartmentID,
			cv.ServiceLineID,
			cv.PatientClassID,
			cv.AgeCohortID,
			cv.MedicalSurgicalID,
			cv.ChargeCodeID,
			cv.UnitTypeID,
			cv.ServiceEntityID,
			cv.MSDRGID,
			cv.UBRevCodeID,
			cv.PrimaryCPTID,
			cv.BillingCPTID,
			cv.ServiceProviderID,
			cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID,
			cv.PerformingProviderSpecialtyID,
			ProjectionLockType,
			ProjectionAdjusted01 AS 'Month01',
			ProjectionAdjusted02 AS 'Month02',
			ProjectionAdjusted03 AS 'Month03',
			ProjectionAdjusted04 AS 'Month04',
			ProjectionAdjusted05 AS 'Month05',
			ProjectionAdjusted06 AS 'Month06',
			ProjectionAdjusted07 AS 'Month07',
			ProjectionAdjusted08 AS 'Month08',
			ProjectionAdjusted09 AS 'Month09',
			ProjectionAdjusted10 AS 'Month10',
			ProjectionAdjusted11 AS 'Month11',
			ProjectionAdjusted12 AS 'Month12'
	FROM
		fp.ChargeVolume cv
	WHERE cv.UnitTypeID = 145 -- We only want the units (aka volume)
		) cv 
		UNPIVOT (Value FOR FiscalMonth IN (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as vol
LEFT JOIN fw.DimFiscalMonth m ON
	m.MonthColumnName = vol.FiscalMonth
INNER JOIN fp.BudgetConfig bc ON
	vol.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewABBFlexingAuditGL
CREATE VIEW fp.viewABBFlexingAuditGL
as
 SELECT
  slv.EntityID,
  slv.DepartmentID,
  bc.FiscalYearID,
  GL.TimeClassID,
  bc.BudgetConfigID,
  slv.ChargeCodeID,
  GL.OriginalAccountID,
  GL.CostComponentID,
  cc.CostingConfigGuid,
--  COALESCE(BudgetChargeUnits / NULLIF(BudgetServiceLineCases, 0), 0) as Utilization,
0 as Utilization,
  slv.Month01 as ChargeUnits_Month01,
slv.Month02 as ChargeUnits_Month02,
slv.Month03 as ChargeUnits_Month03,
slv.Month04 as ChargeUnits_Month04,
slv.Month05 as ChargeUnits_Month05,
slv.Month06 as ChargeUnits_Month06,
slv.Month07 as ChargeUnits_Month07,
slv.Month08 as ChargeUnits_Month08,
slv.Month09 as ChargeUnits_Month09,
slv.Month10 as ChargeUnits_Month10,
slv.Month11 as ChargeUnits_Month11,
slv.Month12 as ChargeUnits_Month12,
GL.VariableDirectUnitCost,
  GL.FixedDirectUnitCost,
  GL.Volume
 FROM
  [fp].[viewServiceLineChargeVolume_aggregate] slv
  INNER JOIN [fp].[BudgetConfig] bc ON slv.BudgetConfigID = bc.BudgetConfigID
  INNER JOIN [fp].[EntityGroupConfig] ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
  INNER JOIN [dss].[CostingConfig] cc on ec.CostingConfigGUID=cc.CostingConfigGuid
  INNER JOIN [dss].[CostingResult] cr on cc.CostingConfigGuid=cr.CostingConfigGuid
  INNER JOIN [dss].[FactCostingOutDetailGL] GL ON 1=1
   AND gl.CostingResultID=cr.CostingResultID 
   AND gl.DepartmentID=slv.DepartmentID 
   AND gl.ChargeCodeID=slv.ChargeCodeID
   AND GL.TimeClassID = ec.CostingConfigTimeClassID
 WHERE
 	cr.CostingResultID in(select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = cc.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0)
GO


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

-- fp.viewABBGLBudgetCostPerRVUbyMonth
CREATE VIEW [fp].[viewABBGLBudgetCostPerRVUbyMonth] AS

SELECT
	 A.DepartmentID
	,B.AccountID
	,A.ChargeCodeID
	,A.CostComponentID
	,A.BudgetConfigID
	,A.FiscalMonthID
	,A.FiscalYearID
	,A.ChargeVolume
	,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost
	,B.TotalCost
	,B.TotalVariableDirectCost
FROM
	(SELECT 
		  b.DepartmentID
		, b.ChargeCodeID
		, ca.CostComponentID
		, b.BudgetConfigID
		, b.FiscalMonthID
		, b.FiscalYearID
		, MAX(ca.RVU) as RVU
		, SUM(Volume) as ChargeVolume
	 FROM [fp].[viewABBDeptChargeVolumesByMonth] b
		  INNER JOIN [fp].[BudgetConfig] bc ON b.BudgetConfigID = bc.BudgetConfigID
          INNER JOIN [fp].[EntityGroupConfig] ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
		  INNER JOIN [dss].[ChargeAllocation] ca
			ON ca.CostingConfigGuid = ec.CostingConfigGUID
			and ca.ChargeCodeID = b.ChargeCodeID 
			and ca.DepartmentID = b.DepartmentID
			and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
	 GROUP BY
		b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.BudgetConfigID, b.FiscalMonthID, b.FiscalYearID) A

INNER JOIN 

	(SELECT
		  OriginalAccountID as AccountID
		, gl.DepartmentID
		, gl.FiscalYearID
		, gl.CostComponentID
		, bc.BudgetConfigID
		, SUM(gl.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU
		, SUM(gl.VariableDirectUnitCost * gl.Volume) as TotalVariableDirectCost
		, SUM(gl.TotalCost) as TotalCost
	FROM [dss].[FactCostingOutDetailGL] gl
		INNER JOIN [dss].[CostingResult] cr on gl.CostingResultID = cr.CostingResultID
		INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid
		INNER JOIN [fp].[EntityGroupConfig] ec on con.CostingConfigGuid = ec.CostingConfigGUID
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = ec.BudgetConfigGUID
		INNER JOIN [dss].[ChargeAllocation] ca on
			ca.CostingConfigGuid = con.CostingConfigGUID
			and ca.ChargeCodeID = gl.ChargeCodeID 
			and ca.DepartmentID = gl.DepartmentID
			and ca.CostComponentID = gl.CostComponentID
			and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
	WHERE 
		gl.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0)
		and gl.TimeClassID = ec.CostingConfigTimeClassID
	GROUP BY
		  gl.OriginalAccountID
		, gl.DepartmentID
		, bc.BudgetConfigID
		, gl.FiscalYearID
		, gl.CostComponentID) B
ON 
	A.DepartmentID = B.DepartmentID 
	and A.CostComponentID = B.CostComponentID;
GO


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

-- fp.viewABBPayrollBudgetCostPerRVUbyMonth
CREATE VIEW [fp].[viewABBPayrollBudgetCostPerRVUbyMonth] AS
	
	SELECT
		 A.DepartmentID
		,B.JobCodeID
		,B.PayCodeGroupID
		,A.ChargeCodeID
		,A.CostComponentID
		,A.BudgetConfigID
		,A.FiscalMonthID
		,A.FiscalYearID
		,B.UnitTypeID
		,A.ChargeVolume
		,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost
		,B.TotalCost
		,B.TotalVariableDirectCost
	FROM
		(SELECT 
			  b.DepartmentID
			, b.ChargeCodeID
			, ca.CostComponentID
			, b.BudgetConfigID
			, b.FiscalMonthID
			, b.FiscalYearID
			, MAX(ca.RVU) as RVU
			, SUM(Volume) as ChargeVolume
		 FROM [fp].[viewABBDeptChargeVolumesByMonth] b
			  INNER JOIN [fp].[BudgetConfig] bc on b.BudgetConfigID = bc.BudgetConfigID
			  INNER JOIN [fp].[EntityGroupConfig] ec on ec.BudgetConfigGUID = bc.BudgetConfigGUID
			  INNER JOIN [dss].[ChargeAllocation] ca
				ON ca.CostingConfigGuid = ec.CostingConfigGUID
				and ca.ChargeCodeID = b.ChargeCodeID 
				and ca.DepartmentID = b.DepartmentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
		 GROUP BY
			b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.BudgetConfigID, b.FiscalMonthID, b.FiscalYearID) A
	
	INNER JOIN 
	
		(SELECT
			  OriginalJobCodeID as JobCodeID
			, pc.PayCodeGroupID
			, pay.DepartmentID
			, pay.FiscalYearID
			, pay.CostComponentID
			, bc.BudgetConfigID
			, pay.UnitTypeID
			, SUM(pay.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU
			, SUM(pay.VariableDirectUnitCost * pay.Volume) as TotalVariableDirectCost
			, SUM(pay.TotalCost) as TotalCost
		FROM [dss].[FactCostingOutDetailPayroll] pay
			INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID
			INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid
			INNER JOIN [fp].[EntityGroupConfig] ec on con.CostingConfigGuid = ec.CostingConfigGUID
			INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = ec.BudgetConfigGUID
			INNER JOIN [dss].[ChargeAllocation] ca on
				ca.CostingConfigGuid = con.CostingConfigGUID
				and ca.ChargeCodeID = pay.ChargeCodeID 
				and ca.DepartmentID = pay.DepartmentID
				and ca.CostComponentID = pay.CostComponentID
				and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = pay.OriginalPayCodeID
		WHERE 
			pay.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0)
			and pay.TimeClassID = ec.CostingConfigTimeClassID
		GROUP BY
			  pay.OriginalJobCodeID
			, pc.PayCodeGroupID
			, pay.DepartmentID
			, bc.BudgetConfigID
			, pay.UnitTypeID
			, pay.FiscalYearID
			, pay.CostComponentID) B
	ON 
		A.DepartmentID = B.DepartmentID 
		and A.CostComponentID = B.CostComponentID
GO


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

-- fp.viewAPEDepartmentWorkflowStatus
CREATE view fp.viewAPEDepartmentWorkflowStatus
as
select
bc.BudgetConfigID,
wk.EntityGroupConfigID,
dept.DepartmentWorkflowStatusID,
dept.DepartmentID,
dept.EnteredStepDateTimeUtc,
dept.Status,
wk.WorkflowStepID,
wk.Name,
wk.RoleID,
wk.WorkflowStepOrder,
wk.IsEditable
from fp.APEDepartmentWorkflowStatus as dept 
inner join fp.APEWorkflow as wk on dept.WorkflowStepID = wk.WorkflowStepID 
inner join fp.EntityGroupConfig as egc on wk.EntityGroupConfigID = egc.EntityGroupConfigID 
inner join fp.BudgetConfig as bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID
GO


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

-- fp.viewAPESectionRoleAccessByUser
create view fp.viewAPESectionRoleAccessByUser
as
	select
		a.EntityGroupConfigID,
		a.Section,
		ra.IdentityGUID as UserGUID,
		max(a.AccessType) as AccessType 
	from 
		fp.APESectionRoleAccess a
		inner join dbo.viewS3RoleAssignment ra on ra.RoleID = a.RoleID
	where 
		a.budgetphaseid = 2
		and ra.lootgroupid like 'DEPT|%'
	group by
		a.EntityGroupConfigID,
		a.Section,
		ra.IdentityGUID
GO


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

-- fp.viewAPESectionRoleAccessByUserPerDepartment
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2023-10-12  MY      JAZZ-61714		Import Tool Error for Local Admin (added TRY_CAST)
*************************************************************/
CREATE   VIEW fp.viewAPESectionRoleAccessByUserPerDepartment
AS
	SELECT
		a.EntityGroupConfigID,
		a.Section,
		ra.IdentityGUID as UserGUID,
		TRY_CAST(REPLACE(ra.lootgroupid, 'DEPT|', '') AS INT) AS DepartmentID,
		a.AccessType as AccessType
	FROM fp.APESectionRoleAccess a
		INNER JOIN dbo.viewS3RoleAssignment ra on ra.RoleID = a.RoleID
	WHERE 
			a.budgetphaseid = 2
		AND ra.lootgroupid LIKE 'DEPT|%'
GO


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

-- fp.viewAccountFlexConfig
CREATE VIEW fp.viewAccountFlexConfig
AS
	SELECT bc.BudgetConfigID, egcm.EntityGroupConfigGUID, egcm.EntityID, afc.AccountID, afc.FlexMethodClassName
	FROM [fp].[AccountFlexConfig] afc
	 INNER JOIN [fp].[EntityGroupConfig] egc ON afc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
	 INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
	 INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
GO


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

-- fp.viewAddProviderSummary
CREATE   view [fp].[viewAddProviderSummary]  as 

SELECT
    prov.SummaryID,
    prov.SLEncounterAdjustmentGUID,
	 prov.DCVolumeAdjustmentGUID,
    prov.EmployeeType,
    emp.Number as EmployeeNumber,
    emp.NameFirst,
    emp.NameLast,
    emp.NPI,
    prov.StartDateUTC,
    provtype.Name as ProviderType,
    spec.Name Speciality,
    prov.BenchmarkProvidersJSON,
    prov.BenchmarkAverage,
    prov.ProjectionTotal,
    prov.BudgetTotal,
    prov.ClassificationCategoryID,
    prov.ClassificationGroupID,
    prov.Comment
FROM fp.AddProviderSummary prov
    LEFT JOIN [fw].[DimEmployee] emp ON prov.EmployeeID = emp.EmployeeID
    LEFT JOIN [clientdss].[DimProviderType] provtype on provtype.ProviderTypeID = prov.ProviderType
    LEFT JOIN [dss].[DimPhysicianSpecialty] spec on spec.PhysicianSpecialtyID = prov.Specialty
GO


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

-- fp.viewAdjustmentClassificationCategory
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fp].[viewAdjustmentClassificationCategory]
AS
SELECT
   grp6BD697B47CED4B698C166B89FE895E9E.[CategoryID]
   ,grp6BD697B47CED4B698C166B89FE895E9E.[Name]
   ,grp6BD697B47CED4B698C166B89FE895E9E.[MemberGUID]
   ,grp6BD697B47CED4B698C166B89FE895E9E.[GroupID]
FROM [fp].[AdjustmentClassificationCategory] grp6BD697B47CED4B698C166B89FE895E9E (readuncommitted)
GO


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

-- fp.viewAdjustmentClassificationGroup
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fp].[viewAdjustmentClassificationGroup]
AS
SELECT
   grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[GroupID]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[Name]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[MemberGUID]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[BudgetConfigID]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsEncounterVisible]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsChargesVisible]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsStatisticsVisible]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsStaffingVisible]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsBenefitsVisible]
   ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsGeneralLedgerVisible]
FROM [fp].[AdjustmentClassificationGroup] grp67DF447E1BD04F1F8D5C73CDDF4B3EAC (readuncommitted)
GO


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

-- fp.viewAdjustmentGrouping
CREATE VIEW fp.viewAdjustmentGrouping
AS 
SELECT [GroupingGUID]
      ,[Description]
      ,[ExcelFile]
      ,[IsRecordDeleted]
  FROM [fp].[AdjustmentGrouping]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewArchiveFactBenefits_HistoryViewer
CREATE VIEW fp.viewArchiveFactBenefits_HistoryViewer
AS
SELECT
	ov.BenefitsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.ArchiveFactBenefits gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactBenefits gl 
		INNER JOIN fp.ArchiveFactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactBenefits gl 
		INNER JOIN fp.ArchiveFactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewArchiveFactBenefits_Pivoted
CREATE VIEW [fp].[viewArchiveFactBenefits_Pivoted]
AS
SELECT
	fb.BenefitsID,
	fb.BudgetConfigID,
	fb.EntityGroupConfigID,
	fb.EntityID,
	fb.DepartmentID,
	fb.AccountID,
	fb.FinancialReportingID,
	fb.UnitTypeID,

	CASE WHEN fb.FlexMethodID = 1 THEN 1 ELSE 0 END AS FlexByFTEs,
	CASE WHEN fb.FlexMethodID = 2 THEN 1 ELSE 0 END AS FlexBySalaries,

	fbdgt.LockType as BudgetLockType,
	fbdgt.LockFlag as BudgetLockFlag,
	fproj.LockType as ProjectionLockType,
	fproj.LockFlag as ProjectionLockFlag,

	dbdgt.LockType as FinalBudgetLockType,
	dbdgt.LockFlag as FinalBudgetLockFlag,
	dproj.LockType as FinalProjectionLockType,
	dproj.LockFlag as FinalProjectionLockFlag,

	fbdgt.AdjustedValueTotal,

	dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal,
	dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal,

	dproj.AdjustedValueTotal as AdjustedProjectionValueTotal,

	hist.ActualYTDValueTotal,
	hist.CurrentYearBudgetTotal,
	hist.PriorYearActualValueTotal,

	fb.InitialBudgetTotal,
	fb.InitialProjectionTotal,

	fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12,
	dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12,
	dproj.AdjustedValue01 AS AdjustedProjectionValue01, dproj.AdjustedValue02 AS AdjustedProjectionValue02, dproj.AdjustedValue03 AS AdjustedProjectionValue03, dproj.AdjustedValue04 AS AdjustedProjectionValue04, dproj.AdjustedValue05 AS AdjustedProjectionValue05, dproj.AdjustedValue06 AS AdjustedProjectionValue06, dproj.AdjustedValue07 AS AdjustedProjectionValue07, dproj.AdjustedValue08 AS AdjustedProjectionValue08, dproj.AdjustedValue09 AS AdjustedProjectionValue09, dproj.AdjustedValue10 AS AdjustedProjectionValue10, dproj.AdjustedValue11 AS AdjustedProjectionValue11, dproj.AdjustedValue12 AS AdjustedProjectionValue12,
	fb.InitialBudget01, fb.InitialBudget02, fb.InitialBudget03, fb.InitialBudget04, fb.InitialBudget05, fb.InitialBudget06, fb.InitialBudget07, fb.InitialBudget08, fb.InitialBudget09, fb.InitialBudget10, fb.InitialBudget11, fb.InitialBudget12,
	hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12,
	hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12,
	hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12
FROM [fp].[ArchiveFactBenefits] fb (READUNCOMMITTED)
			 INNER JOIN [fp].[ArchiveFactBenefitsBudget] (READUNCOMMITTED) fbdgt ON fb.BenefitsID = fbdgt.BenefitsID AND fbdgt.BudgetPhaseID = 2
			 INNER JOIN [fp].[ArchiveFactBenefitsBudget] (READUNCOMMITTED) dbdgt ON fb.BenefitsID = dbdgt.BenefitsID AND dbdgt.BudgetPhaseID = 3
			 INNER JOIN [fp].[ArchiveFactBenefitsProjection] (READUNCOMMITTED) fproj ON fb.BenefitsID = fproj.BenefitsID AND fproj.BudgetPhaseID = 2
			 INNER JOIN [fp].[ArchiveFactBenefitsProjection] (READUNCOMMITTED) dproj ON fb.BenefitsID = dproj.BenefitsID AND dproj.BudgetPhaseID = 3
			 INNER JOIN [fp].[ArchiveFactBenefitsHistory] hist (READUNCOMMITTED) ON fb.BenefitsID = hist.BenefitsID
GO


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

-- fp.viewArchiveFactChargeVolume_Pivoted
CREATE VIEW fp.viewArchiveFactChargeVolume_Pivoted
AS
	SELECT
		fcv.ChargeVolumeID,
		fcv.BudgetConfigID, 
		fcv.EntityGroupConfigID,
		fcv.EntityID,
		fcv.DepartmentID,
		fcv.ServiceLineID,
		fcv.PatientClassID,
		fcv.AgeCohortID,
		fcv.MedicalSurgicalID,
		fcv.ChargeCodeID,
		fcv.UnitTypeID,
		
		fbdgt.LockType as TargetLockType,
		fbdgt.LockFlag as TargetLockFlag,
		--dbdgt.LockType as BudgetLockType,
		--dbdgt.LockFlag as BudgetLockFlag,
		fproj.LockType as ProjectionLockType,
		fproj.LockFlag as ProjectionLockFlag,
		
		fcv.VariableDirectUnitCost,
		fcv.InitialBudgetTotal,
		fcv.InitialProjectionTotal,
	
		fbdgt.AdjustedValueTotal,
	
		dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal,
		fproj.AdjustedValueTotal as AdjustedProjectionValueTotal,
		dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal,
	
		hist.ActualYTDValueTotal,
		hist.PriorYearActualValueTotal,
		hist.CurrentYearBudgetValueTotal AS CurrentYearBudgetTotal,
	
		fbdgt.AdjustedValue01, 
		fbdgt.AdjustedValue02, 
		fbdgt.AdjustedValue03, 
		fbdgt.AdjustedValue04, 
		fbdgt.AdjustedValue05, 
		fbdgt.AdjustedValue06, 
		fbdgt.AdjustedValue07, 
		fbdgt.AdjustedValue08, 
		fbdgt.AdjustedValue09, 
		fbdgt.AdjustedValue10, 
		fbdgt.AdjustedValue11, 
		fbdgt.AdjustedValue12,
		
		dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, 
		dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, 
		dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, 
		dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, 
		dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, 
		dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, 
		dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, 
		dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, 
		dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, 
		dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, 
		dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, 
		dbdgt.AdjustedValue12 AS ManagerAdjustedValue12,
		
		fproj.AdjustedValue01 AS AdjustedProjectionValue01, 
		fproj.AdjustedValue02 AS AdjustedProjectionValue02, 
		fproj.AdjustedValue03 AS AdjustedProjectionValue03, 
		fproj.AdjustedValue04 AS AdjustedProjectionValue04, 
		fproj.AdjustedValue05 AS AdjustedProjectionValue05, 
		fproj.AdjustedValue06 AS AdjustedProjectionValue06, 
		fproj.AdjustedValue07 AS AdjustedProjectionValue07, 
		fproj.AdjustedValue08 AS AdjustedProjectionValue08, 
		fproj.AdjustedValue09 AS AdjustedProjectionValue09, 
		fproj.AdjustedValue10 AS AdjustedProjectionValue10, 
		fproj.AdjustedValue11 AS AdjustedProjectionValue11, 
		fproj.AdjustedValue12 AS AdjustedProjectionValue12
	FROM 
		[fp].[ArchiveFactChargeVolume] fcv with (readuncommitted)
		INNER JOIN [fp].[ArchiveFactChargeVolumeBudget] fbdgt with (readuncommitted) ON fcv.ChargeVolumeID = fbdgt.ChargeVolumeID and fbdgt.BudgetPhaseID = 2
		INNER JOIN [fp].[ArchiveFactChargeVolumeBudget] dbdgt with (readuncommitted) ON fcv.ChargeVolumeID = dbdgt.ChargeVolumeID and dbdgt.BudgetPhaseID = 3
		INNER JOIN [fp].[ArchiveFactChargeVolumeProjection] fproj with (readuncommitted) ON fcv.ChargeVolumeID = fproj.ChargeVolumeID and fproj.BudgetPhaseID = 2
		INNER JOIN [fp].[ArchiveFactChargeVolumeProjection] dproj with (readuncommitted) ON fcv.ChargeVolumeID = dproj.ChargeVolumeID and dproj.BudgetPhaseID = 3
		INNER JOIN [fp].[ArchiveFactChargeVolumeHistory] hist with (readuncommitted) ON fcv.ChargeVolumeID = hist.ChargeVolumeID
GO


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

-- fp.viewArchiveFactServiceLineEncounter_HistoryViewer
CREATE VIEW fp.viewArchiveFactServiceLineEncounter_HistoryViewer
AS
SELECT
	ov.ServiceLineEncounterID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.PatientClassID, 
	ov.ServiceLineID, 
	ov.ServiceLineRollupID, 
	ov.AgeCohortID, 
	ov.MedicalSurgicalID, 
	ov.DepartmentID, 
	ov.PayorID, 
	ov.PayorGroupID, 
	ov.MSDRGID, 
	ov.CPTID, 
	ov.ProviderID, 
	ov.PhysicianSpecialtyID,
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT 
		ServiceLineEncounterID, 
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		PatientClassID, 
		ServiceLineID, 
		ServiceLineRollupID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		DepartmentID, 
		PayorID, 
		PayorGroupID, 
		MSDRGID, 
		CPTID, 
		ProviderID, 
		PhysicianSpecialtyID, 
		UnitTypeID, 
		m.FiscalMonthID, 
		f.InitialValue
	FROM (
		SELECT sle.*
		FROM fp.ArchiveFactServiceLineEncounter sle ) sle
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT 
		ServiceLineEncounterID, 
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		PatientClassID, 
		ServiceLineID, 
		ServiceLineRollupID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		DepartmentID, 
		PayorID, 
		PayorGroupID, 
		MSDRGID, 
		CPTID, 
		ProviderID, 
		PhysicianSpecialtyID, 
		UnitTypeID, 
		m.FiscalMonthID, 
		f.Value, 
		LockType
	FROM (
			SELECT sle.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.ArchiveFactServiceLineEncounter sle 
				INNER JOIN fp.ArchiveFactServiceLineEncounterBudget bdgt ON sle.ServiceLineEncounterID = bdgt.ServiceLineEncounterID 
			WHERE bdgt.BudgetPhaseID = 2
		) sle
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
		AND ov.EntityGroupConfigID = v.EntityGroupConfigID
		AND ov.EntityID = v.EntityID
		AND ov.PatientClassID = v.PatientClassID
		AND ov.ServiceLineID = v.ServiceLineID
		AND ov.ServiceLineRollupID = v.ServiceLineRollupID
		AND ov.AgeCohortID = v.AgeCohortID
		AND ov.MedicalSurgicalID = v.MedicalSurgicalID
		AND ov.DepartmentID = v.DepartmentID
		AND ov.PayorID = v.PayorID
		AND ov.PayorGroupID = v.PayorGroupID
		AND ov.MSDRGID = v.MSDRGID 
		AND ov.CPTID = v.CPTID 
		AND ov.ProviderID = v.ProviderID
		AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID 
		AND ov.UnitTypeID = v.UnitTypeID
		AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT 
		ServiceLineEncounterID, 
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		PatientClassID, 
		ServiceLineID, 
		ServiceLineRollupID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		DepartmentID, 
		PayorID, 
		PayorGroupID, 
		MSDRGID, 
		CPTID, 
		ProviderID, 
		PhysicianSpecialtyID,  
		UnitTypeID, 
		m.FiscalMonthID, 
		f.Value AS ManagerValue
	FROM (
			SELECT sle.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.ArchiveFactServiceLineEncounter sle 
				INNER JOIN fp.ArchiveFactServiceLineEncounterBudget bdgt ON sle.ServiceLineEncounterID = bdgt.ServiceLineEncounterID 
			WHERE bdgt.BudgetPhaseID = 3
		) sle
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
		AND ov.EntityGroupConfigID = mgrv.EntityGroupConfigID
		AND ov.EntityID = mgrv.EntityID
		AND ov.PatientClassID = mgrv.PatientClassID
		AND ov.ServiceLineID = mgrv.ServiceLineID
		AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID
		AND ov.AgeCohortID = mgrv.AgeCohortID
		AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID
		AND ov.DepartmentID = mgrv.DepartmentID
		AND ov.PayorID = mgrv.PayorID
		AND ov.PayorGroupID = mgrv.PayorGroupID
		AND ov.MSDRGID = mgrv.MSDRGID 
		AND ov.CPTID = mgrv.CPTID 
		AND ov.ProviderID = mgrv.ProviderID
		AND ov.PhysicianSpecialtyID = mgrv.PhysicianSpecialtyID 
		AND ov.UnitTypeID = mgrv.UnitTypeID
		AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewArchiveFactServiceLineEncounter_Pivoted
CREATE VIEW fp.viewArchiveFactServiceLineEncounter_Pivoted
AS
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	tbdgt.LockType as TargetLockType,
	tbdgt.LockFlag as TargetLockFlag,
	fbdgt.LockType as BudgetLockType,
	fbdgt.LockFlag as BudgetLockFlag,
	tproj.LockType as ProjectionLockType,
	tproj.LockFlag as ProjectionLockFlag,

	tbdgt.AdjustedValueTotal,
    fbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal,

    tproj.AdjustedValueTotal as AdjustedProjectionValueTotal,

    hist.PriorYearActualValueTotal as PriorYearActualValueTotal,
    hist.ActualYTDValueTotal as ActualYTDValueTotal,
    hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal,

	sl.SampledBudgetTotal,
    sl.InitialBudgetTotal,
    sl.InitialProjectionTotal,

    tbdgt.AdjustedValue01, tbdgt.AdjustedValue02, tbdgt.AdjustedValue03, tbdgt.AdjustedValue04, tbdgt.AdjustedValue05, tbdgt.AdjustedValue06, tbdgt.AdjustedValue07, tbdgt.AdjustedValue08, tbdgt.AdjustedValue09, tbdgt.AdjustedValue10, tbdgt.AdjustedValue11, tbdgt.AdjustedValue12,
    fbdgt.AdjustedValue01 AS ManagerAdjustedValue01, fbdgt.AdjustedValue02 AS ManagerAdjustedValue02, fbdgt.AdjustedValue03 AS ManagerAdjustedValue03, fbdgt.AdjustedValue04 AS ManagerAdjustedValue04, fbdgt.AdjustedValue05 AS ManagerAdjustedValue05, fbdgt.AdjustedValue06 AS ManagerAdjustedValue06, fbdgt.AdjustedValue07 AS ManagerAdjustedValue07, fbdgt.AdjustedValue08 AS ManagerAdjustedValue08, fbdgt.AdjustedValue09 AS ManagerAdjustedValue09, fbdgt.AdjustedValue10 AS ManagerAdjustedValue10, fbdgt.AdjustedValue11 AS ManagerAdjustedValue11, fbdgt.AdjustedValue12 AS ManagerAdjustedValue12,
    tproj.AdjustedValue01 AS AdjustedProjectionValue01, tproj.AdjustedValue02 AS AdjustedProjectionValue02, tproj.AdjustedValue03 AS AdjustedProjectionValue03, tproj.AdjustedValue04 AS AdjustedProjectionValue04, tproj.AdjustedValue05 AS AdjustedProjectionValue05, tproj.AdjustedValue06 AS AdjustedProjectionValue06, tproj.AdjustedValue07 AS AdjustedProjectionValue07, tproj.AdjustedValue08 AS AdjustedProjectionValue08, tproj.AdjustedValue09 AS AdjustedProjectionValue09, tproj.AdjustedValue10 AS AdjustedProjectionValue10, tproj.AdjustedValue11 AS AdjustedProjectionValue11, tproj.AdjustedValue12 AS AdjustedProjectionValue12

From fp.ArchiveFactServiceLineEncounter sl
	INNER JOIN fp.ArchiveFactServiceLineEncounterBudget tbdgt ON sl.ServiceLineEncounterID = tbdgt.ServiceLineEncounterID AND tbdgt.BudgetPhaseID = 2
	INNER JOIN fp.ArchiveFactServiceLineEncounterBudget fbdgt ON sl.ServiceLineEncounterID = fbdgt.ServiceLineEncounterID AND fbdgt.BudgetPhaseID = 3
	INNER JOIN fp.ArchiveFactServiceLineEncounterProjection tproj ON sl.ServiceLineEncounterID = tproj.ServiceLineEncounterID AND tproj.BudgetPhaseID = 2
	INNER JOIN fp.ArchiveFactServiceLineEncounterHistory hist ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewArchiveFactStaffingBudget_HistoryViewer
CREATE VIEW fp.viewArchiveFactStaffing_HistoryViewer
AS
SELECT 
	ov.StaffingID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.JobCodeID, 
	ov.PayCodeGroupID, 
	ov.ProductiveClassID, 
	ov.VariabilityID,
	ov.ProviderID, ov.ProviderTypeID, ov.ProviderSpecialtyID, ov.ProviderLineItemID, ov.SubsectionID,
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT fs.*
		FROM fp.ArchiveFactStaffing fs ) fs
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT fs.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStaffing fs 
		INNER JOIN fp.ArchiveFactStaffingBudget bdgt ON fs.StaffingID = bdgt.StaffingID 
		WHERE bdgt.BudgetPhaseID = 2) fs
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.JobCodeID = v.JobCodeID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.PayCodeGroupID = v.PayCodeGroupID
	AND ov.ProductiveClassID = v.ProductiveClassID
	AND ov.VariabilityID = v.VariabilityID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT fs.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStaffing fs 
		INNER JOIN fp.ArchiveFactStaffingBudget bdgt ON fs.StaffingID = bdgt.StaffingID 
		WHERE bdgt.BudgetPhaseID = 3) fs
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.JobCodeID = mgrv.JobCodeID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.ProductiveClassID = mgrv.ProductiveClassID
	AND ov.PayCodeGroupID = v.PayCodeGroupID
	AND ov.VariabilityID = mgrv.VariabilityID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewArchiveFactStaffingProjection_HistoryViewer
CREATE VIEW [fp].[viewArchiveFactStaffingProjection_HistoryViewer]
AS
SELECT 
	ov.StaffingID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.JobCodeID, 
	ov.PayCodeGroupID, 
	ov.ProductiveClassID, 
	ov.VariabilityID,
	ov.ProviderID, ov.ProviderTypeID, ov.ProviderSpecialtyID, ov.ProviderLineItemID, ov.SubsectionID,
	ov.UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT fs.*
		FROM fp.ArchiveFactStaffing fs ) fs
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT fs.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStaffing fs 
		INNER JOIN fp.ArchiveFactStaffingProjection bdgt ON fs.StaffingID = bdgt.StaffingID 
		WHERE bdgt.BudgetPhaseID = 2) fs
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.JobCodeID = v.JobCodeID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.PayCodeGroupID = v.PayCodeGroupID
	AND ov.ProductiveClassID = v.ProductiveClassID
	AND ov.VariabilityID = v.VariabilityID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT fs.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStaffing fs 
		INNER JOIN fp.ArchiveFactStaffingProjection bdgt ON fs.StaffingID = bdgt.StaffingID 
		WHERE bdgt.BudgetPhaseID = 3) fs
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.JobCodeID = mgrv.JobCodeID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.ProductiveClassID = mgrv.ProductiveClassID
	AND ov.PayCodeGroupID = v.PayCodeGroupID
	AND ov.VariabilityID = mgrv.VariabilityID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewArchiveFactStaffing_Pivoted
CREATE VIEW fp.viewArchiveFactStaffing_Pivoted
AS

with WageRate as (
		SELECT
			BudgetConfigID, EntityGroupConfigID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID,
			ProviderID,
			ProviderTypeID,
			ProviderSpecialtyID,
			ProviderLineItemID,
			SubsectionID, 
			bTarg.LockType as TargetLockType,
			bTarg.LockFlag as TargetLockFlag,
			bFinal.LockType as BudgetLockType,
			bFinal.LockFlag as BudgetLockFlag,
			pFinal.LockType as ProjectionLockType,
			pFinal.LockFlag as ProjectionLockFlag
		FROM [fp].[ArchiveFactStaffing] (READUNCOMMITTED) fs
			INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bTarg ON fs.StaffingID = bTarg.StaffingID AND bTarg.BudgetPhaseID = 2
			INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bFinal ON fs.StaffingID = bFinal.StaffingID AND bFinal.BudgetPhaseID = 3
			INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pTarg ON fs.StaffingID = pTarg.StaffingID AND pTarg.BudgetPhaseID = 2
			INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pFinal ON fs.StaffingID = pFinal.StaffingID AND pFinal.BudgetPhaseID = 3
		WHERE fs.UnitTypeID = 159
)
SELECT
	fs.StaffingID,
	fs.BudgetConfigID, 
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.ProductiveClassID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	fs.VariabilityID,
	fs.UnitTypeID,
	
	bTarg.LockType as TargetLockType,
	bTarg.LockFlag as TargetLockFlag,
	bFinal.LockType as BudgetLockType,
	bFinal.LockFlag as BudgetLockFlag,
	pFinal.LockType as ProjectionLockType,
	pFinal.LockFlag as ProjectionLockFlag,
	
	CASE WHEN bFinal.LockType = 6 THEN 1 ELSE 0 END AS BudgetSpreadsLockFlag,
	
	CASE WHEN bFinal.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag,
	CASE WHEN bTarg.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag,
	CASE WHEN pFinal.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag,
	
	wr.TargetLockType as WageRateTargetLockType,
	wr.TargetLockFlag as WageRateTargetLockFlag,
	wr.BudgetLockType as WageRateBudgetLockType,
	wr.BudgetLockFlag as WageRateBudgetLockFlag,
	wr.ProjectionLockType as WageRateProjectionLockType,
	wr.ProjectionLockFlag as WageRateProjectionLockFlag,
	
	bTarg.AdjustedValueTotal,
	
	bFinal.AdjustedValueTotal as ManagerAdjustedValueTotal,
	pFinal.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal,
	
	pTarg.AdjustedValueTotal as AdjustedProjectionValueTotal,
	
	hist.ActualYTDValueTotal,
	hist.CurrentYearBudgetTotal,
	hist.PriorYearActualValueTotal,
	
	fs.InitialBudgetTotal,
	fs.InitialProjectionTotal,
	
	-- Target Montly Values
	bTarg.AdjustedValue01 AS AdjustedValue01, 
	bTarg.AdjustedValue02 AS AdjustedValue02, 
	bTarg.AdjustedValue03 AS AdjustedValue03, 
	bTarg.AdjustedValue04 AS AdjustedValue04, 
	bTarg.AdjustedValue05 AS AdjustedValue05, 
	bTarg.AdjustedValue06 AS AdjustedValue06, 
	bTarg.AdjustedValue07 AS AdjustedValue07, 
	bTarg.AdjustedValue08 AS AdjustedValue08, 
	bTarg.AdjustedValue09 AS AdjustedValue09, 
	bTarg.AdjustedValue10 AS AdjustedValue10, 
	bTarg.AdjustedValue11 AS AdjustedValue11, 
	bTarg.AdjustedValue12 AS AdjustedValue12,
	
	-- Budgeted Monthly Values
	bFinal.AdjustedValue01 AS ManagerAdjustedValue01, 
	bFinal.AdjustedValue02 AS ManagerAdjustedValue02, 
	bFinal.AdjustedValue03 AS ManagerAdjustedValue03, 
	bFinal.AdjustedValue04 AS ManagerAdjustedValue04, 
	bFinal.AdjustedValue05 AS ManagerAdjustedValue05, 
	bFinal.AdjustedValue06 AS ManagerAdjustedValue06, 
	bFinal.AdjustedValue07 AS ManagerAdjustedValue07, 
	bFinal.AdjustedValue08 AS ManagerAdjustedValue08, 
	bFinal.AdjustedValue09 AS ManagerAdjustedValue09, 
	bFinal.AdjustedValue10 AS ManagerAdjustedValue10, 
	bFinal.AdjustedValue11 AS ManagerAdjustedValue11, 
	bFinal.AdjustedValue12 AS ManagerAdjustedValue12,
	
	-- Projected Monthly Values
	pTarg.AdjustedValue01 AS AdjustedProjectionValue01, 
	pTarg.AdjustedValue02 AS AdjustedProjectionValue02, 
	pTarg.AdjustedValue03 AS AdjustedProjectionValue03, 
	pTarg.AdjustedValue04 AS AdjustedProjectionValue04, 
	pTarg.AdjustedValue05 AS AdjustedProjectionValue05, 
	pTarg.AdjustedValue06 AS AdjustedProjectionValue06, 
	pTarg.AdjustedValue07 AS AdjustedProjectionValue07, 
	pTarg.AdjustedValue08 AS AdjustedProjectionValue08, 
	pTarg.AdjustedValue09 AS AdjustedProjectionValue09, 
	pTarg.AdjustedValue10 AS AdjustedProjectionValue10, 
	pTarg.AdjustedValue11 AS AdjustedProjectionValue11, 
	pTarg.AdjustedValue12 AS AdjustedProjectionValue12,
	
	pFinal.AdjustedValue01 AS ManagerAdjustedProjectionValue01, 
	pFinal.AdjustedValue02 AS ManagerAdjustedProjectionValue02, 
	pFinal.AdjustedValue03 AS ManagerAdjustedProjectionValue03, 
	pFinal.AdjustedValue04 AS ManagerAdjustedProjectionValue04, 
	pFinal.AdjustedValue05 AS ManagerAdjustedProjectionValue05, 
	pFinal.AdjustedValue06 AS ManagerAdjustedProjectionValue06, 
	pFinal.AdjustedValue07 AS ManagerAdjustedProjectionValue07, 
	pFinal.AdjustedValue08 AS ManagerAdjustedProjectionValue08, 
	pFinal.AdjustedValue09 AS ManagerAdjustedProjectionValue09, 
	pFinal.AdjustedValue10 AS ManagerAdjustedProjectionValue10, 
	pFinal.AdjustedValue11 AS ManagerAdjustedProjectionValue11, 
	pFinal.AdjustedValue12 AS ManagerAdjustedProjectionValue12
FROM [fp].[ArchiveFactStaffing] fs (READUNCOMMITTED)
	INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bTarg ON fs.StaffingID = bTarg.StaffingID AND bTarg.BudgetPhaseID = 2
	INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bFinal ON fs.StaffingID = bFinal.StaffingID AND bFinal.BudgetPhaseID = 3
	INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pTarg ON fs.StaffingID = pTarg.StaffingID AND pTarg.BudgetPhaseID = 2
	INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pFinal ON fs.StaffingID = pFinal.StaffingID AND pFinal.BudgetPhaseID = 3
	INNER JOIN [fp].[ArchiveFactStaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
	INNER JOIN WageRate wr
		ON fs.BudgetConfigID = wr.BudgetConfigID
		AND fs.EntityGroupConfigID = wr.EntityGroupConfigID
		AND fs.DepartmentID = wr.DepartmentID
		AND fs.JobCodeID = wr.JobCodeID
		AND fs.PayCodeGroupID = wr.PayCodeGroupID
		AND fs.ProductiveClassID = wr.ProductiveClassID
		AND fs.ProviderID = wr.ProviderID
		AND fs.ProviderTypeID = wr.ProviderTypeID
		AND fs.ProviderSpecialtyID = wr.ProviderSpecialtyID
		AND fs.ProviderLineItemID = wr.ProviderLineItemID
		AND fs.SubsectionID = wr.SubsectionID
GO


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

-- fp.viewArchiveFactStatisticsBudget_HistoryViewer
CREATE VIEW fp.viewArchiveFactStatistics_HistoryViewer
AS
SELECT
	ov.StatisticsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.PatientClassID, 
	ov.PayorID, 
	ov.ProviderID,
	ov.ProviderTypeID,
	ov.ProviderSpecialtyID,
	ov.ProviderLineItemID,
	ov.SubsectionID,
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, 
	ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.ArchiveFactStatistics gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, 
	ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStatistics gl 
		INNER JOIN fp.ArchiveFactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStatistics gl 
		INNER JOIN fp.ArchiveFactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewArchiveFactStatisticsProjection_HistoryViewer
CREATE VIEW fp.viewArchiveFactStatisticsProjection_HistoryViewer
AS
SELECT
	ov.StatisticsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.PatientClassID, 
	ov.PayorID, 
	ov.ProviderID,
	ov.ProviderTypeID,
	ov.ProviderSpecialtyID,
	ov.ProviderLineItemID,
	ov.SubsectionID,
	ov.UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, 
	ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.ArchiveFactStatistics gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, 
	ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStatistics gl 
		INNER JOIN fp.ArchiveFactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.ArchiveFactStatistics gl 
		INNER JOIN fp.ArchiveFactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewArchiveFactStatistics_Pivoted
CREATE VIEW [fp].[viewArchiveFactStatistics_Pivoted]
AS
SELECT 
	stat.StatisticsID,
	stat.BudgetConfigID,
	stat.EntityGroupConfigID,
	stat.DepartmentID,
	stat.FinancialReportingID,
	stat.PayorID,
	stat.PatientClassID,
	stat.EntityID,
	stat.AccountID,
	bc.FiscalYearID,
	stat.UnitTypeID,
	stat.ProviderID,
	stat.ProviderTypeID,
	stat.ProviderSpecialtyID,
	stat.ProviderLineItemID,
	stat.SubsectionID,
	fbdgt.LockType as BudgetLockType,
	fbdgt.LockFlag as BudgetLockFlag,
	fproj.LockType as ProjectionLockType,
	fproj.LockFlag as ProjectionLockFlag,
	
	CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag,
	CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag,
	CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag,
	
	fbdgt.AdjustedValueTotal,
	dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal,
	
	fproj.AdjustedValueTotal as AdjustedProjectionValueTotal,
	dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal,
	
	hist.PriorYearActualValueTotal as PriorYearActualValueTotal,
	hist.ActualYTDValueTotal as ActualYTDValueTotal,
	hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal,
	
	stat.InitialBudgetTotal,
	stat.InitialProjectionTotal,
	
	dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12,
	
	fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12,
	fproj.AdjustedValue01 as AdjustedProjectionValue01, fproj.AdjustedValue02 as AdjustedProjectionValue02, fproj.AdjustedValue03 as AdjustedProjectionValue03, fproj.AdjustedValue04 as AdjustedProjectionValue04, fproj.AdjustedValue05 as AdjustedProjectionValue05, fproj.AdjustedValue06 as AdjustedProjectionValue06, fproj.AdjustedValue07 as AdjustedProjectionValue07, fproj.AdjustedValue08 as AdjustedProjectionValue08, fproj.AdjustedValue09 as AdjustedProjectionValue09, fproj.AdjustedValue10 as AdjustedProjectionValue10, fproj.AdjustedValue11 as AdjustedProjectionValue11, fproj.AdjustedValue12 as AdjustedProjectionValue12,
	dproj.AdjustedValue01 as ManagerAdjustedProjectionValue01, dproj.AdjustedValue02 as ManagerAdjustedProjectionValue02, dproj.AdjustedValue03 as ManagerAdjustedProjectionValue03, dproj.AdjustedValue04 as ManagerAdjustedProjectionValue04, dproj.AdjustedValue05 as ManagerAdjustedProjectionValue05, dproj.AdjustedValue06 as ManagerAdjustedProjectionValue06, dproj.AdjustedValue07 as ManagerAdjustedProjectionValue07, dproj.AdjustedValue08 as ManagerAdjustedProjectionValue08, dproj.AdjustedValue09 as ManagerAdjustedProjectionValue09, dproj.AdjustedValue10 as ManagerAdjustedProjectionValue10, dproj.AdjustedValue11 as ManagerAdjustedProjectionValue11, dproj.AdjustedValue12 as ManagerAdjustedProjectionValue12
FROM 
	fp.ArchiveFactStatistics stat
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON stat.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN fp.ArchiveFactStatisticsBudget fbdgt with (readuncommitted) ON stat.StatisticsID = fbdgt.StatisticsID and fbdgt.BudgetPhaseID = 2
	INNER JOIN fp.ArchiveFactStatisticsBudget dbdgt with (readuncommitted) ON stat.StatisticsID = dbdgt.StatisticsID and dbdgt.BudgetPhaseID = 3
	INNER JOIN fp.ArchiveFactStatisticsProjection fproj with (readuncommitted) ON stat.StatisticsID = fproj.StatisticsID and fproj.BudgetPhaseID = 2
	INNER JOIN fp.ArchiveFactStatisticsProjection dproj with (readuncommitted) ON stat.StatisticsID = dproj.StatisticsID and dproj.BudgetPhaseID = 3
	INNER JOIN fp.ArchiveFactStatisticsHistory hist with (readuncommitted) ON stat.StatisticsID = hist.StatisticsID
GO


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

-- fp.viewBaseBudgetSnapshotWithNameConcat
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2024-12-04  MY      JAZZ-80433		Initial
*************************************************************/
-- This is needed because otherwise score blows up on trying to find the column
CREATE   VIEW [fp].[viewBaseBudgetSnapshotWithNameConcat]
AS
	SELECT
		SnapshotID,
		BudgetConfigID,
		MemberGUID,
		AuthorGUID,
		AuthorName,
		AdjustmentsStampedOff,
		DateCreatedUTC,
		DateProcessedUTC,
		-- Only doing this because I know if we don't CCHS will complain about the date format in the EU
		(Name + ' - ' + CASE WHEN ISNULL((SELECT Value FROM fw.SystemSetting WHERE Name = 'System Culture'), 'en-US') = 'en-US' 
			THEN FORMAT(DateCreatedUTC, 'MM-dd-yyyy HH:mm:ss') 
			ELSE FORMAT(DateCreatedUTC, 'yyyy-MM-dd HH:mm:ss') END) AS Name,
		Comment,
		'00000000-0000-0000-0000-000000000000' AS HistoryItemGUID,
		TransactionID
	FROM [fp].[BudgetSnapshot]
GO


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

-- fp.viewBenefitsAccounts
CREATE VIEW [fp].[viewBenefitsAccounts]
AS
	SELECT acc.*
	FROM [fw].[DimAccount] acc
	INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID
	WHERE aph.Name LIKE '%Benefits%'
GO


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

-- fp.viewBenefitsAdjustment
CREATE VIEW fp.viewBenefitsAdjustment
AS 
SELECT [AdjustmentGUID]
      ,[BudgetConfigGUID]
      ,[AdjustmentType]
      ,[Value]
      ,[AdjustmentFilterJSON]
      ,[GroupingHierarchyJSON]
      ,[AdjustedProperty]
      ,[Comment]
      ,[AuthorGUID]
      ,[AuthorFullName]
      ,[LastModifiedDateUtc]
      ,[DateCreatedUtc]
      ,[GroupingGUID]
      ,[UnitTypeID]
      ,[TimeClassID]
      ,[BudgetPhaseID]
      ,[ClassificationGroupID]
      ,[ClassificationCategoryID]
      ,[IsRecordDeleted]
      ,[DimensionMemberJson]
	  ,[AdjustmentID]
	  ,[IsErrored]
FROM [fp].[BenefitsAdjustment]
WHERE IsRecordDeleted = 0;
GO


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

-- fp.viewBenefitsAdjustmentImport
CREATE VIEW fp.viewBenefitsAdjustmentImport
AS 
SELECT [RowID]
      ,[AdjustmentGUID]
      ,[DepartmentID]
      ,[AccountID]
      ,[FinancialReportingID]
      ,[EntityID]
      ,[FiscalYearID]
      ,[UnitTypeID]
      ,[FiscalMonthID]
      ,[Value]
      ,[Version]
      ,[TimeClassID]
      ,[IsRecordDeleted]
	  ,[AdjustmentID]
  FROM [fp].[BenefitsAdjustmentImport]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewBenefitsSpreadUnlockData
CREATE VIEW fp.viewBenefitsSpreadUnlockData
AS 

SELECT [RowID]
      ,[BudgetConfigID]
      ,[AdjustmentGUID]
      ,[EntityID]
      ,[DepartmentID]
      ,[AccountID]
      ,[FinancialReportingID]
      ,[Version]
      ,[Value01]
      ,[Value02]
      ,[Value03]
      ,[Value04]
      ,[Value05]
      ,[Value06]
      ,[Value07]
      ,[Value08]
      ,[Value09]
      ,[Value10]
      ,[Value11]
      ,[Value12]
      ,[IsRecordDeleted]
  FROM [fp].[BenefitsSpreadUnlockData]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewBenefitsSpreads
CREATE VIEW fp.viewBenefitsSpreads
AS
    SELECT [BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID]
    FROM [fp].[BenefitsSpreads] with (readuncommitted)
    WHERE GlobalSpreadID = 1

    UNION ALL

    SELECT bs.[BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID]
    FROM [fp].[BenefitsSpreads] bs with (readuncommitted)
    INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID
    WHERE bs.GlobalSpreadID > 1
GO


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

-- fp.viewBudgetConfigSetting
CREATE VIEW fp.viewBudgetConfigSetting
 AS
	SELECT bc.BudgetConfigID, bc.BudgetConfigName, bc.IsActive AS BudgetConfigIsActive, def.Name, def.Description, sett.Value, def.DefaultValue
	FROM [fp].[BudgetConfigSetting] sett
		INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON sett.SettingID = def.SettingID
		INNER JOIN [fp].[BudgetConfig] bc ON sett.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewBudgetConfig_DEBUG
CREATE VIEW fp.viewBudgetConfig_DEBUG
 AS
	SELECT bc.BudgetConfigGUID, bc.BudgetConfigID, bc.FiscalYearID AS BudgetConfigYear, bc.BudgetConfigName AS BCName, bc.IsActive, ec.EntityGroupConfigGUID, ec.EntityGroupConfigID, ec.Name AS ECName, ecm.Entities, 
		ServiceLineEncounterFiscalYearID AS SLCV_FY, ServiceLineEncounterTimeClassID AS SLCV_TC, DepartmentChargeVolumeFiscalYearID AS DCV_FY, DepartmentChargeVolumeTimeClassID AS DCV_TC, StatisticsFiscalYearID AS STAT_FY, StatisticsTimeClassID AS STAT_TC, 
		PayrollFiscalYearID AS PR_FY, PayrollTimeClassID AS PR_TC, BenefitsFiscalYearID AS BEN_FY, BenefitsTimeClassID AS BEN_TC, AccountFiscalYearID AS AC_FY, AccountTimeClassID AS AC_TC, CostingConfigGUID AS CostingGUID, CostingConfigTimeClassID AS Costing_TC,
		ec.RevenueAndDeductionsFiscalYearID AS RANDD_FY, ec.RevenueAndDeductionsTimeClassID AS RANDD_TC, ec.IsRosterUsed, ec.IsBudgetLockDown, ec.ParentEntityGroupConfigGuid, ec.StatisticsModel, bc.MonthsLoaded
	FROM [fp].[EntityGroupConfig] ec 
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = ec.BudgetConfigGUID
		INNER JOIN (SELECT DISTINCT EntityGroupConfigGUID, 
	            (
	                Select CAST(ecm1.EntityID AS VARCHAR(MAX)) + ',' AS [text()]
	                From [fp].[EntityGroupConfigMapping] ecm1
	                Where ecm1.EntityGroupConfigGUID = ecm2.EntityGroupConfigGUID
	                ORDER BY ecm1.EntityGroupConfigGUID
	                For XML PATH ('')
	            ) Entities
	        From [fp].[EntityGroupConfigMapping] ecm2) ecm ON ec.EntityGroupConfigGUID = ecm.EntityGroupConfigGUID
GO


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

-- fp.viewChargeVolumeAdjustmentImport_Pivoted
CREATE VIEW  [fp].[viewChargeVolumeAdjustmentImport_Pivoted]  
 AS
 SELECT
		AdjustmentGUID,
		DepartmentID,
		ServiceLineID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		ChargeCodeID,
		EntityID,
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		TimeClassID,
		IsRecordDeleted,
		AdjustmentID,
		[Month01],
		[Month02],
		[Month03],
		[Month04],
		[Month05],
		[Month06],
		[Month07],
		[Month08],
		[Month09],
		[Month10],
		[Month11],
		[Month12]
 FROM (SELECT 	
 				AdjustmentGUID,
				DepartmentID,
				ServiceLineID,
				PatientClassID,
				AgeCohortID,
				MedicalSurgicalID,
				ChargeCodeID,
				EntityID,
				ServiceEntityID,
				MSDRGID,
				UBRevCodeID,
				PrimaryCPTID,
				ServiceProviderID,
				ServiceProviderSpecialtyID,
				PerformingProviderID,
				PerformingProviderSpecialtyID,
				BillingCPTID,
				TimeClassID,
				IsRecordDeleted,
				AdjustmentID,
				m.MonthColumnName,
				Value
		FROM [fp].[DepartmentChargeAdjustmentImport] imp
		INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = imp.FiscalMonthID
	) data
	PIVOT (SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pvt
WHERE IsRecordDeleted = 0;
GO


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

-- fp.viewChargeVolumeByPayorGroup
CREATE   VIEW fp.viewChargeVolumeByPayorGroup
AS
SELECT 
	cv.ChargeVolumeID,
	cv.BudgetConfigID,
	cv.EntityGroupConfigID,
	cv.EntityID, 
	cv.DepartmentID, 
	cv.ServiceLineID,
	cv.PatientClassID,
	cv.AgeCohortID,
	cv.MedicalSurgicalID,
	cv.ChargeCodeID,
	cv.ServiceEntityID,
	cv.MSDRGID,
	cv.UBRevCodeID,
	cv.PrimaryCPTID,
	cv.ServiceProviderID,
	cv.ServiceProviderSpecialtyID,
	cv.PerformingProviderID,
	cv.PerformingProviderSpecialtyID,
	cv.BillingCPTID,
	mix.PayorGroupID,
	mix.BudgetMixPercentage,
	cv.BudgetDollarsAdjustedTotal * BudgetMixPercentage AS BudgetTotal,
	cv.TargetDollarsAdjustedTotal * BudgetMixPercentage AS TargetTotal,
	cv.ProjectionDollarsAdjustedTotal * ProjectionMixPercentage AS ProjectionTotal
FROM fp.ChargeVolume cv 
	INNER JOIN fp.ServiceLineEncounterToChargePayorMix mix on 
			mix.BudgetConfigID = cv.BudgetConfigID
		AND mix.EntityGroupConfigID = cv.EntityGroupConfigID
		AND	mix.PatientClassID = cv.PatientClassID
		AND mix.EntityID = cv.ServiceEntityID
		AND mix.ServiceLineID = cv.ServiceLineID
		AND mix.AgeCohortID = cv.AgeCohortID
		AND mix.MedicalSurgicalID = cv.MedicalSurgicalID
		AND mix.MSDRGID = cv.MSDRGID
		AND mix.CPTID = cv.PrimaryCPTID
		AND mix.ProviderID = cv.ServiceProviderID
GO


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

-- fp.viewChargeVolumeChangeHistoryGrouped
CREATE   VIEW fp.viewChargeVolumeChangeHistoryGrouped
 AS
	SELECT
		CAST(0 AS BIGINT) AS RowID,
		ch.ChargeVolumeID,
		ch.AdjustmentGUID,
		ch.AdjustmentType,
		ROW_NUMBER() OVER (PARTITION BY ch.ChargeVolumeID, ch.UnitTypeID, ch.TimeClassID, ch.BudgetPhaseID ORDER BY adj.DateCreatedUTC) - 1 AS SortOrder,
		SUM(ch.OldValue) AS OldValue,
		SUM(ch.NewValue) AS NewValue,
		ch.UnitTypeID,
		ch.TimeClassID,
		ch.BudgetPhaseID
	FROM [fp].[ChargeVolumeChangeHistory] ch
		INNER JOIN [fp].[DepartmentChargeVolumeAdjustment] adj ON ch.AdjustmentGUID = adj.AdjustmentGUID
	GROUP BY ch.ChargeVolumeID,
	    ch.UnitTypeID,
	    ch.TimeClassID,
	    ch.BudgetPhaseID,
	    ch.AdjustmentGUID,
	    ch.AdjustmentType,
	    adj.DateCreatedUTC
GO


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

-- fp.viewChargeVolumeChangeHistoryWithRollUpDetail
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	2-22-2023  MY      JAZZ-46241		Removed 1000 row limit
*************************************************************/
CREATE   VIEW fp.viewChargeVolumeChangeHistoryWithRollUpDetail
AS
	SELECT slech.RowID, slech.ChargeVolumeID, slech.AdjustmentGUID, slech.AdjustmentType, slech.FiscalMonthID, slech.UnitTypeID, slech.TimeClassID, slech.BudgetPhaseID, slech.OldValue, slech.NewValue, slech.BudgetConfigID, slech.DateCreatedUTC, slea.DateCreatedUTC AS AdjustmentDateCreatedUTC, 
		slea.GroupingGUID AS AdjustmentGroupingGUID, CASE WHEN slea.AdjustmentType IN (0, 2, 3) AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' THEN slea2.AdjustmentGUID ELSE slea.AdjustmentGUID END ReportingAdjustmentGUID
	FROM fp.ChargeVolumeChangeHistory slech
		INNER JOIN fp.DepartmentChargeVolumeAdjustment slea ON slech.AdjustmentGUID = slea.AdjustmentGUID
		LEFT JOIN fp.DepartmentChargeVolumeAdjustment slea2 ON slea.GroupingGUID = slea2.GroupingGUID AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' AND slea2.AdjustmentType IN (12, 13, 14)
GO


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

-- fp.viewChargeVolumeChangeHistory_Pivoted
CREATE VIEW  fp.viewChargeVolumeChangeHistory_Pivoted  
 AS
WITH months AS 
(
	SELECT 
		FiscalMonthID, 
		REPLACE(MonthColumnName, 'Month', 'OldValue') AS OldMonthColumnName, 
		REPLACE(MonthColumnName, 'Month', 'NewValue') AS NewMonthColumnName 
	FROM fw.DimFiscalMonth
)
SELECT 
	ChargeVolumeID, 
	AdjustmentGUID, 
	UnitTypeID,
	TimeClassID ,
	BudgetPhaseID ,
	BudgetConfigID ,
	AdjustmentType ,
	SUM(pvt2.OldValue01) AS OldValue01,
	SUM(pvt2.OldValue02) AS OldValue02,
	SUM(pvt2.OldValue03) AS OldValue03,
	SUM(pvt2.OldValue04) AS OldValue04,
	SUM(pvt2.OldValue05) AS OldValue05,
	SUM(pvt2.OldValue06) AS OldValue06,
	SUM(pvt2.OldValue07) AS OldValue07,
	SUM(pvt2.OldValue08) AS OldValue08,
	SUM(pvt2.OldValue09) AS OldValue09,
	SUM(pvt2.OldValue10) AS OldValue10,
	SUM(pvt2.OldValue11) AS OldValue11,
	SUM(pvt2.OldValue12) AS OldValue12,	
	SUM(pvt2.NewValue01) AS NewValue01,	
	SUM(pvt2.NewValue02) AS NewValue02,	
	SUM(pvt2.NewValue03) AS NewValue03,	
	SUM(pvt2.NewValue04) AS NewValue04,	
	SUM(pvt2.NewValue05) AS NewValue05,	
	SUM(pvt2.NewValue06) AS NewValue06,	
	SUM(pvt2.NewValue07) AS NewValue07,	
	SUM(pvt2.NewValue08) AS NewValue08,	
	SUM(pvt2.NewValue09) AS NewValue09,	
	SUM(pvt2.NewValue10) AS NewValue10,	
	SUM(pvt2.NewValue11) AS NewValue11,	
	SUM(pvt2.NewValue12) AS NewValue12
FROM 
	(
		SELECT 
			ChargeVolumeID,
			AdjustmentGUID,
			AdjustmentType,
			UnitTypeID,
			TimeClassID ,
			BudgetPhaseID ,
			BudgetConfigID ,
			m.OldMonthColumnName,
			m.NewMonthColumnName,
			OldValue, 
			NewValue 
		FROM [fp].[ChargeVolumeChangeHistory] ch
			INNER JOIN months m ON m.FiscalMonthID = ch.FiscalMonthID
	) data
	PIVOT (SUM(OldValue) for OldMonthColumnName in ([OldValue01],[OldValue02],[OldValue03],[OldValue04],[OldValue05],[OldValue06],[OldValue07],[OldValue08],[OldValue09],[OldValue10],[OldValue11],[OldValue12])) as pvt
	PIVOT (SUM(NewValue) for NewMonthColumnName in ([NewValue01],[NewValue02],[NewValue03],[NewValue04],[NewValue05],[NewValue06],[NewValue07],[NewValue08],[NewValue09],[NewValue10],[NewValue11],[NewValue12])) as pvt2
GROUP BY 
	ChargeVolumeID, 
	AdjustmentGUID, 
	UnitTypeID,
	TimeClassID,
	BudgetPhaseID,
	BudgetConfigID,
	AdjustmentType;
GO


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

-- fp.viewChargeVolumeSpreadUnlockData
CREATE VIEW fp.viewChargeVolumeSpreadUnlockData
AS 
/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1	 2022-09-01	 JB		 JAZZ-32095	Remove Payor and PayorGroupID from joins.
	*************************************************************/	 
SELECT [RowID]
      ,[BudgetConfigID]
      ,[AdjustmentGUID]
      ,[EntityID]
      ,[DepartmentID]
      ,[PatientClassID]
      ,[ServiceLineID]
      ,[AgeCohortID]
      ,[MedicalSurgicalID]
      ,[ChargeCodeID]
	   ,[ServiceEntityID]
      ,[MSDRGID]
      ,[UBRevCodeID]
      ,[PrimaryCPTID]
      ,[ServiceProviderID]
      ,[ServiceProviderSpecialtyID]
      ,[PerformingProviderID]
      ,[PerformingProviderSpecialtyID]
      ,[BillingCPTID]
      ,[Version]
      ,[Value01]
      ,[Value02]
      ,[Value03]
      ,[Value04]
      ,[Value05]
      ,[Value06]
      ,[Value07]
      ,[Value08]
      ,[Value09]
      ,[Value10]
      ,[Value11]
      ,[Value12]
      ,[IsRecordDeleted]
  FROM [fp].[ChargeVolumeSpreadUnlockData]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewChargeVolumeSpreads
CREATE VIEW [fp].[viewChargeVolumeSpreads]
AS
    SELECT [BudgetConfigID], [DepartmentID], [ServiceLineID], [ChargeCodeID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID]
    FROM [fp].[ChargeVolumeSpreads] with (readuncommitted)
    WHERE GlobalSpreadID = 1

    UNION ALL

    SELECT bs.[BudgetConfigID], [DepartmentID], [ServiceLineID], [ChargeCodeID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID]
    FROM [fp].[ChargeVolumeSpreads] bs with (readuncommitted)
    INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID
    WHERE bs.GlobalSpreadID > 1
GO


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

-- fp.viewChargeVolume_BudgetAdjusted
CREATE   VIEW  fp.viewChargeVolume_BudgetAdjusted  
 AS
 /**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			 Description
 ** 1 	 2023-02-13  NT  	 JAZZ-48268  Create ChargeVolume view for Budget adjusted only
 ** 2 	 2023-03-08  MY  	 JAZZ-48307  Remove unnecessary history join
 *************************************************************/
 	SELECT cv.[ChargeVolumeID]
      ,cv.[BudgetConfigID]
      ,cv.[EntityGroupConfigID]
      ,cv.[EntityID]
      ,cv.[DepartmentID]
      ,cv.[ServiceLineID]
      ,cv.[PatientClassID]
      ,cv.[AgeCohortID]
      ,cv.[MedicalSurgicalID]
      ,cv.[ChargeCodeID]
      ,cv.[ServiceEntityID]
      ,cv.[MSDRGID]
      ,cv.[UBRevCodeID]
      ,cv.[PrimaryCPTID]
      ,cv.[ServiceProviderID]
      ,cv.[ServiceProviderSpecialtyID]
      ,cv.[PerformingProviderID]
      ,cv.[PerformingProviderSpecialtyID]
      ,cv.[BillingCPTID]
      ,cv.[UnitTypeID]
            
      ,cv.[BudgetAdjustedTotal]
      ,cv.[BudgetDollarsAdjustedTotal]
      
      ,cv.[BudgetAdjusted01]
      ,cv.[BudgetAdjusted02]
      ,cv.[BudgetAdjusted03]
      ,cv.[BudgetAdjusted04]
      ,cv.[BudgetAdjusted05]
      ,cv.[BudgetAdjusted06]
      ,cv.[BudgetAdjusted07]
      ,cv.[BudgetAdjusted08]
      ,cv.[BudgetAdjusted09]
      ,cv.[BudgetAdjusted10]
      ,cv.[BudgetAdjusted11]
      ,cv.[BudgetAdjusted12]
      
      ,cv.[BudgetUnitsPerEncounterAdjusted01]
      ,cv.[BudgetUnitsPerEncounterAdjusted02]
      ,cv.[BudgetUnitsPerEncounterAdjusted03]
      ,cv.[BudgetUnitsPerEncounterAdjusted04]
      ,cv.[BudgetUnitsPerEncounterAdjusted05]
      ,cv.[BudgetUnitsPerEncounterAdjusted06]
      ,cv.[BudgetUnitsPerEncounterAdjusted07]
      ,cv.[BudgetUnitsPerEncounterAdjusted08]
      ,cv.[BudgetUnitsPerEncounterAdjusted09]
      ,cv.[BudgetUnitsPerEncounterAdjusted10]
      ,cv.[BudgetUnitsPerEncounterAdjusted11]
      ,cv.[BudgetUnitsPerEncounterAdjusted12]
      
      ,cv.[BudgetPrice01]
      ,cv.[BudgetPrice02]
      ,cv.[BudgetPrice03]
      ,cv.[BudgetPrice04]
      ,cv.[BudgetPrice05]
      ,cv.[BudgetPrice06]
      ,cv.[BudgetPrice07]
      ,cv.[BudgetPrice08]
      ,cv.[BudgetPrice09]
      ,cv.[BudgetPrice10]
      ,cv.[BudgetPrice11]
      ,cv.[BudgetPrice12]
      
      ,cv.[BudgetDollarsAdjusted01]
      ,cv.[BudgetDollarsAdjusted02]
      ,cv.[BudgetDollarsAdjusted03]
      ,cv.[BudgetDollarsAdjusted04]
      ,cv.[BudgetDollarsAdjusted05]
      ,cv.[BudgetDollarsAdjusted06]
      ,cv.[BudgetDollarsAdjusted07]
      ,cv.[BudgetDollarsAdjusted08]
      ,cv.[BudgetDollarsAdjusted09]
      ,cv.[BudgetDollarsAdjusted10]
      ,cv.[BudgetDollarsAdjusted11]
      ,cv.[BudgetDollarsAdjusted12]
FROM fp.ChargeVolume cv
GO


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

-- fp.viewChargeVolume_InitialBudget
CREATE   VIEW  fp.viewChargeVolume_InitialBudget  
 AS
 /**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-02-13  NT  	 JAZZ-48268  Create ChargeVolume view for inital budget only
 ** 2 	 2023-03-08  MY  	 JAZZ-48307  Remove unnecessary history join
 *************************************************************/
 	SELECT cv.[ChargeVolumeID]
      ,cv.[BudgetConfigID]
      ,cv.[EntityGroupConfigID]
      ,cv.[EntityID]
      ,cv.[DepartmentID]
      ,cv.[ServiceLineID]
      ,cv.[PatientClassID]
      ,cv.[AgeCohortID]
      ,cv.[MedicalSurgicalID]
      ,cv.[ChargeCodeID]
      ,cv.[ServiceEntityID]
      ,cv.[MSDRGID]
      ,cv.[UBRevCodeID]
      ,cv.[PrimaryCPTID]
      ,cv.[ServiceProviderID]
      ,cv.[ServiceProviderSpecialtyID]
      ,cv.[PerformingProviderID]
      ,cv.[PerformingProviderSpecialtyID]
      ,cv.[BillingCPTID]
      ,cv.[UnitTypeID]
            
      ,cv.[InitialBudgetTotal]
      ,cv.[InitialBudgetDollarsTotal]
      
      ,cv.[InitialBudget01]
      ,cv.[InitialBudget02]
      ,cv.[InitialBudget03]
      ,cv.[InitialBudget04]
      ,cv.[InitialBudget05]
      ,cv.[InitialBudget06]
      ,cv.[InitialBudget07]
      ,cv.[InitialBudget08]
      ,cv.[InitialBudget09]
      ,cv.[InitialBudget10]
      ,cv.[InitialBudget11]
      ,cv.[InitialBudget12]
      
      ,cv.[InitialBudgetUnitsPerEncounter01]
      ,cv.[InitialBudgetUnitsPerEncounter02]
      ,cv.[InitialBudgetUnitsPerEncounter03]
      ,cv.[InitialBudgetUnitsPerEncounter04]
      ,cv.[InitialBudgetUnitsPerEncounter05]
      ,cv.[InitialBudgetUnitsPerEncounter06]
      ,cv.[InitialBudgetUnitsPerEncounter07]
      ,cv.[InitialBudgetUnitsPerEncounter08]
      ,cv.[InitialBudgetUnitsPerEncounter09]
      ,cv.[InitialBudgetUnitsPerEncounter10]
      ,cv.[InitialBudgetUnitsPerEncounter11]
      ,cv.[InitialBudgetUnitsPerEncounter12]
      
      ,cv.[InitialBudgetDollars01]
      ,cv.[InitialBudgetDollars02]
      ,cv.[InitialBudgetDollars03]
      ,cv.[InitialBudgetDollars04]
      ,cv.[InitialBudgetDollars05]
      ,cv.[InitialBudgetDollars06]
      ,cv.[InitialBudgetDollars07]
      ,cv.[InitialBudgetDollars08]
      ,cv.[InitialBudgetDollars09]
      ,cv.[InitialBudgetDollars10]
      ,cv.[InitialBudgetDollars11]
      ,cv.[InitialBudgetDollars12]
FROM fp.ChargeVolume cv
GO


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

-- fp.viewChargeVolume_InitialProjection
CREATE   VIEW  fp.viewChargeVolume_InitialProjection  
 AS
  /**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-02-13  NT  	 JAZZ-48268  Create ChargeVolume view for inital projection only
 ** 2 	 2023-03-08  MY  	 JAZZ-48307  Remove unnecessary history join
 *************************************************************/
 	SELECT 
 	    cv.[ChargeVolumeID]
      ,cv.[BudgetConfigID]
      ,cv.[EntityGroupConfigID]
      ,cv.[EntityID]
      ,cv.[DepartmentID]
      ,cv.[ServiceLineID]
      ,cv.[PatientClassID]
      ,cv.[AgeCohortID]
      ,cv.[MedicalSurgicalID]
      ,cv.[ChargeCodeID]
      ,cv.[ServiceEntityID]
      ,cv.[MSDRGID]
      ,cv.[UBRevCodeID]
      ,cv.[PrimaryCPTID]
      ,cv.[ServiceProviderID]
      ,cv.[ServiceProviderSpecialtyID]
      ,cv.[PerformingProviderID]
      ,cv.[PerformingProviderSpecialtyID]
      ,cv.[BillingCPTID]
      ,cv.[UnitTypeID]
   
	   ,cv.[InitialProjectionTotal]
      ,cv.[InitialProjectionDollarsTotal]

      ,cv.[InitialProjection01]
      ,cv.[InitialProjection02]
      ,cv.[InitialProjection03]
      ,cv.[InitialProjection04]
      ,cv.[InitialProjection05]
      ,cv.[InitialProjection06]
      ,cv.[InitialProjection07]
      ,cv.[InitialProjection08]
      ,cv.[InitialProjection09]
      ,cv.[InitialProjection10]
      ,cv.[InitialProjection11]
      ,cv.[InitialProjection12]
      
      ,cv.[InitialProjectionUnitsPerEncounter01]
      ,cv.[InitialProjectionUnitsPerEncounter02]
      ,cv.[InitialProjectionUnitsPerEncounter03]
      ,cv.[InitialProjectionUnitsPerEncounter04]
      ,cv.[InitialProjectionUnitsPerEncounter05]
      ,cv.[InitialProjectionUnitsPerEncounter06]
      ,cv.[InitialProjectionUnitsPerEncounter07]
      ,cv.[InitialProjectionUnitsPerEncounter08]
      ,cv.[InitialProjectionUnitsPerEncounter09]
      ,cv.[InitialProjectionUnitsPerEncounter10]
      ,cv.[InitialProjectionUnitsPerEncounter11]
      ,cv.[InitialProjectionUnitsPerEncounter12]
      
      ,cv.[InitialBudgetDollars01]
      ,cv.[InitialBudgetDollars02]
      ,cv.[InitialBudgetDollars03]
      ,cv.[InitialBudgetDollars04]
      ,cv.[InitialBudgetDollars05]
      ,cv.[InitialBudgetDollars06]
      ,cv.[InitialBudgetDollars07]
      ,cv.[InitialBudgetDollars08]
      ,cv.[InitialBudgetDollars09]
      ,cv.[InitialBudgetDollars10]
      ,cv.[InitialBudgetDollars11]
      ,cv.[InitialBudgetDollars12]
FROM fp.ChargeVolume cv
GO


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

-- fp.viewChargeVolume_Pivoted
CREATE   VIEW [fp].[viewChargeVolume_Pivoted]
AS
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI			Description
	 ** 1	 2023-02-21	 MD		 JAZZ-50101	Initial
	 ** 2	 2023-03-08	 MY		 JAZZ-48307	Fix for missing Dollars Total
	*************************************************************/	 
	SELECT
		cv.ChargeVolumeID,
		cv.BudgetConfigID, 
		cv.EntityGroupConfigID,
		cv.EntityID,
		cv.DepartmentID,
		cv.ServiceLineID,
		cv.PatientClassID,
		cv.AgeCohortID,
		cv.MedicalSurgicalID,
		cv.ChargeCodeID,
		cv.UnitTypeID,
		cv.ServiceEntityID,
		cv.MSDRGID,
		cv.UBRevCodeID,
		cv.PrimaryCPTID,
		cv.BillingCPTID,
		cv.ServiceProviderID,
		cv.ServiceProviderSpecialtyID,
		cv.PerformingProviderID,
		cv.PerformingProviderSpecialtyID,
		
		cv.TargetLockType,
		cv.TargetLockFlag,
		cv.ProjectionLockType,
		cv.ProjectionLockFlag,
		
		cv.VariableDirectUnitCost,
		cv.InitialBudgetTotal,
		cv.InitialProjectionTotal,
	
		cv.TargetAdjustedTotal,	
		cv.BudgetAdjustedTotal,
		cv.ProjectionAdjustedTotal,

		cv.TargetDollarsAdjustedTotal,
		cv.BudgetDollarsAdjustedTotal,
		cv.ProjectionDollarsAdjustedTotal,
		cv.InitialBudgetDollarsTotal,
		cv.InitialProjectionDollarsTotal,
			
		hist.ActualYTDValueTotal,
		hist.PriorYearActualValueTotal,
		hist.CurrentYearBudgetTotal,
		hist.ActualYTDDollarValueTotal,
		hist.PriorYearActualDollarValueTotal,
		hist.CurrentYearBudgetDollarTotal,
	
		cv.TargetAdjusted01, 
		cv.TargetAdjusted02, 
		cv.TargetAdjusted03, 
		cv.TargetAdjusted04, 
		cv.TargetAdjusted05, 
		cv.TargetAdjusted06, 
		cv.TargetAdjusted07, 
		cv.TargetAdjusted08, 
		cv.TargetAdjusted09, 
		cv.TargetAdjusted10, 
		cv.TargetAdjusted11, 
		cv.TargetAdjusted12,
		
		cv.BudgetAdjusted01, 
		cv.BudgetAdjusted02, 
		cv.BudgetAdjusted03, 
		cv.BudgetAdjusted04, 
		cv.BudgetAdjusted05, 
		cv.BudgetAdjusted06, 
		cv.BudgetAdjusted07, 
		cv.BudgetAdjusted08, 
		cv.BudgetAdjusted09, 
		cv.BudgetAdjusted10, 
		cv.BudgetAdjusted11, 
		cv.BudgetAdjusted12,

		cv.ProjectionAdjusted01, 
		cv.ProjectionAdjusted02, 
		cv.ProjectionAdjusted03, 
		cv.ProjectionAdjusted04, 
		cv.ProjectionAdjusted05, 
		cv.ProjectionAdjusted06, 
		cv.ProjectionAdjusted07, 
		cv.ProjectionAdjusted08, 
		cv.ProjectionAdjusted09, 
		cv.ProjectionAdjusted10, 
		cv.ProjectionAdjusted11, 
		cv.ProjectionAdjusted12,

		cv.TargetDollarsAdjusted01, 
		cv.TargetDollarsAdjusted02, 
		cv.TargetDollarsAdjusted03, 
		cv.TargetDollarsAdjusted04, 
		cv.TargetDollarsAdjusted05, 
		cv.TargetDollarsAdjusted06, 
		cv.TargetDollarsAdjusted07, 
		cv.TargetDollarsAdjusted08, 
		cv.TargetDollarsAdjusted09, 
		cv.TargetDollarsAdjusted10, 
		cv.TargetDollarsAdjusted11, 
		cv.TargetDollarsAdjusted12,

		cv.BudgetDollarsAdjusted01, 
		cv.BudgetDollarsAdjusted02, 
		cv.BudgetDollarsAdjusted03, 
		cv.BudgetDollarsAdjusted04, 
		cv.BudgetDollarsAdjusted05, 
		cv.BudgetDollarsAdjusted06, 
		cv.BudgetDollarsAdjusted07, 
		cv.BudgetDollarsAdjusted08, 
		cv.BudgetDollarsAdjusted09, 
		cv.BudgetDollarsAdjusted10, 
		cv.BudgetDollarsAdjusted11, 
		cv.BudgetDollarsAdjusted12,

		cv.ProjectionDollarsAdjusted01, 
		cv.ProjectionDollarsAdjusted02, 
		cv.ProjectionDollarsAdjusted03, 
		cv.ProjectionDollarsAdjusted04, 
		cv.ProjectionDollarsAdjusted05, 
		cv.ProjectionDollarsAdjusted06, 
		cv.ProjectionDollarsAdjusted07, 
		cv.ProjectionDollarsAdjusted08, 
		cv.ProjectionDollarsAdjusted09, 
		cv.ProjectionDollarsAdjusted10, 
		cv.ProjectionDollarsAdjusted11, 
		cv.ProjectionDollarsAdjusted12
	FROM 
		[fp].[ChargeVolume] cv WITH (READUNCOMMITTED)
			INNER JOIN [fp].[ChargeVolumeHistory] hist WITH (READUNCOMMITTED) ON cv.ChargeVolumeID = hist.ChargeVolumeID
GO


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

-- fp.viewChargeVolume_ProjectionAdjusted
CREATE   VIEW  fp.viewChargeVolume_ProjectionAdjusted  
 AS
 /**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-02-13  NT  	 JAZZ-48268  Create ChargeVolume view for Projection adjusted only
 ** 2 	 2023-03-08  MY  	 JAZZ-48307  Remove unnecessary history join
 *************************************************************/
 	SELECT cv.[ChargeVolumeID]
      ,cv.[BudgetConfigID]
      ,cv.[EntityGroupConfigID]
      ,cv.[EntityID]
      ,cv.[DepartmentID]
      ,cv.[ServiceLineID]
      ,cv.[PatientClassID]
      ,cv.[AgeCohortID]
      ,cv.[MedicalSurgicalID]
      ,cv.[ChargeCodeID]
      ,cv.[ServiceEntityID]
      ,cv.[MSDRGID]
      ,cv.[UBRevCodeID]
      ,cv.[PrimaryCPTID]
      ,cv.[ServiceProviderID]
      ,cv.[ServiceProviderSpecialtyID]
      ,cv.[PerformingProviderID]
      ,cv.[PerformingProviderSpecialtyID]
      ,cv.[BillingCPTID]
      ,cv.[UnitTypeID]
            
      ,cv.[ProjectionAdjustedTotal]
      ,cv.[ProjectionDollarsAdjustedTotal]
      
      ,cv.[ProjectionAdjusted01]
      ,cv.[ProjectionAdjusted02]
      ,cv.[ProjectionAdjusted03]
      ,cv.[ProjectionAdjusted04]
      ,cv.[ProjectionAdjusted05]
      ,cv.[ProjectionAdjusted06]
      ,cv.[ProjectionAdjusted07]
      ,cv.[ProjectionAdjusted08]
      ,cv.[ProjectionAdjusted09]
      ,cv.[ProjectionAdjusted10]
      ,cv.[ProjectionAdjusted11]
      ,cv.[ProjectionAdjusted12]
      
      ,cv.[ProjectionUnitsPerEncounterAdjusted01]
      ,cv.[ProjectionUnitsPerEncounterAdjusted02]
      ,cv.[ProjectionUnitsPerEncounterAdjusted03]
      ,cv.[ProjectionUnitsPerEncounterAdjusted04]
      ,cv.[ProjectionUnitsPerEncounterAdjusted05]
      ,cv.[ProjectionUnitsPerEncounterAdjusted06]
      ,cv.[ProjectionUnitsPerEncounterAdjusted07]
      ,cv.[ProjectionUnitsPerEncounterAdjusted08]
      ,cv.[ProjectionUnitsPerEncounterAdjusted09]
      ,cv.[ProjectionUnitsPerEncounterAdjusted10]
      ,cv.[ProjectionUnitsPerEncounterAdjusted11]
      ,cv.[ProjectionUnitsPerEncounterAdjusted12]
      
      ,cv.[ProjectionPrice01]
      ,cv.[ProjectionPrice02]
      ,cv.[ProjectionPrice03]
      ,cv.[ProjectionPrice04]
      ,cv.[ProjectionPrice05]
      ,cv.[ProjectionPrice06]
      ,cv.[ProjectionPrice07]
      ,cv.[ProjectionPrice08]
      ,cv.[ProjectionPrice09]
      ,cv.[ProjectionPrice10]
      ,cv.[ProjectionPrice11]
      ,cv.[ProjectionPrice12]
      
      ,cv.[ProjectionDollarsAdjusted01]
      ,cv.[ProjectionDollarsAdjusted02]
      ,cv.[ProjectionDollarsAdjusted03]
      ,cv.[ProjectionDollarsAdjusted04]
      ,cv.[ProjectionDollarsAdjusted05]
      ,cv.[ProjectionDollarsAdjusted06]
      ,cv.[ProjectionDollarsAdjusted07]
      ,cv.[ProjectionDollarsAdjusted08]
      ,cv.[ProjectionDollarsAdjusted09]
      ,cv.[ProjectionDollarsAdjusted10]
      ,cv.[ProjectionDollarsAdjusted11]
      ,cv.[ProjectionDollarsAdjusted12]
FROM fp.ChargeVolume cv
GO


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

-- fp.viewChargeVolume_TargetAdjusted
CREATE   VIEW  fp.viewChargeVolume_TargetAdjusted  
 AS
 /**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-02-13  NT  	 JAZZ-48268  Create ChargeVolume view for Target adjusted only
 ** 2 	 2023-03-08  MY  	 JAZZ-48307  Remove unnecessary history join
 *************************************************************/
 	SELECT cv.[ChargeVolumeID]
      ,cv.[BudgetConfigID]
      ,cv.[EntityGroupConfigID]
      ,cv.[EntityID]
      ,cv.[DepartmentID]
      ,cv.[ServiceLineID]
      ,cv.[PatientClassID]
      ,cv.[AgeCohortID]
      ,cv.[MedicalSurgicalID]
      ,cv.[ChargeCodeID]
      ,cv.[ServiceEntityID]
      ,cv.[MSDRGID]
      ,cv.[UBRevCodeID]
      ,cv.[PrimaryCPTID]
      ,cv.[ServiceProviderID]
      ,cv.[ServiceProviderSpecialtyID]
      ,cv.[PerformingProviderID]
      ,cv.[PerformingProviderSpecialtyID]
      ,cv.[BillingCPTID]
      ,cv.[UnitTypeID]
            
      ,cv.[TargetAdjustedTotal]
      ,cv.[TargetDollarsAdjustedTotal]
      
      ,cv.[TargetAdjusted01]
      ,cv.[TargetAdjusted02]
      ,cv.[TargetAdjusted03]
      ,cv.[TargetAdjusted04]
      ,cv.[TargetAdjusted05]
      ,cv.[TargetAdjusted06]
      ,cv.[TargetAdjusted07]
      ,cv.[TargetAdjusted08]
      ,cv.[TargetAdjusted09]
      ,cv.[TargetAdjusted10]
      ,cv.[TargetAdjusted11]
      ,cv.[TargetAdjusted12]
      
      ,cv.[TargetUnitsPerEncounterAdjusted01]
      ,cv.[TargetUnitsPerEncounterAdjusted02]
      ,cv.[TargetUnitsPerEncounterAdjusted03]
      ,cv.[TargetUnitsPerEncounterAdjusted04]
      ,cv.[TargetUnitsPerEncounterAdjusted05]
      ,cv.[TargetUnitsPerEncounterAdjusted06]
      ,cv.[TargetUnitsPerEncounterAdjusted07]
      ,cv.[TargetUnitsPerEncounterAdjusted08]
      ,cv.[TargetUnitsPerEncounterAdjusted09]
      ,cv.[TargetUnitsPerEncounterAdjusted10]
      ,cv.[TargetUnitsPerEncounterAdjusted11]
      ,cv.[TargetUnitsPerEncounterAdjusted12]
      
      ,cv.[TargetPrice01]
      ,cv.[TargetPrice02]
      ,cv.[TargetPrice03]
      ,cv.[TargetPrice04]
      ,cv.[TargetPrice05]
      ,cv.[TargetPrice06]
      ,cv.[TargetPrice07]
      ,cv.[TargetPrice08]
      ,cv.[TargetPrice09]
      ,cv.[TargetPrice10]
      ,cv.[TargetPrice11]
      ,cv.[TargetPrice12]
      
      ,cv.[TargetDollarsAdjusted01]
      ,cv.[TargetDollarsAdjusted02]
      ,cv.[TargetDollarsAdjusted03]
      ,cv.[TargetDollarsAdjusted04]
      ,cv.[TargetDollarsAdjusted05]
      ,cv.[TargetDollarsAdjusted06]
      ,cv.[TargetDollarsAdjusted07]
      ,cv.[TargetDollarsAdjusted08]
      ,cv.[TargetDollarsAdjusted09]
      ,cv.[TargetDollarsAdjusted10]
      ,cv.[TargetDollarsAdjusted11]
      ,cv.[TargetDollarsAdjusted12]
FROM fp.ChargeVolume cv
GO


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

-- fp.viewDeductionsAccounts
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	8-9-2023  MY      JAZZ-58777		1Plan - Deductions flexing does not work for Fixed departments even when set to use Total Gross Charges in setup
*************************************************************/
CREATE   VIEW [fp].[viewDeductionsAccounts]
AS
	SELECT acc.*
	FROM [fw].[DimAccount] acc
	INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID
	WHERE aph.Name IN ('Deductions', 'Deductions - Charity and Bad Debt', 'Deductions - Reimbursement') -- Do not update this list unless you're adding to it. This view is used by multiple places to find all of the Deduction accounts in the system. Removing a value can lead to unexpected errors.
GO


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

-- fp.viewDeductionsFlexingConfig
CREATE VIEW [fp].[viewDeductionsFlexingConfig]
AS
SELECT 
		fc.EntityGroupConfigGUID,
		fc.DepartmentID,
		acct.AccountID,
		fc.FlexMethodID
	FROM [fp].[DeductionsFlexingConfig] fc
	CROSS APPLY (SELECT AccountID FROM [fp].[viewDeductionsAccounts]) acct
GO


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

-- fp.viewDepartmentAccessByUser
CREATE view fp.viewDepartmentAccessByUser
as
	select
		a.EntityGroupConfigID,
		a.Section,
		ra.IdentityGUID as UserGUID,
		REPLACE(ra.LootGroupID, 'DEPT|', '') as DepartmentID,
		MAX(a.AccessType) as AccessType
	from 
		[fp].[APESectionRoleAccess] a
		LEFT JOIN [dbo].[viewS3RoleAssignment] ra on ra.RoleID = a.RoleID
		INNER JOIN [fw].[DimDepartment] dept on 'DEPT|' + CAST(dept.DepartmentID as nvarchar(10)) = ra.LootGroupID
	where 
		a.budgetphaseid = 2
		and ra.lootgroupid like 'DEPT|%'
	group by
		a.EntityGroupConfigID,
		a.Section,
		ra.IdentityGUID,
		ra.LootGroupID
GO


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

-- fp.viewDepartmentChargeVolumeAdjustment
CREATE VIEW fp.viewDepartmentChargeVolumeAdjustment
AS 

SELECT [AdjustmentGUID]
      ,[BudgetConfigGUID]
      ,[AdjustmentType]
      ,[Value]
      ,[AdjustmentFilterJSON]
      ,[GroupingHierarchyJSON]
      ,[AdjustedProperty]
      ,[Comment]
      ,[AuthorGUID]
      ,[AuthorFullName]
      ,[LastModifiedDateUtc]
      ,[DateCreatedUtc]
      ,[GroupingGUID]
      ,[TimeClassID]
      ,[ClassificationGroupID]
      ,[ClassificationCategoryID]
      ,[IsRecordDeleted]
      ,[AffectedDataCount]
      ,[DimensionMemberJson]
	  ,[AdjustmentID]
	  ,[IsErrored]
  FROM [fp].[DepartmentChargeVolumeAdjustment]
  WHERE IsRecordDeleted = 0;
GO


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

-- fp.viewDepartmentChargeVolumeAdjustmentImport
CREATE VIEW fp.viewDepartmentChargeVolumeAdjustmentImport
AS 
/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1	 2022-09-01	 JB		 JAZZ-32095	Remove Payor and PayorGroupID from joins.
	*************************************************************/	 
SELECT [RowID]
      ,[AdjustmentGUID]
      ,[DepartmentID]
      ,[ServiceLineID]
      ,[PatientClassID]
      ,[AgeCohortID]
      ,[MedicalSurgicalID]
      ,[ChargeCodeID]
	  ,[ServiceEntityID]
      ,[MSDRGID]
      ,[UBRevCodeID]
      ,[PrimaryCPTID]
      ,[ServiceProviderID]
      ,[ServiceProviderSpecialtyID]
      ,[PerformingProviderID]
      ,[PerformingProviderSpecialtyID]
      ,[BillingCPTID]
      ,[Value]
      ,[Version]
      ,[EntityID]
      ,[TimeClassID]
      ,[FiscalMonthID]
      ,[IsRecordDeleted]
	  ,[AdjustmentID]
  FROM [fp].[DepartmentChargeAdjustmentImport]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewDependentByDriverStatisticsFlexConfigMapping
CREATE   VIEW fp.viewDependentByDriverStatisticsFlexConfigMapping
AS
SELECT
    EntityGroupConfigID,
	DepartmentID AS DependentDepartmentID,
	DependentStatisticAccountID AS DependentAccountID,
	SourceDepartmentID AS DriverDepartmentID,
	StatAccountID AS DriverAccountID
FROM fp.FlexConfigMapping
WHERE FlexingTypeID = 8 -- FlexDependentStatisticsByDriverStatistics
GO


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

-- fp.viewDimBudgetConfig
CREATE VIEW [fp].[viewDimBudgetConfig]
AS
	SELECT
		BudgetConfigID,
		BudgetConfigGUID AS MemberGUID,
		FiscalYearID,
		DateModified,
		DatePublished,
		BudgetConfigName AS Name,
		IsActive,
		Comments,
		'00000000-0000-0000-0000-000000000000' AS HistoryItemGUID,
		0 AS TransactionID
	FROM [fp].[BudgetConfig]
GO


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

-- fp.viewDimBudgetConfig_auto
--Last Modified 2/5/2018 7:18 PM
CREATE VIEW [fp].[viewDimBudgetConfig_auto]
AS
SELECT
   grpE945519B243042599E20EC7624B3FF68.[BudgetConfigID]
   ,grpE945519B243042599E20EC7624B3FF68.[Name]
   ,grpE945519B243042599E20EC7624B3FF68.[TransactionID]
   ,grpE945519B243042599E20EC7624B3FF68.[MemberGUID]
   ,grpE945519B243042599E20EC7624B3FF68.[HistoryItemGUID]
FROM [fp].[ViewDimBudgetConfig] grpE945519B243042599E20EC7624B3FF68
GO


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

-- fp.viewDimBudgetSnapshot
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2024-12-04  MY      JAZZ-80433		Update Name to Concat Date and Time
*************************************************************/
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2024-12-04  MY      JAZZ-80433		Update Name to Concat Date and Time
*************************************************************/
CREATE   VIEW [fp].[viewDimBudgetSnapshot]
AS
	SELECT
		SnapshotID,
		BudgetConfigID,
		MemberGUID,
		AuthorGUID,
		AuthorName,
		AdjustmentsStampedOff,
		DateCreatedUTC,
		DateProcessedUTC,
		Name,
		Comment,
		'00000000-0000-0000-0000-000000000000' AS HistoryItemGUID,
		TransactionID
	FROM [fp].[viewBaseBudgetSnapshotWithNameConcat]
GO


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

-- fp.viewDimBudgetSnapshot_auto
--Last Modified 12/9/2024 11:54 AM
CREATE VIEW [fp].[viewDimBudgetSnapshot_auto]
AS
SELECT
   grp9B2D0CB6369242248B72E41D9D831413.[SnapshotID]
   ,grp9B2D0CB6369242248B72E41D9D831413.[Name]
   ,grp9B2D0CB6369242248B72E41D9D831413.[TransactionID]
   ,grp9B2D0CB6369242248B72E41D9D831413.[MemberGUID]
  ,coalesce(grp9B2D0CB6369242248B72E41D9D831413.[HistoryItemGUID],'') as [HistoryItemGUID]
  ,coalesce(grp9B2D0CB6369242248B72E41D9D831413.[Comment],'') as [Comment]
   ,grp9B2D0CB6369242248B72E41D9D831413.[AdjustmentsStampedOff]
   ,grp9B2D0CB6369242248B72E41D9D831413.[DateCreatedUTC]
FROM [fp].[ViewDimBudgetSnapshot] grp9B2D0CB6369242248B72E41D9D831413
GO


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

-- fp.viewDimItemizationDataType
--Last Modified 5/26/2021 3:28 PM
CREATE VIEW [fp].[viewDimItemizationDataType]
AS
SELECT
   grp46FF9613EEC34DE4B2B4F9DFA90D18B5.[ItemizationDataTypeID]
   ,grp46FF9613EEC34DE4B2B4F9DFA90D18B5.[Name]
   ,grp46FF9613EEC34DE4B2B4F9DFA90D18B5.[MemberGUID]
FROM [fp].[DimItemizationDataType] grp46FF9613EEC34DE4B2B4F9DFA90D18B5 (readuncommitted)
GO


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

-- fp.viewDimPerformingProvider
CREATE VIEW [fp].[viewDimPerformingProvider] 
AS
	SELECT 
		PhysicianID AS [PerformingProviderID]
		,TransactionID
		,Physician
		,PhysicianCode AS [PhysicianCode]
		,FullName
		,PhysicianSpecialtyID
		,StateLicenseNumber
		,GroupAffiliation
		,NPI
		,MemberGUID
		,ProviderTypeID
		,HistoryItemGUID
		,Title
		,IsActive
		,ACOFlag
		,InMedicalGroup
		,FirstName
		,IsProvider
		,ProviderGroup
		,PhysicianGroupAffiliationID
		,EmployeeID
		,PhysicianTaxonomyID
		,IsFP
		,IsDS
		,EmailAddress
		,NPIPhysician
	
 ,[EmployeeCode] [EmployeeCode]
 ,[PhysicianGroupAffiliation] [PhysicianGroupAffiliation]
FROM [dss].[DimPhysician];
GO


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

-- fp.viewDimPerformingProvider_auto
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fp].[viewDimPerformingProvider_auto]
AS
SELECT
   grp6E30837FBA9B4380BB0834CE2978DBE1.[PerformingProviderID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[TransactionID]
  ,coalesce(grp6E30837FBA9B4380BB0834CE2978DBE1.[Physician],'') as [Physician]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianCode]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[FullName]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianSpecialtyID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[StateLicenseNumber]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[GroupAffiliation]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[NPI]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[MemberGUID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[ProviderTypeID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[HistoryItemGUID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[Title]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsActive]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[ACOFlag]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[InMedicalGroup]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[FirstName]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsProvider]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[ProviderGroup]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianGroupAffiliationID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[EmployeeID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianTaxonomyID]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsFP]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsDS]
   ,grp6E30837FBA9B4380BB0834CE2978DBE1.[EmailAddress]
  ,coalesce(grp6E30837FBA9B4380BB0834CE2978DBE1.[NPIPhysician],'') as [NPIPhysician]
   ,ISNULL([PHYSSPECIALTY].[Name], 'Not Specified') as [PhysicianSpecialty]
   ,ISNULL([PHYSSPECIALTY].[PhysicianSpecialtyCode], 'Not Specified') as [PhysicianSpecialtyCode]
   ,ISNULL([PHYSSPECIALTY].[Description], 'Not Specified') as [PhysicianSpecialtyDescription]
   ,ISNULL([PHYSSPECIALTY].[SpecialtyGroup], 'Not Specified') as [PhysicianSpecialtyGroup]
   ,ISNULL([PROVTYPE].[Name], 'Not Specified') as [ProviderTypeName]
   ,ISNULL([PROVTYPE].[ProviderTypeCode], 'Not Specified') as [ProviderTypeCode]
   ,ISNULL([PROVTYPE].[Description], 'Not Specified') as [ProviderTypeDescription]
   ,ISNULL([PHYSICIANGROUPAFFILIATION].[Name], 'Not Specified') as [PhysicianGroupAffiliation]
   ,ISNULL([PHYSICIANGROUPAFFILIATION].[PhysicianGroupAffiliationCode], 'Not Specified') as [PhysicianGroupAffiliationCode]
   ,ISNULL([PHYSICIANGROUPAFFILIATION].[Description], 'Not Specified') as [PhysicianGroupAffiliationDescription]
   ,ISNULL([EMP].[Code], 'Not Specified') as [EmployeeCode]
   ,ISNULL([PHYSTAX].[Name], 'Not Specified') as [PhysicianTaxonomy]
FROM [fp].[viewDimPerformingProvider] grp6E30837FBA9B4380BB0834CE2978DBE1 
   LEFT JOIN [dss].[viewDimPhysicianSpecialty] [PHYSSPECIALTY]  on [PHYSSPECIALTY].[PhysicianSpecialtyID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[PhysicianSpecialtyID]
   LEFT JOIN [clientdss].[viewDimProviderType] [PROVTYPE]  on [PROVTYPE].[ProviderTypeID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[ProviderTypeID]
   LEFT JOIN [dss].[viewDimPhysicianGroupAffiliation] [PHYSICIANGROUPAFFILIATION]  on [PHYSICIANGROUPAFFILIATION].[PhysicianGroupAffiliationID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[PhysicianGroupAffiliationID]
   INNER JOIN [fw].[viewDimEmployee] [EMP]  on [EMP].[EmployeeID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[EmployeeID]
   LEFT JOIN [clientdss].[viewDimPhysicianTaxonomy] [PHYSTAX]  on [PHYSTAX].[PhysicianTaxonomyID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[PhysicianTaxonomyID]
GO


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

-- fp.viewDimPhysician
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1	09-19-2023  MD      JAZZ-59502		Add physician column
*************************************************************/
CREATE   VIEW [fp].[viewDimPhysician]
AS
SELECT 
	PhysicianID as ProviderID, 
	PhysicianSpecialtyID, 
	MemberGUID, 
	FullName as Name, 
	PhysicianCode as ProviderCode, 
	ProviderTypeID,
	Physician
FROM dss.DimPhysician
GO


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

-- fp.viewDimSection
CREATE VIEW  fp.viewDimSection  
 AS
 SELECT CONVERT(INT, ROW_NUMBER() OVER (ORDER BY ps.SortOrder,  SubsectionID)) -1 AS SectionID,
        CASE WHEN ps.PlanSectionID = 2 THEN 'Charges'
             WHEN ps.PlanSectionID = 3 AND SubsectionID = 2 THEN 'Dependent Statistics'
             WHEN ps.PlanSectionID = 4 AND SubsectionID = 4 THEN 'Provider Compensation'
             WHEN ps.PlanSectionID = 7 AND SubSectionID = 5 THEN 'Reimbursement - Service Line'
             WHEN ps.PlanSectionID = 7 AND SubSectionID = 7 THEN 'Reimbursement - General Ledger'
             ELSE Description
       END AS Description,
       PlanSectionGUID AS MemberGUID,
       HistoryItemGUID
       FROM fp.PlanSection ps 
 LEFT JOIN fp.PlanSubSection pss on ps.PlanSectionID = pss.PlanSectionID
 WHERE ISNULL(SubSectionID, '') <> 6  -- Exluding Reimbursement Charges
GO


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

-- fp.viewDimSection_auto
--Last Modified 12/23/2024 10:16 AM
CREATE VIEW [fp].[viewDimSection_auto]
AS
SELECT
   grpAE25CD3C290A48A697B5C97D7FBE44E2.[SectionID]
  ,coalesce(grpAE25CD3C290A48A697B5C97D7FBE44E2.[Description],'') as [Description]
   ,grpAE25CD3C290A48A697B5C97D7FBE44E2.[MemberGUID]
, [grpAE25CD3C290A48A697B5C97D7FBE44E2].[HistoryItemGUID]FROM [fp].[viewDimSection] grpAE25CD3C290A48A697B5C97D7FBE44E2
GO


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

-- fp.viewDimServiceEntity
CREATE VIEW [fp].[viewDimServiceEntity] 
AS
	SELECT 
		EntityID AS [ServiceEntityID]
		,Name
		,Code AS [Code]
		,Description
		,SortOrder
		,EntityType
		,IsActive
		,CAPIsDefined
		,DSSIsDefined
		,OBIsDefined
		,OBBenefitsDepartmentID
		,OBHasGlobalStatisticsPlan
		,OBHasReimbursementPlan
		,OBHasServiceLinePlan
		,OBIsUsingProviderComp
		,SPIsDefined
		,SPGrossChargesPatientTypeRollup
		,SPGrossChargesPayorGroup
		,SPContractualsPatientTypeRollup
		,SPContractualsPayorGroup
		,SPIPVolumesPatientTypeRollup
		,SPIPVolumesPayorGroup
		,SPIPDaysPatientTypeRollup
		,SPIPDaysPayorGroup
		,SPOPVolumesPatientTypeRollup
		,SPOPVolumesPayorGroup
		,SPFTEsJobCodeGroup
		,SPSalariesJobCodeGroup
		,SPClinicGrossChargesPayorGroup
		,SPClinicContractualsPayorGroup
		,SPClinicPrimaryVolumePhysicianGroup
		,SPClinicSecondaryVolumePhysicianGroup
		,SPClinicFTEsPhysicianGroup
		,SPClinicSalariesPhysicianGroup
		,SPOperationsSLDrivenModelID
		,SPRollingForecastSLDrivenModelID
		,SPServiceLineForecastType
		,SecureGroupID
		,WorkWeekID
		,TransactionID
		,PayCycleID
		,HistoryItemGUID
		,MemberGUID
		,CAPDefaultSalesTax
		,FWIsDefined
		,EliminationsDepartmentID
	
 ,[OBBenefitsDepartment] [OBBenefitsDepartment]
FROM [fw].[DimEntity];
GO


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

-- fp.viewDimServiceEntity_auto
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fp].[viewDimServiceEntity_auto]
AS
SELECT
   grp5666302E7CA94A6685CFFA1BBE6A261F.[ServiceEntityID]
  ,coalesce(grp5666302E7CA94A6685CFFA1BBE6A261F.[Name],'') as [Name]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[Code]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[Description]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SortOrder]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[EntityType]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[IsActive]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[CAPIsDefined]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[DSSIsDefined]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBIsDefined]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBBenefitsDepartmentID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBHasGlobalStatisticsPlan]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBHasReimbursementPlan]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBHasServiceLinePlan]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBIsUsingProviderComp]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIsDefined]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPGrossChargesPatientTypeRollup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPGrossChargesPayorGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPContractualsPatientTypeRollup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPContractualsPayorGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPVolumesPatientTypeRollup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPVolumesPayorGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPDaysPatientTypeRollup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPDaysPayorGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPOPVolumesPatientTypeRollup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPOPVolumesPayorGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPFTEsJobCodeGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPSalariesJobCodeGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicGrossChargesPayorGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicContractualsPayorGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicPrimaryVolumePhysicianGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicSecondaryVolumePhysicianGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicFTEsPhysicianGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicSalariesPhysicianGroup]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPOperationsSLDrivenModelID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPRollingForecastSLDrivenModelID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPServiceLineForecastType]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[WorkWeekID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SecureGroupID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[TransactionID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[PayCycleID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[HistoryItemGUID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[MemberGUID]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[CAPDefaultSalesTax]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[FWIsDefined]
   ,grp5666302E7CA94A6685CFFA1BBE6A261F.[EliminationsDepartmentID]
   ,ISNULL([DEPT].[Name], 'Not Specified') as [OBBenefitsDepartment]
FROM [fp].[viewDimServiceEntity] grp5666302E7CA94A6685CFFA1BBE6A261F 
   INNER JOIN [fw].[viewDimDepartment] [DEPT]  on [DEPT].[DepartmentID] = [grp5666302E7CA94A6685CFFA1BBE6A261F].[OBBenefitsDepartmentID]
GO


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

-- fp.viewDimSubAccountCategory
--Last Modified 2/22/2022 10:18 AM
CREATE VIEW [fp].[viewDimSubAccountCategory]
AS
SELECT
   grp335A2DAAD2584078A30A81CA9B64823B.[SubAccountCategoryID]
   ,grp335A2DAAD2584078A30A81CA9B64823B.[Description]
   ,grp335A2DAAD2584078A30A81CA9B64823B.[CategoryRollUp]
   ,grp335A2DAAD2584078A30A81CA9B64823B.[FullDescription]
   ,grp335A2DAAD2584078A30A81CA9B64823B.[TransactionID]
   ,grp335A2DAAD2584078A30A81CA9B64823B.[MemberGUID]
   ,grp335A2DAAD2584078A30A81CA9B64823B.[HistoryItemGUID]
FROM [fp].[DimSubAccountCategory] grp335A2DAAD2584078A30A81CA9B64823B (readuncommitted)
GO


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

-- fp.viewEntityAccessByUser
CREATE VIEW [fp].[viewEntityAccessByUser]
AS
	SELECT
		a.EntityGroupConfigID,
		a.Section,
		ra.IdentityGUID as UserGUID,
		REPLACE(ra.LootGroupID, 'DEPT|', '') as DepartmentID,
		MAX(a.AccessType) as AccessType
	FROM 
		[fp].[APESectionRoleAccess] a
		LEFT JOIN [dbo].[viewS3RoleAssignment] ra ON ra.RoleID = a.RoleID
		INNER JOIN [fw].[DimDepartment] dept ON 'DEPT|' + CAST(dept.DepartmentID as nvarchar(10)) = ra.LootGroupID
		INNER JOIN fp.EntityGroupConfig egc ON a.EntityGroupConfigID = egc.EntityGroupConfigID
		INNER JOIN fp.EntityGroupConfigMapping egcm 
			ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
			AND dept.EntityID = egcm.EntityID
	WHERE 
		a.budgetphaseid = 2
		AND ra.lootgroupid like 'DEPT|%'
	GROUP BY
		a.EntityGroupConfigID,
		a.Section,
		ra.IdentityGUID,
		ra.LootGroupID
	HAVING 
		MAX(a.AccessType) > 0
GO


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

-- fp.viewExceptionDepartmentsWithoutBudget
CREATE VIEW fp.viewExceptionDepartmentsWithoutBudget
AS
/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
*******************************************************************************/
-- Has YTD data but no budgeted data
SELECT DISTINCT 
	dep.DepartmentID , 
	acc.AccountID ,
	'Department has ' + CAST(CAST(SUM(glh.ActualYTDValueTotal) AS DECIMAL(16,2)) AS NVARCHAR(100)) + ' current year for account ' + ACC.[Name] + ' but does not have a budget.' AS [Detail]  
FROM fp.GeneralLedger gl
	INNER JOIN fp.GeneralLedgerHistory glh ON glh.GeneralLedgerID = gl.GeneralLedgerID
	INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID
	INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID
	INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID
WHERE bc.IsActive =1 and ActualYTDValueTotal <> 0 and BudgetAdjustedTotal = 0
GROUP BY
dep.DepartmentID,
acc.AccountID,
Acc.Name
GO


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

-- fp.viewExceptionDeptMissingPrimaryStatsConfig
CREATE VIEW [fp].[viewExceptionDeptMissingPrimaryStatsConfig]
AS 
/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
** 3 	07-04-2024 		VZ 				   JAZZ-69920 	  Added EntityGroupConfig
*******************************************************************************/
-- Missing Primary Statistics Mappings


-- Set as driver but no values to drive
SELECT DISTINCT 
	dep.DepartmentID, 
	acc.AccountID,
	'Driver statistics exist but no data exists for the mapped department/account.' AS Detail,
	ec.EntityGroupConfigGuid,
	ec.Name
FROM fp.PrimaryStatisticsConfig ps
INNER JOIN fp.EntityGroupConfig EC ON EC.EntityGroupConfigGUID = ps.EntityGroupConfigGUID 
INNER JOIN fp.BudgetConfig BC ON BC.BudgetConfigGUID = EC.BudgetConfigGUID
INNER JOIN fw.DimDepartment Dep ON dep.DepartmentID = ps.DepartmentID 
INNER JOIN fw.DimAccount acc ON acc.accountID = ps.AccountID
WHERE bc.IsActive =1 
AND Cast(IsRevenue AS INT) + Cast(IsStaffing AS INT) + Cast(IsNonStaffing  AS INT)  <>0  -- has driver set
AND						-- Stat YTD data does not exist

	(
			SELECT SUM(SampledProjectionTotal) FROM fp.FactStatistics FS
			WHERE FS.DepartmentID = ps.DepartmentID 
			AND fs.AccountID = ps.AccountID
			AND BC.BudgetConfigID = FS.BudgetConfigID 											
	) <> 0

UNION ALL

-- Has Stat data but not in primary stats driver table

SELECT DISTINCT 
	dep.DepartmentID, 
	acc.AccountID,
	'Statisitics data is mapped to a department/account but you must configure a driver statistic.' AS Detail,
	ec.EntityGroupConfigGuid,
	ec.Name
FROM fp.FactStatistics fs
INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fs.DepartmentID 
INNER JOIN fw.DimAccount acc ON acc.accountID = fs.AccountID 
INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = fs.BudgetConfigID 
INNER JOIN fp.EntityGroupConfig EC ON EC.BudgetConfigGUID = bc.BudgetConfigGUID
WHERE SampledProjectionTotal <> 0 -- NOn -zero stats data
AND dep.OBIsDefined = 1 AND dep.IsVariable = 1
AND bc.IsActive = 1 -- Active Configuration
AND  EXISTS 
	(
		SELECT * FROM fp.PrimaryStatisticsConfig ps
		WHERE ps.DepartmentID = fs.DepartmentID 
		AND ps.AccountID = acc.accountID
		AND ps.EntityGroupConfigGUID = EC.EntityGroupConfigGUID 
		AND Cast(IsRevenue AS Int) + Cast(IsStaffing AS Int) + Cast(IsNonStaffing  AS Int)  = 0 
	)
GO


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

-- fp.viewExceptionDeptMissingProductivityStandard
CREATE VIEW [fp].[viewExceptionDeptMissingProductivityStandard]
AS
/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
** 3	07-05-2024		VZ				JAZZ-69920		Added EntityGroupConfigGuid
*******************************************************************************/
----Missing Productivity Standards ---
SELECT DISTINCT 
	bc.BudgetConfigID,
	EC.Name AS EntityGroupConfig,
	dep.departmentID,
	'Department has variable job codes but you must specify productivity standards for flexing.' AS Detail,
	EC.EntityGroupConfigGUID,
	EC.Name
FROM fp.StaffingExpenseFlexingConfig fc
	INNER JOIN fp.EntityGroupConfig EC ON EC.EntityGroupConfigGUID = fc.EntityGroupConfigGUID 
	INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = EC.BudgetConfigGUID
	INNER JOIN fw.DimDepartment dep ON dep.departmentID = fc.DepartmentID
	INNER JOIN fp.PayrollVariabilityConfig pc ON pc.EntityGroupConfigGUID = EC.EntityGroupConfigGUID
	INNER JOIN fp.Staffing fs ON fs.BudgetConfigID = bc.BudgetConfigID AND fs.departmentID = fc.departmentID AND fs.jobcodeID = pc.jobcodeid -- Data Check
WHERE bc.IsActive = 1 --- Active Configuration 
	AND EC.IsPatientActivityFlexingForStaffing = 0 -- Non PAF Clients
	AND fc.FlexMethodID = 1 --- Flex Method = Stat Accounts
	AND NOT EXISTS (SELECT 1 FROM fp.StaffingVariabilityOverrideConfig varovr WHERE varovr.entityGroupConfigGUID = fc.EntityGroupConfigGUID AND fc.departmentID = varovr.DepartmentID AND pc.Jobcodeid = varovr.JobCodeID  AND varovr.Variability = 0) -- JC variability Override check 
	AND NOT EXISTS (SELECT 1 FROM fp.StaffingFlexingOverrideConfig stovr WHERE stovr.EntityGroupConfigGUID = EC.EntityGroupConfigGUID AND stovr.DepartmentID = fc.DepartmentID  AND stovr.JobCodeID = pc.JobCodeID AND stovr.FlexMethodID = 6 )-- Flexing Override Check
	AND fc.IsUsingProductivityTarget = 1 -- Set to use target
	AND fc.ProductivityTarget = 0 
	AND pc.Variability != 0 -- Only Variable jobcodes"
GO


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

-- fp.viewExceptionInvalidDeductionsFlexingSetup
CREATE VIEW [fp].[viewExceptionInvalidDeductionsFlexingSetup]
AS

/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
** 3	07-05-2024		VZ				JAZZ-69920		Added EntityGroupConfig
*******************************************************************************/

-- UseCase#1 : No underlying charge data for depts set to flex on charges --
-- Dept setup for deductions flexing--
SELECT DISTINCT 
	dep.DepartmentID,
	'No revenue data exists for the selected fiscal year/time class from the deductions baseline in  [int].[FactGL].' AS Detail,
	egc.EntityGroupConfigGUID,
	egc.Name
FROM fp.deductionsflexingConfig fc
INNER JOIN fp.entitygroupConfig egc ON egc.entityGroupConfigGUID= fc.entityGroupConfiggUID
INNER JOIN fp.budgetconfig bc ON bc.budgetconfigGUID = egc.BudgetConfigGUID
INNER JOIN fw.dimdepartment dep ON dep.departmentID = fc.departmentID
WHERE bc.isactive =1 AND fc.flexmethodID =8 -- Total Gross Charges
-- There was no revenue data found for the selected fiscal year/time class from the deduction baseline in [int].[FactGL]
AND NOT EXISTS (SELECT * FROM [int].[FactGL] gl
				WHERE gl.FiscalYearID = egc.RevenueAndDeductionsFiscalYearID AND gl.TimeClassID = egc.RevenueAndDeductionsTimeClassID
				AND  gl.DepartmentID = dep.DepartmentID
				AND 
					gl.AccountID IN (
					SELECT accountID FROM fw.DimAccount acc WHERE 
				acc.OBModelSectionName LIKE '%Charge%'))

UNION ALL

-- UseCase #2: No historical deductions data to establish base rate for flexing
SELECT DISTINCT 
	dep.DepartmentID,
	'No general ledger data exists for the selected fiscal year/time class from the deductions baseline in  [int].[FactGL].' AS Detail,
	egc.EntityGroupConfigGUID,
	egc.Name
FROM fp.deductionsflexingConfig fc
INNER JOIN fp.entitygroupConfig egc ON egc.entityGroupConfigGUID= fc.entityGroupConfiggUID
INNER JOIN fp.budgetconfig bc ON bc.budgetconfigGUID = egc.BudgetConfigGUID
INNER JOIN fw.dimdepartment dep ON dep.departmentID = fc.departmentID
WHERE bc.isactive =1 AND fc.flexmethodID =8 -- Total Gross Charges

-- There was no revenue data found for the selected fiscal year/time class from the deduction baseline in [int].[FactGL]
AND NOT EXISTS (SELECT * FROM [int].[FactGL] gl
				WHERE gl.FiscalYearID = egc.RevenueAndDeductionsFiscalYearID AND gl.TimeClassID = egc.RevenueAndDeductionsTimeClassID
				AND  gl.DepartmentID = dep.DepartmentID
				AND 
					gl.AccountID IN (
					SELECT accountID FROM fw.DimAccount acc WHERE 
				acc.OBModelSectionName LIKE '%Deductions%'))
GO


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

-- fp.viewExceptionInvalidRevenueFlexingSetup
CREATE VIEW [fp].[viewExceptionInvalidRevenueFlexingSetup]
AS

/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
** 3	07-05-2024		VZ				JAZZ-69920		Added EntityGroupConfig
*******************************************************************************/

-- Revenue Flexing (Invalid Setup)
-- Dept flex driver set as Stats 
-- No overrides 
-- YTD revenue data 
-- revenue driver set for primary stats
-- NO Stats data available

--<<<<<<<<<<<<<<<< Flex Method = ID =3 --> Statistics Accounts By PatientClass --<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
SELECT DISTINCT
	dep.DepartmentID , 
	acc.AccountID , 
	flex.FlexMethodID , 
	'Statistics Accounts By Patient Class' AS FlexMethod,
	'Department is set up for flexing but has no statistics data for statistics accounts by patient class.' AS Detail, 
	ec.EntityGroupConfigGUID,
	ec.Name
FROM fp.GeneralLedger gl
	INNER JOIN fp.GeneralLedgerHistory hi ON hi.GeneralLedgerID = gl.generalledgerID
	INNER JOIN fw.dimdepartment dep ON dep.departmentID = gl.departmentID
	INNER JOIN fw.dimaccount acc ON acc.accountID = gl.accountID
	INNER join fp.BudgetConfig bc ON bc.budgetconfigID = gl.BudgetConfigID
	INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.BudgetConfigGUID
	INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID  = gl.APEModelSectionID AND map.OBModelSectionName = acc.OBModelSectionName
	INNER JOIN fp.RevenueExpenseFlexingConfig flex ON flex.departmentID = gl.departmentID AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
WHERE bc.IsActive =1  AND ec.IsPatientActivityFlexingForNonStaffing <> 1 -- NON ABB/PAF client
	AND map.APEModelSectionName ='Revenue' 
	AND hi.ActualYTDValueTotal <> 0 -- has YTD data 
	AND gl.VariabilityID <> 1 -- Revenues are always 100% variable unless for fixed dept or set overrides
	AND flex.flexMethodID = 3 -- Stats by patient Class	
	AND NOT EXISTS  -- No Overrides 
		(
			SELECT 1 
			FROM fp.RevenueFlexingOverrideConfig ovr
			WHERE ovr.DepartmentID = gl.DepartmentID 
				AND ovr.AccountID = gl.AccountID
				AND ovr.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
				AND ovr.FlexMethodID = 6 -- Override as "Fixed"
		) --- Missing Flexmapping probably due to mismatch patient class 
	AND NOT EXISTS
		(
			SELECT 1 
			FROM fp.FlexConfigMapping map
				INNER JOIN fp.FactStatistics fstat ON fstat.DepartmentID = map.DepartmentID AND fstat.AccountID = map.StatAccountID 
			WHERE map.GLAccountID = acc.AccountID
				AND map.EntityGroupConfigID = ec.entitygroupConfigID
		)

		--- Primary Stats drivers Exists ----
	AND EXISTS 
		(
			SELECT 1 
			FROM fp.PrimaryStatisticsConfig ps
			WHERE ps.DepartmentID = gl.DepartmentID 
				AND ps.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
				AND ps.IsRevenue =1
		
			-- No Data 
			AND NOT EXISTS 
				(
					SELECT * 
					FROM fp.FactStatistics fs
					WHERE fs.departmentID = ps.departmentID
						AND fs.accountID = ps.accountid 
						AND Fs.PatientClassID = acc.patientclassID
						AND fs.EntityGroupConfigID = ec.EntityGroupConfigID
						AND SampledProjectionTotal <> 0  -- Non Zero volume data for driver statistics	
				)
		)
		
UNION ALL

--<<<<<<<<<<<<<<<< Flex Method = ID =4 --> Total Statistics Accounts--<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
SELECT DISTINCT
	dep.DepartmentID , 
	acc.AccountID , 
	flex.FlexMethodID,
	'Total Statistics Accounts' AS FlexMethod,
	'Department is set up for flexing but has no statistics data for total statistics accounts.' AS Detail, 
	ec.EntityGroupConfigGUID,
	ec.Name
FROM fp.GeneralLedger gl
	INNER JOIN fp.GeneralLedgerHistory hi ON hi.GeneralLedgerID = gl.GeneralLedgerID
	INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID
	INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID
	INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID
	INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.BudgetConfigGUID
	INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID  = gl.APEModelSectionID
	INNER JOIN fp.RevenueExpenseFlexingConfig flex ON flex.departmentID = gl.departmentID AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
WHERE BC.IsActive =1  AND EC.IsPatientActivityFlexingForNonStaffing <> 1 -- NON ABB/PAF client
	AND map.APEModelSectionName ='Revenue' 
	AND hi.ActualYTDValueTotal <> 0 -- has YTD data 
	AND gl.VariabilityID <> 1 -- Revenues are always 100% variable unless for fixed dept or set overrides
	AND flex.flexMethodID = 4 -- Total Statistics Accounts
	AND NOT EXISTS  -- No Overrides 
		(
			SELECT 1 
			FROM fp.RevenueFlexingOverrideConfig ovr
			WHERE ovr.DepartmentID = gl.DepartmentID 
				AND ovr.AccountID = gl.AccountID
				AND ovr.FlexMethodID = 6 -- Override as "Fixed"
		) --- Primary Stats drivers Exists ----
	AND EXISTS 
		(
			SELECT 1 
			FROM fp.PrimaryStatisticsConfig ps
			WHERE ps.DepartmentID = gl.DepartmentID 
				AND ps.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
				AND ps.IsRevenue =1

			AND NOT EXISTS
				(
					SELECT * 
					FROM fp.FactStatistics fs
						INNER JOIN fw.DimAccount acc2 ON acc2.accountID = fs.AccountID
						INNER JOIN fp.entitygroupconfig ecc ON ecc.entitygroupconfigID = fs.entitygroupconfigID
					WHERE fs.departmentID = ps.departmentID
						AND fs.accountID = ps.accountid
						AND ps.EntityGroupConfigGUID = ecc.EntityGroupConfigGUID
						AND SampledProjectionTotal <>0  -- Non Zero volume data for driver statistics
				)
		)
GO


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

-- fp.viewExceptionVariableDeptNoFlexDrivers
CREATE VIEW [fp].[viewExceptionVariableDeptNoFlexDrivers]
AS
/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
** 3	07-05-2024		VZ				JAZZ-69920		Added EntityGroupConfig
*******************************************************************************/
SELECT DISTINCT 
	Dd.DepartmentID,
	'Department has variable expense accounts but you must configure statistics accounts to drive expense accounts.' AS Detail,
	egc.EntityGroupConfigGuid,
	egc.Name
FROM [fp].[GeneralLedger] SF1 WITH (readuncommitted)
	INNER JOIN [fw].[DimDepartment] DD WITH (readuncommitted) ON SF1.DepartmentID=DD.DepartmentID  --CID 2
	INNER JOIN [fw].[DimAccount] DA ON SF1.AccountID=DA.AccountID
	LEFT JOIN [fp].[ModelSectionMap] msm ON msm.OBModelSectionName = DA.OBModelSectionName
	INNER join [fp].[BudgetConfig] bc1 ON bc1.BudgetConfigID=SF1.BudgetConfigID
	INNER JOIN [fp].EntityGroupConfig egc ON SF1.EntityGroupConfigID = egc.EntityGroupConfigID
WHERE 
	1=1 
	AND bc1.IsActive='1'
	AND	MSM.ModelSectionMapID='6' --Expenses - Non-Staffing
	AND DD.IsVariable=1
	AND DA.Variability=1
	AND SF1.InitialProjectionTotal<>0
	AND NOT EXISTS 
		(
			SELECT TOP 1 1 FROM [fp].[PrimaryStatisticsConfig] psc
				INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID=psc.EntityGroupConfigGUID
				INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID=egc.BudgetConfigGUID
			WHERE bc.IsActive='1' AND psc.DepartmentID=dd.DepartmentID AND psc.IsNonStaffing='1'	
		)

UNION ALL

SELECT DISTINCT 
	dd.DepartmentID,
	'Department has variable job codes but you must configure statistics accounts to drive staffing.' AS Detail,
	egc.EntityGroupConfigGuid,
	egc.Name
FROM [fp].[Staffing] SF1 WITH (readuncommitted)
	INNER JOIN [fw].[DimDepartment] DD WITH (readuncommitted) ON SF1.DepartmentID=DD.DepartmentID  --CID 2
	INNER JOIN [fw].[DimJobCode] JJ WITH (readuncommitted) ON SF1.JobCodeID=jj.JobCodeID
	INNER join [fp].[BudgetConfig] bc1 ON bc1.BudgetConfigID=SF1.BudgetConfigID
	INNER JOIN [fp].EntityGroupConfig egc ON SF1.EntityGroupConfigID = egc.EntityGroupConfigID
WHERE 
	1=1
	AND bc1.IsActive='1'
	AND DD.IsVariable=1
	AND JJ.IsVariable=1
	AND NOT EXISTS 
		(
			SELECT TOP 1 1 FROM [fp].[PrimaryStatisticsConfig] psc
				INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID=psc.EntityGroupConfigGUID
				INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID=egc.BudgetConfigGUID
			WHERE bc.IsActive='1' AND psc.DepartmentID=dd.DepartmentID AND psc.IsStaffing='1'		
		)
GO


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

-- fp.viewExceptionsDepsWithRegularPCGNOHoursNODollars
CREATE VIEW fp.viewExceptionsDepsWithRegularPCGNOHoursNODollars
AS
/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
*******************************************************************************/
SELECT DISTINCT
	dep.DepartmentID,
	JC.JobCodeID,
	'Department has only non-regular hours/dollars for job code '+JC.name+' and cannot project non-regular dollars.' AS 'Detail'
FROM (
	SELECT 
        fs.DepartmentID,
        fs.JobCodeID,
        fs.PayCodeGroupID,
		fs.budgetconfigID,
		fs.variabilityID
	FROM fp.staffing fs
		INNER JOIN fw.DimPayCodeGroup PCG ON PCG.paycodegroupID = fs.paycodegroupID
		INNER JOIN fw.dimproductiveClass PC ON pCG.ProductiveClassID = PC.ProductiveClassID 
	WHERE PC.ProductiveClassID NOT  IN (3, 4) -- Productive , Dollars Only
		AND sampledProjectionDollarsTotal <> 0 AND SampledProjectionHoursTotal <> 0 -- Non Zero Non-Regular Dollars 
) Other
INNER JOIN (	  
	SELECT -- Zero YTD Dollars
        fs.departmentID,
        fs.JobCodeID,
        fs.PayCodeGroupID,
		fs.budgetConfigID,
		fs.variabilityID
	FROM fp.staffing fs
		INNER JOIN fw.DimPayCodeGroup PCG ON PCG.paycodegroupID = fs.paycodegroupID
		INNER JOIN fw.dimproductiveClass PC ON pCG.ProductiveClassID = PC.ProductiveClassID 
	WHERE PC.Name ='Productive' AND fs.paycodegroupID = 1048 -- Regular
		AND sampledProjectionDollarsTotal = 0 AND SampledProjectionHoursTotal = 0 -- Zero YTD Dollars 
) Regular ON Other.DepartmentID = Regular.DepartmentID
	AND other.JobCodeID = Regular.JobCodeID
	AND Other.BudgetConfigID = Regular.BUdgetConfigID
	AND other.VariabilityID = Regular.VariabilityID
	INNER JOIN fw.dimdepartment dep ON dep.departmentID = Regular.departmentID
	INNER JOIN fw.DimJobCode JC ON JC.jobcodeid = Regular.Jobcodeid
	INNER JOIN fp.budgetcOnfig bc ON bc.budgetConfigID = Regular.budgetconfigID
	INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.BudgetConfigGUID
WHERE bc.IsActive =1  -- Active Config
GO


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

-- fp.viewExceptionsDeptProjectionEqualsYTD
CREATE VIEW fp.viewExceptionsDeptProjectionEqualsYTD
AS 

/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
*******************************************************************************/

SELECT DISTINCT 
dep.DepartmentID , 
acc.AccountID ,
'Department has projection equal to YTD for account ' + acc.Name + '.'   AS Detail
FROM fp.generalledger gl
	INNER JOIN fp.generalledgerHistory glh ON glh.generalledgerID = gl.generalledgerID
	INNER JOIN fp.budgetconfig bc ON bc.budgetconfigid = gl.budgetconfigID
	INNER JOIN fw.DimDepartment dep ON dep.departmentID = gl.departmentID
	INNER JOIN fw.dimaccount acc ON acc.accountID = gl.accountID
WHERE bc.IsActive =1 AND ActualYTDValueTotal <>0 -- Final
AND glh.ActualYTDValueTotal = InitialProjectionTotal AND
 bc.MonthsLoaded <> 12
GO


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

-- fp.viewExceptionsJobCodePayCodeGroupMissingPayrollToAccountCrosswalkConfigurations
CREATE   VIEW [fp].[viewExceptionsJobCodePayCodeGroupMissingPayrollToAccountCrosswalkConfigurations] 
AS

/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
** 3	07-02-2024		VZ				JAZZ-73527		Update script to better performance
** 4	08-15-2024		MZ				JAZZ-75111		Cleaned up the View & removed DepartmentID
** 5	08-27-2024		MZ				JAZZ-76012		Fix checking cw.PayCodeGroupID instead of Staffing
*******************************************************************************/

SELECT DISTINCT
	s.JobCodeID,
    s.PayCodeGroupID,
    pcg.Name +' dollars budgeted to ' + jc.Name + ' but you must map the payroll combination to a GL account.' AS 'Detail'
FROM [fp].[Staffing] s
	INNER JOIN [fw].[DimPayCodeGroup] pcg WITH (readuncommitted)
	    ON s.PayCodeGroupID = pcg.PayCodeGroupID
	INNER JOIN [fw].[DimJobCode] jc WITH (readuncommitted)
	    ON s.JobCodeID = jc.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc 
		ON s.BudgetConfigID = bc.BudgetConfigID
WHERE
	s.BudgetAdjustedDollarsTotal <> 0
	AND bc.IsActive = 1
	AND s.SubsectionID = 3
	AND NOT EXISTS (
	    SELECT 1
	    FROM [clientob].[FactPayrollToAccountCrosswalk] cw WITH (readuncommitted)
	    WHERE               
	        (
	            (cw.JobCodeID = s.JobCodeID AND cw.PayCodeGroupID = s.PayCodeGroupID) --pay code group and job code specific
	            OR (cw.JobCodeID = s.JobCodeID AND cw.PayCodeGroupID = 0)              --job code specific
	            OR (cw.JobCodeID = 0 AND cw.PayCodeGroupID = s.PayCodeGroupID)        --pay code group specific
	        )
	    AND cw.UnitTypeID = 34 --dollars
	    AND cw.IsDeleted = 0
	)
GO


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

-- fp.viewExceptionsJobCodesWithHoursButNODollars
CREATE View [fp].[viewExceptionsJobCodesWithHoursButNODollars]
AS
/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
*******************************************************************************/
	 SELECT DISTINCT
	 
		dep.DepartmentID,
		Jc.JobCodeID,
		'Department has hours in pay code group '
			+ pcg.name
			+ ' but no dollars for job code '
			+ jc.name
			+ '.'
			
			AS Detail
		
		FROM  fp.staffing fs
	INNER JOIN fw.dimdepartment dep ON dep.departmentid = fs.departmentid 
	INNER JOIN fw.dimjobcode jc ON jc.jobcodeid = fs.jobcodeid 
	INNER JOIN fw.DimPayCodeGroup pcg ON pcg.paycodegroupID = fs.paycodegroupID
	INNER JOIN fp.budgetconfig  bc ON bc.budgetconfigid = fs.budgetconfigid
	INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.budgetConfigGUID
WHERE bc.IsActive =1
AND fs.ProductiveClassID NOT IN (4,5,6) --Productive Non-FTE', 'Differential', 'Dollars-Only' EXCLUDED from FTE Calcs
AND jc.jobcodeid <>0 
	AND fs.InitialProjectionDollarsTotal <>0 

	AND NOT EXISTS
		(
	SELECT 1 
		FROM fp.Staffing fs2 
		WHERE 
		fs2.BudgetConfigID = fs.BudgetConfigID	
		AND fs2.departmentid = fs.departmentid
		AND fs2.jobcodeid = fs.jobcodeid
		AND fs2.paycodegroupid = fs.paycodegroupid
		AND fs2.InitialProjectionDollarsTotal <>0 
	)
GO


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

-- fp.viewExceptionsJobCodewithDollarsButNOHours
CREATE View [fp].[viewExceptionsJobCodewithDollarsButNOHours]
AS

/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
*******************************************************************************/

-- ************ JObCode with Dollars but NO Hours 
--- ** Description: Checks for job code/pay code group combos that have dollars but not hours in historic time periods

SELECT DISTINCT
	DB.DepartmentID AS DepartmentID,
	Jc.jobCodeID,
	'Department has dollars in pay code group ' + PCG.[Name] + ' but no hours for job code ' + JC.[Name] + '.' AS [Detail]
 FROM fp.staffing AS ST WITH (READUNCOMMITTED) 
	INNER JOIN fw.dimdepartment AS DB WITH (READUNCOMMITTED)
	    ON DB.departmentID = ST.departmentID
	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 fp.Budgetconfig bc ON bc.BudgetConfigID = ST.budgetconfigID
	INNER JOIN fp.entityGroupConfig EC ON EC.budgetConfigGUID = bc.BudgetConfigGUID
WHERE 1=1
AND bc.IsActive =1 -- Active COnfig
AND PCG.[ProductiveClassID] NOT IN (4,6)  --Productive Non-FTE', 'Dollars-Only' EXCLUDED from FTE Calcs
AND ST.InitialProjectionDollarsTotal != 0
AND NOT EXISTS(
	SELECT 1
	FROM fp.Staffing AS H WITH (READUNCOMMITTED) 
	WHERE 1=1
		AND H.DepartmentID = ST.DepartmentID
		AND H.[JobCodeID] = ST.[JobCodeID]
		AND H.[PayCodeGroupID] = ST.[PayCodeGroupID]
		AND H.BudgetConfigID = ST.BudgetConfigID 
		AND H.InitialProjectionHoursTotal <>0
)
GO


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

-- fp.viewExceptionsNonStaffingExpenseInValidFlexingSetup
CREATE VIEW [fp].[viewExceptionsNonStaffingExpenseInValidFlexingSetup]
AS 

/*******************************************************************************
** Change History
********************************************************************************
** CID  Date			Author			WI              Description
** 1	04-24-2024		VZ              JAZZ-69354      Initial Creation
** 2	05-17-2024		NH              JAZZ-71771      Update report messages
** 3	07-05-2024		VZ				JAZZ-69920		Added EntityGroupConfig
*******************************************************************************/

-- Expense Flexing (Invalid Setup)
-- Dept flex driver set as Stats 
-- No overrides 
-- YTD Expense data 
-- Expense driver set for primary stats
-- NO Stats data available

--<<<<<<<<<<<<<<<< Flex Method = ID =1 --> Statistics Accounts  --<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

SELECT DISTINCT
	dep.DepartmentID ,
	acc.AccountID ,
	flex.FlexMethodID,
	'Statistics Accounts' AS FlexMethod,
	'Department is set up for flexing but has no statistics data for statistics accounts.' AS Detail,
	EC.EntityGroupConfigGUID,
	EC.Name
FROM [fp].[GeneralLedger] GL
	INNER JOIN [fp].[GeneralLedgerHistory] hi ON hi.GeneralLedgerID = GL.GeneralLedgerID
	INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = GL.DepartmentID
	INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = GL.AccountID
	INNER join [fp].[BudgetConfig] BC ON BC.BudgetConfigID = GL.BudgetConfigID
	INNER JOIN [fp].[EntityGroupConfig] EC ON EC.budgetConfigGUID = BC.BudgetConfigGUID
	INNER JOIN [fp].[ModelSectionMap] map ON map.APEModelSectionID  = GL.APEModelSectionID
	INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] flex ON flex.departmentID = GL.departmentID AND flex.EntityGroupConfigGUID = EC.EntityGroupConfigGUID
WHERE BC.IsActive =1  AND EC.IsPatientActivityFlexingForNonStaffing <> 1 -- NON ABB/PAF client
	AND map.APEModelSectionName ='Non-Staffing' 
	AND hi.ActualYTDValueTotal <> 0 -- has YTD data 
	AND GL.VariabilityID <>  1 -- 
	AND flex.flexMethodID = 1 -- Statistic Accounts
	AND NOT Exists  -- No Overrides 
		(
			SELECT 1 
			FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] ovr
			WHERE ovr.DepartmentID = GL.DepartmentID 
				AND ovr.AccountID = GL.AccountID
				AND ovr.FlexMethodID = 6 -- Override as "Fixed"
		)
		--- Primary Stats drivers Exists ----
	AND EXISTS 
		(
			SELECT 1 FROM [fp].[PrimaryStatisticsConfig] ps
			WHERE ps.DepartmentID = gl.DepartmentID 
				AND ps.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
				AND ps.IsNonStaffing =1
				AND NOT EXISTS
					(
						SELECT * 
						FROM [fp].[FactStatistics] fs
							INNER JOIN fw.DimAccount acc2 ON acc2.AccountID = fs.AccountID
							INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigID = fs.EntityGroupConfigID
						WHERE fs.DepartmentID = ps.departmentID
						--and fs.accountID = ps.accountid
						AND ps.EntityGroupConfigGUID = ecc.EntityGroupConfigGUID
						AND SampledProjectionTotal <>0  -- Non Zero volume data for driver statistics
					)
		)
GO


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

-- fp.viewExcludedProductiveClassesForFTE
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI            Description
** 1    2023-08-22  BK  	 JAZZ-59251	  Use ProductiveClassID = 4 instead of Dollars-Only to accommodate internationalization
**************************************************************
*/
CREATE VIEW fp.viewExcludedProductiveClassesForFTE
AS

SELECT PayCodeGroupID FROM [fw].[DimPayCodeGroup] pcg INNER JOIN [fw].[DimProductiveClass] pc on pcg.ProductiveClassID = pc.ProductiveClassID 
WHERE pc.ProductiveClassID IN (4,5,6)
GO


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

-- fp.viewExecutiveSummary
CREATE VIEW [fp].[viewExecutiveSummary]
AS

select  
	[bc].[BudgetConfigID],
	[ex].[DepartmentID], 
	Case
		When [ex].[SummaryType] = '0' Then 'Statistics'
		When [ex].[SummaryType] = '1' Then 'Revenue and Reductions'
		When [ex].[SummaryType] = '2' Then 'Other Revenue'
		When [ex].[SummaryType] = '3' Then 'Roster'
		When [ex].[SummaryType] = '4' Then 'Staffing'
		When [ex].[SummaryType] = '5' Then 'Benefits'
		When [ex].[SummaryType] = '6' Then 'Non-Staffing Expense'
		When [ex].[SummaryType] = '7' Then 'Staffing'
		When [ex].[SummaryType] = '8' Then 'Provider Compensation'
		Else 'Not implemented' End as SummaryTypeName,
	[ex].[DateModified], 
	[ex].[LastAuthorGUID] as UserGUID, 
	[ex].[LastAuthorName], 
	[ex].[Comments]
from [fp].[ExecutiveSummary] ex
	inner join [fp].[BudgetConfig] bc on bc.BudgetConfigGUID=ex.BudgetConfigGUID
GO


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

-- fp.viewFactBenefits
CREATE VIEW fp.viewFactBenefits
AS
SELECT 
	b.BenefitsID,
	b.BudgetConfigID,
	b.EntityGroupConfigID,
	b.DepartmentID,
	b.FinancialReportingID,
	b.EntityID,
	b.AccountID,
	b.UnitTypeID,
	b.FlexMethodID,
	bdgt.LockType as BudgetLockType,
	bdgt.LockFlag as BudgetLockFlag,
	bdgt.BudgetPhaseID as BudgetPhaseID,
	proj.LockType as ProjectionLockType,
	proj.LockFlag as ProjectionLockFlag,
	b.InitialBudget01, b.InitialBudget02, b.InitialBudget03, b.InitialBudget04, b.InitialBudget05, b.InitialBudget06, b.InitialBudget07, b.InitialBudget08, b.InitialBudget09, b.InitialBudget10, b.InitialBudget11, b.InitialBudget12, b.InitialBudgetTotal,
	b.InitialProjection01, b.InitialProjection02, b.InitialProjection03, b.InitialProjection04, b.InitialProjection05, b.InitialProjection06, b.InitialProjection07, b.InitialProjection08, b.InitialProjection09, b.InitialProjection10, b.InitialProjection11, b.InitialProjection12, b.InitialProjectionTotal,
	bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12, bdgt.AdjustedValueTotal,
	bdgt.FlexedValue01, bdgt.FlexedValue02, bdgt.FlexedValue03, bdgt.FlexedValue04, bdgt.FlexedValue05, bdgt.FlexedValue06, bdgt.FlexedValue07, bdgt.FlexedValue08, bdgt.FlexedValue09, bdgt.FlexedValue10, bdgt.FlexedValue11, bdgt.FlexedValue12, bdgt.FlexedValueTotal,
	proj.AdjustedValue01 AS AdjustedProjectionValue01, proj.AdjustedValue02 AS AdjustedProjectionValue02, proj.AdjustedValue03 AS AdjustedProjectionValue03, proj.AdjustedValue04 AS AdjustedProjectionValue04, proj.AdjustedValue05 AS AdjustedProjectionValue05, proj.AdjustedValue06 AS AdjustedProjectionValue06, proj.AdjustedValue07 AS AdjustedProjectionValue07, proj.AdjustedValue08 AS AdjustedProjectionValue08, proj.AdjustedValue09 AS AdjustedProjectionValue09, proj.AdjustedValue10 AS AdjustedProjectionValue10, proj.AdjustedValue11 AS AdjustedProjectionValue11, proj.AdjustedValue12 AS AdjustedProjectionValue12, proj.AdjustedValueTotal AS AdjustedProjectionValueTotal,
	proj.FlexedValue01 AS FlexedProjectionValue01, proj.FlexedValue02 AS FlexedProjectionValue02, proj.FlexedValue03 AS FlexedProjectionValue03, proj.FlexedValue04 AS FlexedProjectionValue04, proj.FlexedValue05 AS FlexedProjectionValue05, proj.FlexedValue06 AS FlexedProjectionValue06, proj.FlexedValue07 AS FlexedProjectionValue07, proj.FlexedValue08 AS FlexedProjectionValue08, proj.FlexedValue09 AS FlexedProjectionValue09, proj.FlexedValue10 AS FlexedProjectionValue10, proj.FlexedValue11 AS FlexedProjectionValue11, proj.FlexedValue12 AS FlexedProjectionValue12, proj.FlexedValueTotal AS FlexedProjectionValueTotal
FROM fp.FactBenefits b
	INNER JOIN fp.FactBenefitsBudget bdgt ON b.BenefitsID = bdgt.BenefitsID
	INNER JOIN fp.FactBenefitsProjection proj ON b.BenefitsID = proj.BenefitsID AND proj.BudgetPhaseID = bdgt.BudgetPhaseID
GO


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

-- fp.viewFactBenefitsForHistoryViewer
CREATE VIEW [fp].[viewFactBenefitsForHistoryViewer]
AS
SELECT
	ov.BenefitsID,
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.UnitTypeID, 
	ov.FiscalMonthID,
	ov.OriginalValue,
	ov.FlexMethodID,
	v.Value,
	fv.FlexedValue,
	ISNULL(ch.HistoryCount, 0) as HistoryCount
FROM (
	-- Unpivot for Value
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
INNER JOIN
	-- Unpivot for OriginalValue
	(SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.OriginalValue, FlexMethodID
	FROM (
		SELECT gl.*
		FROM fp.FactBenefits gl ) gl
		UNPIVOT ( OriginalValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN
	-- Unpivot for OriginalValue
	(SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.FlexedValue
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.FlexedValue01, bdgt.FlexedValue02, bdgt.FlexedValue03, bdgt.FlexedValue04, bdgt.FlexedValue05, bdgt.FlexedValue06, bdgt.FlexedValue07, bdgt.FlexedValue08, bdgt.FlexedValue09, bdgt.FlexedValue10, bdgt.FlexedValue11, bdgt.FlexedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( FlexedValue FOR FiscalMonth IN (FlexedValue01, FlexedValue02, FlexedValue03, FlexedValue04, FlexedValue05, FlexedValue06, FlexedValue07, FlexedValue08, FlexedValue09, FlexedValue10, FlexedValue11, FlexedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'FlexedValue', 'Month')) fv
	ON fv.DepartmentID = v.DepartmentID
	AND fv.AccountID = v.AccountID
	AND fv.BudgetConfigID = v.BudgetConfigID
	AND fv.UnitTypeID = v.UnitTypeID
	AND fv.FiscalMonthID = v.FiscalMonthID	
LEFT JOIN
	(SELECT BenefitsID, FiscalMonthID, count(*) as HistoryCount FROM [fp].[BenefitsChangeHistory] WHERE BudgetPhaseID = 2 AND TimeClassID = 2 GROUP BY BenefitsID, FiscalMonthID) ch
	ON ch.BenefitsID = v.BenefitsID
	AND ch.FiscalMonthID = v.FiscalMonthID
GO


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

-- fp.viewFactBenefitsHistory_Unpivoted
CREATE VIEW fp.viewFactBenefitsHistory_Unpivoted
AS
-- Unpivot for PriorYearActual
SELECT data.BenefitsID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT gl.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12
        FROM fp.FactBenefits gl (READUNCOMMITTED)
        INNER JOIN fp.FactBenefitsHistory hist (READUNCOMMITTED)
        ON gl.BenefitsID = hist.BenefitsID ) gl
        UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f
        INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for ActualYTD
SELECT data.BenefitsID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT gl.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12
        FROM fp.FactBenefits gl (READUNCOMMITTED)
        INNER JOIN fp.FactBenefitsHistory hist (READUNCOMMITTED)
        ON gl.BenefitsID = hist.BenefitsID ) gl
        UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f
        INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for CurrentYearBudget
SELECT data.BenefitsID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT gl.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12
        FROM fp.FactBenefits gl (READUNCOMMITTED)
        INNER JOIN fp.FactBenefitsHistory hist (READUNCOMMITTED)
        ON gl.BenefitsID = hist.BenefitsID ) gl
        UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f
        INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudget', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactBenefits_HistoryViewer
CREATE VIEW fp.viewFactBenefits_HistoryViewer
AS
SELECT
	ov.BenefitsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.FactBenefits gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactBenefits_Pivoted
CREATE VIEW [fp].[viewFactBenefits_Pivoted]
AS
SELECT
	fb.BenefitsID,
	fb.BudgetConfigID, 
	fb.EntityGroupConfigID,
	fb.EntityID,
	fb.DepartmentID,
	fb.AccountID,
	fb.FinancialReportingID,
	fb.UnitTypeID,
	
	CASE WHEN fb.FlexMethodID = 1 THEN 1 ELSE 0 END AS FlexByFTEs,
	CASE WHEN fb.FlexMethodID = 2 THEN 1 ELSE 0 END AS FlexBySalaries,
	
	fbdgt.LockType as BudgetLockType,
	fbdgt.LockFlag as BudgetLockFlag,
	fproj.LockType as ProjectionLockType,
	fproj.LockFlag as ProjectionLockFlag,
	
	dbdgt.LockType as FinalBudgetLockType,
	dbdgt.LockFlag as FinalBudgetLockFlag,
	dproj.LockType as FinalProjectionLockType,
	dproj.LockFlag as FinalProjectionLockFlag,
	
	fbdgt.AdjustedValueTotal,
	
	dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal,
	dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal,
	
	dproj.AdjustedValueTotal as AdjustedProjectionValueTotal,
	
	hist.ActualYTDValueTotal,
	hist.CurrentYearBudgetTotal,
	hist.PriorYearActualValueTotal,
	
	fb.InitialBudgetTotal,
	fb.InitialProjectionTotal,
	
	fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12,
	dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12,
	dproj.AdjustedValue01 AS AdjustedProjectionValue01, dproj.AdjustedValue02 AS AdjustedProjectionValue02, dproj.AdjustedValue03 AS AdjustedProjectionValue03, dproj.AdjustedValue04 AS AdjustedProjectionValue04, dproj.AdjustedValue05 AS AdjustedProjectionValue05, dproj.AdjustedValue06 AS AdjustedProjectionValue06, dproj.AdjustedValue07 AS AdjustedProjectionValue07, dproj.AdjustedValue08 AS AdjustedProjectionValue08, dproj.AdjustedValue09 AS AdjustedProjectionValue09, dproj.AdjustedValue10 AS AdjustedProjectionValue10, dproj.AdjustedValue11 AS AdjustedProjectionValue11, dproj.AdjustedValue12 AS AdjustedProjectionValue12,
	fb.InitialBudget01, fb.InitialBudget02, fb.InitialBudget03, fb.InitialBudget04, fb.InitialBudget05, fb.InitialBudget06, fb.InitialBudget07, fb.InitialBudget08, fb.InitialBudget09, fb.InitialBudget10, fb.InitialBudget11, fb.InitialBudget12,
	hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12,
	hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12,
	hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12
FROM [fp].[FactBenefits] fb (READUNCOMMITTED)
	INNER JOIN [fp].[FactBenefitsBudget] (READUNCOMMITTED) fbdgt ON fb.BenefitsID = fbdgt.BenefitsID AND fbdgt.BudgetPhaseID = 2
	INNER JOIN [fp].[FactBenefitsBudget] (READUNCOMMITTED) dbdgt ON fb.BenefitsID = dbdgt.BenefitsID AND dbdgt.BudgetPhaseID = 3
	INNER JOIN [fp].[FactBenefitsProjection] (READUNCOMMITTED) fproj ON fb.BenefitsID = fproj.BenefitsID AND fproj.BudgetPhaseID = 2
	INNER JOIN [fp].[FactBenefitsProjection] (READUNCOMMITTED) dproj ON fb.BenefitsID = dproj.BenefitsID AND dproj.BudgetPhaseID = 3
	INNER JOIN [fp].[FactBenefitsHistory] hist (READUNCOMMITTED) ON fb.BenefitsID = hist.BenefitsID
GO


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

-- fp.viewFactBenefits_Unpivoted
CREATE VIEW fp.viewFactBenefits_Unpivoted
AS
SELECT
	ov.BenefitsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue as OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.FactBenefits gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID


UNION ALL

SELECT 
	ov.BenefitsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.UnitTypeID, 
	12 as TimeClassID, 
	bc.FiscalYearID - 1 as FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue as OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.FactBenefits gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsProjection bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactBenefits gl 
		INNER JOIN fp.FactBenefitsProjection bdgt ON gl.BenefitsID = bdgt.BenefitsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactChargeDollarsToStatisticsCrosswalkHistory_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI				Description
** 1    2021-11-17  MD          JAZZ-27519      Initial
** 2	2022-09-01	JB			JAZZ-32095		Remove Payor and PayorGroupID from joins.
** 3	2023-03-21	MY			JAZZ-49993		Update reporting to support new data model
*************************************************************/
CREATE   VIEW [fp].[viewFactChargeDollarsToStatisticsCrosswalkHistory_Unpivoted_source]  
 AS
	 -- The report source does not use data at the lowest level, so we're going to roll them up here so there is less data to pivot later. Pivoting is slow
	WITH chargevolume AS (
		SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, 34 as UnitTypeID, 
				SUM(hist.PriorYearActualDollarValue01) AS PriorYearActualValue01, 
				SUM(hist.PriorYearActualDollarValue02) AS PriorYearActualValue02, 
				SUM(hist.PriorYearActualDollarValue03) AS PriorYearActualValue03, 
				SUM(hist.PriorYearActualDollarValue04) AS PriorYearActualValue04, 
				SUM(hist.PriorYearActualDollarValue05) AS PriorYearActualValue05, 
				SUM(hist.PriorYearActualDollarValue06) AS PriorYearActualValue06, 
				SUM(hist.PriorYearActualDollarValue07) AS PriorYearActualValue07, 
				SUM(hist.PriorYearActualDollarValue08) AS PriorYearActualValue08,
				SUM(hist.PriorYearActualDollarValue09) AS PriorYearActualValue09, 
				SUM(hist.PriorYearActualDollarValue10) AS PriorYearActualValue10, 
				SUM(hist.PriorYearActualDollarValue11) AS PriorYearActualValue11, 
				SUM(hist.PriorYearActualDollarValue12) AS PriorYearActualValue12, 
				SUM(hist.ActualYTDDollarValue01) AS ActualYTDValue01, 
				SUM(hist.ActualYTDDollarValue02) AS ActualYTDValue02, 
				SUM(hist.ActualYTDDollarValue03) AS ActualYTDValue03, 
				SUM(hist.ActualYTDDollarValue04) AS ActualYTDValue04, 
				SUM(hist.ActualYTDDollarValue05) AS ActualYTDValue05, 
				SUM(hist.ActualYTDDollarValue06) AS ActualYTDValue06, 
				SUM(hist.ActualYTDDollarValue07) AS ActualYTDValue07, 
				SUM(hist.ActualYTDDollarValue08) AS ActualYTDValue08,
				SUM(hist.ActualYTDDollarValue09) AS ActualYTDValue09, 
				SUM(hist.ActualYTDDollarValue10) AS ActualYTDValue10, 
				SUM(hist.ActualYTDDollarValue11) AS ActualYTDValue11, 
				SUM(hist.ActualYTDDollarValue12) AS ActualYTDValue12,
				SUM(hist.CurrentYearBudgetDollar01) AS CurrentYearBudgetValue01, 
				SUM(hist.CurrentYearBudgetDollar02) AS CurrentYearBudgetValue02, 
				SUM(hist.CurrentYearBudgetDollar03) AS CurrentYearBudgetValue03, 
				SUM(hist.CurrentYearBudgetDollar04) AS CurrentYearBudgetValue04, 
				SUM(hist.CurrentYearBudgetDollar05) AS CurrentYearBudgetValue05, 
				SUM(hist.CurrentYearBudgetDollar06) AS CurrentYearBudgetValue06, 
				SUM(hist.CurrentYearBudgetDollar07) AS CurrentYearBudgetValue07, 
				SUM(hist.CurrentYearBudgetDollar08) AS CurrentYearBudgetValue08,
				SUM(hist.CurrentYearBudgetDollar09) AS CurrentYearBudgetValue09, 
				SUM(hist.CurrentYearBudgetDollar10) AS CurrentYearBudgetValue10, 
				SUM(hist.CurrentYearBudgetDollar11) AS CurrentYearBudgetValue11, 
				SUM(hist.CurrentYearBudgetDollar12) AS CurrentYearBudgetValue12
		FROM fp.ChargeVolume cv 
			INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID
			INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
			INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID
			INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID
				AND cc.DepartmentID = cv.DepartmentID
				AND cc.PatientClassID = cv.PatientClassID
				AND cc.ChargeCodeID = cv.ChargeCodeID
				AND cc.EntityGroupConfigID = cv.EntityGroupConfigID
		WHERE bc.IsActive = 1
		GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID
	)
	SELECT
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		DepartmentID, 
		ChargeCodeID, 
		ServiceLineID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		PatientClassID, 
		UnitTypeID, 
		TimeClassID, 
		FiscalYearID, 
		FiscalMonthID,
		Value
	FROM (
		SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
		FROM (
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID,
					fcv.PriorYearActualValue01, fcv.PriorYearActualValue02, fcv.PriorYearActualValue03, fcv.PriorYearActualValue04, fcv.PriorYearActualValue05, fcv.PriorYearActualValue06, fcv.PriorYearActualValue07, fcv.PriorYearActualValue08, fcv.PriorYearActualValue09, fcv.PriorYearActualValue10, fcv.PriorYearActualValue11, fcv.PriorYearActualValue12
				FROM chargevolume fcv ) fcv
				UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
			INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

		UNION ALL

		-- Unpivot for ActualYTD
		SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
		FROM (
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID,  PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, 
					fcv.ActualYTDValue01, fcv.ActualYTDValue02, fcv.ActualYTDValue03, fcv.ActualYTDValue04, fcv.ActualYTDValue05, fcv.ActualYTDValue06, fcv.ActualYTDValue07, fcv.ActualYTDValue08, fcv.ActualYTDValue09, fcv.ActualYTDValue10, fcv.ActualYTDValue11, fcv.ActualYTDValue12
				FROM chargevolume fcv ) fcv
				UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
			INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

		UNION ALL

		-- Unpivot for CurrentYearBudgetValue
		SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
		FROM (
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID,
					fcv.CurrentYearBudgetValue01, fcv.CurrentYearBudgetValue02, fcv.CurrentYearBudgetValue03, fcv.CurrentYearBudgetValue04, fcv.CurrentYearBudgetValue05, fcv.CurrentYearBudgetValue06, fcv.CurrentYearBudgetValue07, fcv.CurrentYearBudgetValue08, fcv.CurrentYearBudgetValue09, fcv.CurrentYearBudgetValue10, fcv.CurrentYearBudgetValue11, fcv.CurrentYearBudgetValue12
				FROM chargevolume fcv ) fcv
				UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudgetValue01, CurrentYearBudgetValue02, CurrentYearBudgetValue03, CurrentYearBudgetValue04, CurrentYearBudgetValue05, CurrentYearBudgetValue06, CurrentYearBudgetValue07, CurrentYearBudgetValue08, CurrentYearBudgetValue09, CurrentYearBudgetValue10, CurrentYearBudgetValue11, CurrentYearBudgetValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data
			INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

		) data
GO


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

-- fp.viewFactChargeDollarsToStatisticsCrosswalk_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2020-05-08  LR          JAZZ-20     Initial
** 2	2020-13-08	MY			JAZZ-4098	Performance tuning
** 3	2022-09-01	JB			JAZZ-32095	Remove Payor and PayorGroupID from joins.
** 4	2023-03-21	MY			JAZZ-49993	Update reporting to support new data model
*************************************************************/
CREATE   VIEW [fp].[viewFactChargeDollarsToStatisticsCrosswalk_Unpivoted_source]  
AS
	WITH chargevolume AS (
		SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, 34 as UnitTypeID, 
				SUM(cv.InitialBudgetDollars01) AS InitialBudget01, 
				SUM(cv.InitialBudgetDollars02) AS InitialBudget02, 
				SUM(cv.InitialBudgetDollars03) AS InitialBudget03, 
				SUM(cv.InitialBudgetDollars04) AS InitialBudget04, 
				SUM(cv.InitialBudgetDollars05) AS InitialBudget05, 
				SUM(cv.InitialBudgetDollars06) AS InitialBudget06, 
				SUM(cv.InitialBudgetDollars07) AS InitialBudget07, 
				SUM(cv.InitialBudgetDollars08) AS InitialBudget08,
				SUM(cv.InitialBudgetDollars09) AS InitialBudget09, 
				SUM(cv.InitialBudgetDollars10) AS InitialBudget10, 
				SUM(cv.InitialBudgetDollars11) AS InitialBudget11, 
				SUM(cv.InitialBudgetDollars12) AS InitialBudget12, 
				SUM(cv.InitialProjectionDollars01) AS InitialProjection01, 
				SUM(cv.InitialProjectionDollars02) AS InitialProjection02, 
				SUM(cv.InitialProjectionDollars03) AS InitialProjection03, 
				SUM(cv.InitialProjectionDollars04) AS InitialProjection04, 
				SUM(cv.InitialProjectionDollars05) AS InitialProjection05, 
				SUM(cv.InitialProjectionDollars06) AS InitialProjection06, 
				SUM(cv.InitialProjectionDollars07) AS InitialProjection07, 
				SUM(cv.InitialProjectionDollars08) AS InitialProjection08,
				SUM(cv.InitialProjectionDollars09) AS InitialProjection09, 
				SUM(cv.InitialProjectionDollars10) AS InitialProjection10, 
				SUM(cv.InitialProjectionDollars11) AS InitialProjection11, 
				SUM(cv.InitialProjectionDollars12) AS InitialProjection12,
				SUM(cv.TargetDollarsAdjusted01) AS TargetValue01, 
				SUM(cv.TargetDollarsAdjusted02) AS TargetValue02, 
				SUM(cv.TargetDollarsAdjusted03) AS TargetValue03, 
				SUM(cv.TargetDollarsAdjusted04) AS TargetValue04, 
				SUM(cv.TargetDollarsAdjusted05) AS TargetValue05, 
				SUM(cv.TargetDollarsAdjusted06) AS TargetValue06, 
				SUM(cv.TargetDollarsAdjusted07) AS TargetValue07, 
				SUM(cv.TargetDollarsAdjusted08) AS TargetValue08,
				SUM(cv.TargetDollarsAdjusted09) AS TargetValue09, 
				SUM(cv.TargetDollarsAdjusted10) AS TargetValue10, 
				SUM(cv.TargetDollarsAdjusted11) AS TargetValue11, 
				SUM(cv.TargetDollarsAdjusted12) AS TargetValue12,
				SUM(cv.BudgetDollarsAdjusted01) AS ManagerValue01, 
				SUM(cv.BudgetDollarsAdjusted02) AS ManagerValue02, 
				SUM(cv.BudgetDollarsAdjusted03) AS ManagerValue03, 
				SUM(cv.BudgetDollarsAdjusted04) AS ManagerValue04, 
				SUM(cv.BudgetDollarsAdjusted05) AS ManagerValue05, 
				SUM(cv.BudgetDollarsAdjusted06) AS ManagerValue06, 
				SUM(cv.BudgetDollarsAdjusted07) AS ManagerValue07, 
				SUM(cv.BudgetDollarsAdjusted08) AS ManagerValue08,
				SUM(cv.BudgetDollarsAdjusted09) AS ManagerValue09, 
				SUM(cv.BudgetDollarsAdjusted10) AS ManagerValue10, 
				SUM(cv.BudgetDollarsAdjusted11) AS ManagerValue11, 
				SUM(cv.BudgetDollarsAdjusted12) AS ManagerValue12,
				SUM(cv.ProjectionDollarsAdjusted01) AS ProjectedValue01, 
				SUM(cv.ProjectionDollarsAdjusted02) AS ProjectedValue02, 
				SUM(cv.ProjectionDollarsAdjusted03) AS ProjectedValue03, 
				SUM(cv.ProjectionDollarsAdjusted04) AS ProjectedValue04, 
				SUM(cv.ProjectionDollarsAdjusted05) AS ProjectedValue05, 
				SUM(cv.ProjectionDollarsAdjusted06) AS ProjectedValue06, 
				SUM(cv.ProjectionDollarsAdjusted07) AS ProjectedValue07, 
				SUM(cv.ProjectionDollarsAdjusted08) AS ProjectedValue08,
				SUM(cv.ProjectionDollarsAdjusted09) AS ProjectedValue09, 
				SUM(cv.ProjectionDollarsAdjusted10) AS ProjectedValue10, 
				SUM(cv.ProjectionDollarsAdjusted11) AS ProjectedValue11, 
				SUM(cv.ProjectionDollarsAdjusted12) AS ProjectedValue12
		FROM fp.ChargeVolume cv 
			INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID
			INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID
			INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID
				AND cc.DepartmentID = cv.DepartmentID
				AND cc.PatientClassID = cv.PatientClassID
				AND cc.ChargeCodeID = cv.ChargeCodeID
		WHERE bc.IsActive = 1
		AND cv.UnitTypeID = 145
		GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID
	)
	SELECT 
		BudgetConfigID,
		EntityGroupConfigID,
		EntityID,
		DepartmentID,
		ChargeCodeID,
		ServiceLineID,
		AgeCohortID,
		MedicalSurgicalID,
		PatientClassID,
		UnitTypeID,
		TimeClassID,
		FiscalMonthID,
		FiscalYearID,
		OriginalValue,
		Value,
		ManagerValue
	FROM (
		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID,
			ov.EntityID,
			ov.DepartmentID,
			ov.ChargeCodeID,
			ov.ServiceLineID,
			ov.AgeCohortID,
			ov.MedicalSurgicalID,
			ov.PatientClassID,
			ov.UnitTypeID,
			2 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID,
			ov.InitialValue as OriginalValue,
			v.Value,
			mgr.Value as ManagerValue
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID,ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, 
					cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12
				FROM chargevolume cv
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v
			ON ov.BudgetConfigID = v.BudgetConfigID
			AND ov.EntityGroupConfigID = v.EntityGroupConfigID
			AND ov.EntityID = v.EntityID
			AND ov.DepartmentID = v.DepartmentID
			AND ov.ChargeCodeID = v.ChargeCodeID
			AND ov.ServiceLineID = v.ServiceLineID
			AND ov.AgeCohortID = v.AgeCohortID
			AND ov.MedicalSurgicalID = v.MedicalSurgicalID
			AND ov.PatientClassID = v.PatientClassID
			AND ov.UnitTypeID = v.UnitTypeID
			AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN (
			-- Unpivot for ManagerValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr
			ON ov.BudgetConfigID = mgr.BudgetConfigID
			AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID
			AND ov.EntityID = mgr.EntityID
			AND ov.DepartmentID = mgr.DepartmentID
			AND ov.ChargeCodeID = mgr.ChargeCodeID
			AND ov.ServiceLineID = mgr.ServiceLineID
			AND ov.AgeCohortID = mgr.AgeCohortID
			AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID
			AND ov.PatientClassID = mgr.PatientClassID
			AND ov.UnitTypeID = mgr.UnitTypeID
			AND ov.FiscalMonthID = mgr.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID


		UNION ALL

		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID,
			ov.EntityID,
			ov.DepartmentID,
			ov.ChargeCodeID,
			ov.ServiceLineID,
			ov.AgeCohortID,
			ov.MedicalSurgicalID,
			ov.PatientClassID,	
			ov.UnitTypeID,
			12 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID - 1,
			ov.InitialValue as OriginalValue,
			v.Value,
			v.Value as ManagerValue -- Manager value is not different in CV for Projection
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 
				FROM chargevolume cv 
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v
			ON ov.BudgetConfigID = v.BudgetConfigID
			AND ov.EntityGroupConfigID = v.EntityGroupConfigID
			AND ov.EntityID = v.EntityID
			AND ov.DepartmentID = v.DepartmentID
			AND ov.ChargeCodeID = v.ChargeCodeID
			AND ov.ServiceLineID = v.ServiceLineID
			AND ov.AgeCohortID = v.AgeCohortID
			AND ov.MedicalSurgicalID = v.MedicalSurgicalID
			AND ov.PatientClassID = v.PatientClassID
			AND ov.UnitTypeID = v.UnitTypeID
			AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
	) cvData
GO


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

-- fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted
/**************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1	 2022-09-01	 JB		 JAZZ-32095	Remove Payor and PayorGroupID from joins.
*************************************************************/

CREATE VIEW fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted 
 AS
SELECT ChargeVolumeID,
	BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	DepartmentID,
	ChargeCodeID,
	ServiceLineID,
	AgeCohortID,
	MedicalSurgicalID,
	PatientClassID,
	UnitTypeID,
	TimeClassID,
	FiscalYearID,
	FiscalMonthID,
	AccountID,
	RVUWeight,
	Value FROM fp.FactReportChargeToStatisticsCrosswalkHistory
GO


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

-- fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2020-05-08  LR          JAZZ-20     Initial
** 2	2020-13-08	MY			JAZZ-4098	Performance tuning
** 3	2022-09-22	JB			JAZZ-32095	Remove Payor and PayorGroupID
** 4	2023-03-21	MY			JAZZ-49993	Update reporting to support new data model
*************************************************************/
CREATE   VIEW fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted_source  
 AS
	 -- The report source does not use data at the lowest level, so we're going to roll them up here so there is less data to pivot later. Pivoting is slow
	WITH chargevolume AS (
		SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, 
				SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, 
				SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, 
				SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, 
				SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, 
				SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, 
				SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06, 
				SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, 
				SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08,
				SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, 
				SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, 
				SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, 
				SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12, 
				SUM(hist.ActualYTDValue01) AS ActualYTDValue01, 
				SUM(hist.ActualYTDValue02) AS ActualYTDValue02, 
				SUM(hist.ActualYTDValue03) AS ActualYTDValue03, 
				SUM(hist.ActualYTDValue04) AS ActualYTDValue04, 
				SUM(hist.ActualYTDValue05) AS ActualYTDValue05, 
				SUM(hist.ActualYTDValue06) AS ActualYTDValue06, 
				SUM(hist.ActualYTDValue07) AS ActualYTDValue07, 
				SUM(hist.ActualYTDValue08) AS ActualYTDValue08,
				SUM(hist.ActualYTDValue09) AS ActualYTDValue09, 
				SUM(hist.ActualYTDValue10) AS ActualYTDValue10, 
				SUM(hist.ActualYTDValue11) AS ActualYTDValue11, 
				SUM(hist.ActualYTDValue12) AS ActualYTDValue12,
				SUM(hist.CurrentYearBudget01) AS CurrentYearBudgetValue01, 
				SUM(hist.CurrentYearBudget02) AS CurrentYearBudgetValue02, 
				SUM(hist.CurrentYearBudget03) AS CurrentYearBudgetValue03, 
				SUM(hist.CurrentYearBudget04) AS CurrentYearBudgetValue04, 
				SUM(hist.CurrentYearBudget05) AS CurrentYearBudgetValue05, 
				SUM(hist.CurrentYearBudget06) AS CurrentYearBudgetValue06, 
				SUM(hist.CurrentYearBudget07) AS CurrentYearBudgetValue07, 
				SUM(hist.CurrentYearBudget08) AS CurrentYearBudgetValue08,
				SUM(hist.CurrentYearBudget09) AS CurrentYearBudgetValue09, 
				SUM(hist.CurrentYearBudget10) AS CurrentYearBudgetValue10, 
				SUM(hist.CurrentYearBudget11) AS CurrentYearBudgetValue11, 
				SUM(hist.CurrentYearBudget12) AS CurrentYearBudgetValue12
		FROM fp.ChargeVolume cv 
			INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID
			INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
			INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID
			INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID
				AND cc.DepartmentID = cv.DepartmentID
				AND cc.PatientClassID = cv.PatientClassID
				AND cc.ChargeCodeID = cv.ChargeCodeID
				AND cc.EntityGroupConfigID = cv.EntityGroupConfigID
		WHERE bc.IsActive = 1
		GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID
	)
	SELECT
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		DepartmentID, 
		ChargeCodeID, 
		ServiceLineID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		PatientClassID, 
		UnitTypeID, 
		TimeClassID, 
		FiscalYearID, 
		FiscalMonthID,
		Value
	FROM (
		SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID,  data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
		FROM (
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID,
					fcv.PriorYearActualValue01, fcv.PriorYearActualValue02, fcv.PriorYearActualValue03, fcv.PriorYearActualValue04, fcv.PriorYearActualValue05, fcv.PriorYearActualValue06, fcv.PriorYearActualValue07, fcv.PriorYearActualValue08, fcv.PriorYearActualValue09, fcv.PriorYearActualValue10, fcv.PriorYearActualValue11, fcv.PriorYearActualValue12
				FROM chargevolume fcv ) fcv
				UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
			INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

		UNION ALL

		-- Unpivot for ActualYTD
		SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
		FROM (
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID,  PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, 
					fcv.ActualYTDValue01, fcv.ActualYTDValue02, fcv.ActualYTDValue03, fcv.ActualYTDValue04, fcv.ActualYTDValue05, fcv.ActualYTDValue06, fcv.ActualYTDValue07, fcv.ActualYTDValue08, fcv.ActualYTDValue09, fcv.ActualYTDValue10, fcv.ActualYTDValue11, fcv.ActualYTDValue12
				FROM chargevolume fcv ) fcv
				UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
			INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

		UNION ALL

		-- Unpivot for CurrentYearBudgetValue
		SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
		FROM (
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID,
					fcv.CurrentYearBudgetValue01, fcv.CurrentYearBudgetValue02, fcv.CurrentYearBudgetValue03, fcv.CurrentYearBudgetValue04, fcv.CurrentYearBudgetValue05, fcv.CurrentYearBudgetValue06, fcv.CurrentYearBudgetValue07, fcv.CurrentYearBudgetValue08, fcv.CurrentYearBudgetValue09, fcv.CurrentYearBudgetValue10, fcv.CurrentYearBudgetValue11, fcv.CurrentYearBudgetValue12
				FROM chargevolume fcv ) fcv
				UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudgetValue01, CurrentYearBudgetValue02, CurrentYearBudgetValue03, CurrentYearBudgetValue04, CurrentYearBudgetValue05, CurrentYearBudgetValue06, CurrentYearBudgetValue07, CurrentYearBudgetValue08, CurrentYearBudgetValue09, CurrentYearBudgetValue10, CurrentYearBudgetValue11, CurrentYearBudgetValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data
			INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

		) data
GO


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

-- fp.viewFactChargeToStatisticsCrosswalk_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2020-05-08  LR          JAZZ-20     Initial
** 2	2020-13-08	MY			JAZZ-4098	Performance tuning
** 3	2022-09-01	JB			JAZZ-32095	Remove Payor and PayorGroupID from joins.
** 4	2023-03-21	MY			JAZZ-49993	Update reporting to support new data model
*************************************************************/
CREATE   VIEW fp.viewFactChargeToStatisticsCrosswalk_Unpivoted_source  
AS
	WITH chargevolume AS (
		SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, 
				SUM(InitialBudget01) AS InitialBudget01, 
				SUM(InitialBudget02) AS InitialBudget02, 
				SUM(InitialBudget03) AS InitialBudget03, 
				SUM(InitialBudget04) AS InitialBudget04, 
				SUM(InitialBudget05) AS InitialBudget05, 
				SUM(InitialBudget06) AS InitialBudget06, 
				SUM(InitialBudget07) AS InitialBudget07, 
				SUM(InitialBudget08) AS InitialBudget08,
				SUM(InitialBudget09) AS InitialBudget09, 
				SUM(InitialBudget10) AS InitialBudget10, 
				SUM(InitialBudget11) AS InitialBudget11, 
				SUM(InitialBudget12) AS InitialBudget12, 
				SUM(InitialProjection01) AS InitialProjection01, 
				SUM(InitialProjection02) AS InitialProjection02, 
				SUM(InitialProjection03) AS InitialProjection03, 
				SUM(InitialProjection04) AS InitialProjection04, 
				SUM(InitialProjection05) AS InitialProjection05, 
				SUM(InitialProjection06) AS InitialProjection06, 
				SUM(InitialProjection07) AS InitialProjection07, 
				SUM(InitialProjection08) AS InitialProjection08,
				SUM(InitialProjection09) AS InitialProjection09, 
				SUM(InitialProjection10) AS InitialProjection10, 
				SUM(InitialProjection11) AS InitialProjection11, 
				SUM(InitialProjection12) AS InitialProjection12,
				SUM(TargetAdjusted01) AS TargetValue01, 
				SUM(TargetAdjusted02) AS TargetValue02, 
				SUM(TargetAdjusted03) AS TargetValue03, 
				SUM(TargetAdjusted04) AS TargetValue04, 
				SUM(TargetAdjusted05) AS TargetValue05, 
				SUM(TargetAdjusted06) AS TargetValue06, 
				SUM(TargetAdjusted07) AS TargetValue07, 
				SUM(TargetAdjusted08) AS TargetValue08,
				SUM(TargetAdjusted09) AS TargetValue09, 
				SUM(TargetAdjusted10) AS TargetValue10, 
				SUM(TargetAdjusted11) AS TargetValue11, 
				SUM(TargetAdjusted12) AS TargetValue12,
				SUM(BudgetAdjusted01) AS ManagerValue01, 
				SUM(BudgetAdjusted02) AS ManagerValue02, 
				SUM(BudgetAdjusted03) AS ManagerValue03, 
				SUM(BudgetAdjusted04) AS ManagerValue04, 
				SUM(BudgetAdjusted05) AS ManagerValue05, 
				SUM(BudgetAdjusted06) AS ManagerValue06, 
				SUM(BudgetAdjusted07) AS ManagerValue07, 
				SUM(BudgetAdjusted08) AS ManagerValue08,
				SUM(BudgetAdjusted09) AS ManagerValue09, 
				SUM(BudgetAdjusted10) AS ManagerValue10, 
				SUM(BudgetAdjusted11) AS ManagerValue11, 
				SUM(BudgetAdjusted12) AS ManagerValue12,
				SUM(ProjectionAdjusted01) AS ProjectedValue01, 
				SUM(ProjectionAdjusted02) AS ProjectedValue02, 
				SUM(ProjectionAdjusted03) AS ProjectedValue03, 
				SUM(ProjectionAdjusted04) AS ProjectedValue04, 
				SUM(ProjectionAdjusted05) AS ProjectedValue05, 
				SUM(ProjectionAdjusted06) AS ProjectedValue06, 
				SUM(ProjectionAdjusted07) AS ProjectedValue07, 
				SUM(ProjectionAdjusted08) AS ProjectedValue08,
				SUM(ProjectionAdjusted09) AS ProjectedValue09, 
				SUM(ProjectionAdjusted10) AS ProjectedValue10, 
				SUM(ProjectionAdjusted11) AS ProjectedValue11, 
				SUM(ProjectionAdjusted12) AS ProjectedValue12
		FROM fp.ChargeVolume cv 
			INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID
			INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID
			INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID
				AND cc.DepartmentID = cv.DepartmentID
				AND cc.PatientClassID = cv.PatientClassID
				AND cc.ChargeCodeID = cv.ChargeCodeID
		WHERE bc.IsActive = 1
		GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
			cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID
	)
	SELECT 
		BudgetConfigID,
		EntityGroupConfigID,
		EntityID,
		DepartmentID,
		ChargeCodeID,
		ServiceLineID,
		AgeCohortID,
		MedicalSurgicalID,
		PatientClassID,
		UnitTypeID,
		TimeClassID,
		FiscalMonthID,
		FiscalYearID,
		OriginalValue,
		Value,
		ManagerValue
	FROM (
		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID,
			ov.EntityID,
			ov.DepartmentID,
			ov.ChargeCodeID,
			ov.ServiceLineID,
			ov.AgeCohortID,
			ov.MedicalSurgicalID,
			ov.PatientClassID,
			ov.UnitTypeID,
			2 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID,
			ov.InitialValue as OriginalValue,
			v.Value,
			mgr.Value as ManagerValue
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, 
					cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12
				FROM chargevolume cv
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v
			ON ov.BudgetConfigID = v.BudgetConfigID
			AND ov.EntityGroupConfigID = v.EntityGroupConfigID
			AND ov.EntityID = v.EntityID
			AND ov.DepartmentID = v.DepartmentID
			AND ov.ChargeCodeID = v.ChargeCodeID
			AND ov.ServiceLineID = v.ServiceLineID
			AND ov.AgeCohortID = v.AgeCohortID
			AND ov.MedicalSurgicalID = v.MedicalSurgicalID
			AND ov.PatientClassID = v.PatientClassID
			AND ov.UnitTypeID = v.UnitTypeID
			AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN (
			-- Unpivot for ManagerValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr
			ON ov.BudgetConfigID = mgr.BudgetConfigID
			AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID
			AND ov.EntityID = mgr.EntityID
			AND ov.DepartmentID = mgr.DepartmentID
			AND ov.ChargeCodeID = mgr.ChargeCodeID
			AND ov.ServiceLineID = mgr.ServiceLineID
			AND ov.AgeCohortID = mgr.AgeCohortID
			AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID
			AND ov.PatientClassID = mgr.PatientClassID
			AND ov.UnitTypeID = mgr.UnitTypeID
			AND ov.FiscalMonthID = mgr.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID


		UNION ALL

		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID,
			ov.EntityID,
			ov.DepartmentID,
			ov.ChargeCodeID,
			ov.ServiceLineID,
			ov.AgeCohortID,
			ov.MedicalSurgicalID,
			ov.PatientClassID,	
			ov.UnitTypeID,
			12 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID - 1,
			ov.InitialValue as OriginalValue,
			v.Value,
			v.Value as ManagerValue -- Manager value is not different in CV for Projection
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 
				FROM chargevolume cv 
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,
					cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v
			ON ov.BudgetConfigID = v.BudgetConfigID
			AND ov.EntityGroupConfigID = v.EntityGroupConfigID
			AND ov.EntityID = v.EntityID
			AND ov.DepartmentID = v.DepartmentID
			AND ov.ChargeCodeID = v.ChargeCodeID
			AND ov.ServiceLineID = v.ServiceLineID
			AND ov.AgeCohortID = v.AgeCohortID
			AND ov.MedicalSurgicalID = v.MedicalSurgicalID
			AND ov.PatientClassID = v.PatientClassID
			AND ov.UnitTypeID = v.UnitTypeID
			AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
	) cvData
GO


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

-- fp.viewFactChargeVolume
CREATE   VIEW fp.viewFactChargeVolume
AS
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI				Description
	 ** 1	 2022-09-01	 JB		 JAZZ-32095		Remove Payor and PayorGroupID from joins.
	 ** 2	 2023-05-18	 MY		 JAZZ-55153		Update to new structure
	*************************************************************/	 
SELECT 
	fcv.BudgetConfigID,
	fcv.EntityGroupConfigID,
	fcv.EntityID,
	fcv.DepartmentID,
	fcv.ServiceLineID,
	fcv.PatientClassID,
	fcv.AgeCohortID,
	fcv.MedicalSurgicalID,
	fcv.ChargeCodeID,
	fcv.UnitTypeID,
	fcv.ServiceEntityID,
	fcv.MSDRGID,
	fcv.UBRevCodeID,
	fcv.PrimaryCPTID,
	fcv.BillingCPTID,
	fcv.ServiceProviderID,
	fcv.ServiceProviderSpecialtyID,
	fcv.PerformingProviderID,
	fcv.PerformingProviderSpecialtyID,
	2 AS BudgetPhaseID,
	fcv.BudgetLockType as BudgetLockType,
	fcv.BudgetLockFlag as BudgetLockFlag,
	fcv.ProjectionLockType as ProjectionLockType,
	fcv.ProjectionLockFlag as ProjectionLockFlag,
	fcv.TargetAdjusted01 AS AdjustedValue01, fcv.TargetAdjusted02 AS AdjustedValue02, fcv.TargetAdjusted03 AS AdjustedValue03, fcv.TargetAdjusted04 AS AdjustedValue04, fcv.TargetAdjusted05 AS AdjustedValue05, fcv.TargetAdjusted06 AS AdjustedValue06, 
	fcv.TargetAdjusted07 AS AdjustedValue07, fcv.TargetAdjusted08 AS AdjustedValue08, fcv.TargetAdjusted09 AS AdjustedValue09, fcv.TargetAdjusted10 AS AdjustedValue10, fcv.TargetAdjusted11 AS AdjustedValue11, fcv.TargetAdjusted12 AS AdjustedValue12, 
	fcv.TargetAdjustedTotal AS AdjustedValueTotal,

	fcv.TargetAdjusted01 AS FlexedValue01, fcv.TargetAdjusted02 AS FlexedValue02, fcv.TargetAdjusted03 AS FlexedValue03, fcv.TargetAdjusted04 AS FlexedValue04, fcv.TargetAdjusted05 AS FlexedValue05, fcv.TargetAdjusted06 AS FlexedValue06, 
	fcv.TargetAdjusted07 AS FlexedValue07, fcv.TargetAdjusted08 AS FlexedValue08, fcv.TargetAdjusted09 AS FlexedValue09, fcv.TargetAdjusted10 AS FlexedValue10, fcv.TargetAdjusted11 AS FlexedValue11, fcv.TargetAdjusted12 AS FlexedValue12, 
	fcv.TargetAdjustedTotal AS FlexedValueTotal,

	fcv.ProjectionAdjusted01 AS AdjustedProjectionValue01, fcv.ProjectionAdjusted02 AS AdjustedProjectionValue02, fcv.ProjectionAdjusted03 AS AdjustedProjectionValue03, fcv.ProjectionAdjusted04 AS AdjustedProjectionValue04, fcv.ProjectionAdjusted05 AS AdjustedProjectionValue05, fcv.ProjectionAdjusted06 AS AdjustedProjectionValue06, 
	fcv.ProjectionAdjusted07 AS AdjustedProjectionValue07, fcv.ProjectionAdjusted08 AS AdjustedProjectionValue08, fcv.ProjectionAdjusted09 AS AdjustedProjectionValue09, fcv.ProjectionAdjusted10 AS AdjustedProjectionValue10, fcv.ProjectionAdjusted11 AS AdjustedProjectionValue11, fcv.ProjectionAdjusted12 AS AdjustedProjectionValue12, 
	fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal,

	fcv.ProjectionAdjusted01 AS FlexedProjectionValue01, fcv.ProjectionAdjusted02 AS FlexedProjectionValue02, fcv.ProjectionAdjusted03 AS FlexedProjectionValue03, fcv.ProjectionAdjusted04 AS FlexedProjectionValue04, fcv.ProjectionAdjusted05 AS FlexedProjectionValue05, fcv.ProjectionAdjusted06 AS FlexedProjectionValue06, 
	fcv.ProjectionAdjusted07 AS FlexedProjectionValue07, fcv.ProjectionAdjusted08 AS FlexedProjectionValue08, fcv.ProjectionAdjusted09 AS FlexedProjectionValue09, fcv.ProjectionAdjusted10 AS FlexedProjectionValue10, fcv.ProjectionAdjusted11 AS FlexedProjectionValue11, fcv.ProjectionAdjusted12 AS FlexedProjectionValue12, 
	fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal,
	
	fcv.VariableDirectUnitCost
FROM fp.ChargeVolume fcv
UNION ALL
SELECT 
	fcv.BudgetConfigID,
	fcv.EntityGroupConfigID,
	fcv.EntityID,
	fcv.DepartmentID,
	fcv.ServiceLineID,
	fcv.PatientClassID,
	fcv.AgeCohortID,
	fcv.MedicalSurgicalID,
	fcv.ChargeCodeID,
	fcv.UnitTypeID,
	fcv.ServiceEntityID,
	fcv.MSDRGID,
	fcv.UBRevCodeID,
	fcv.PrimaryCPTID,
	fcv.BillingCPTID,
	fcv.ServiceProviderID,
	fcv.ServiceProviderSpecialtyID,
	fcv.PerformingProviderID,
	fcv.PerformingProviderSpecialtyID,
	3 AS BudgetPhaseID,
	fcv.BudgetLockType as BudgetLockType,
	fcv.BudgetLockFlag as BudgetLockFlag,
	fcv.ProjectionLockType as ProjectionLockType,
	fcv.ProjectionLockFlag as ProjectionLockFlag,
	fcv.BudgetAdjusted01 AS AdjustedValue01, fcv.BudgetAdjusted02 AS AdjustedValue02, fcv.BudgetAdjusted03 AS AdjustedValue03, fcv.BudgetAdjusted04 AS AdjustedValue04, fcv.BudgetAdjusted05 AS AdjustedValue05, fcv.BudgetAdjusted06 AS AdjustedValue06, 
	fcv.BudgetAdjusted07 AS AdjustedValue07, fcv.BudgetAdjusted08 AS AdjustedValue08, fcv.BudgetAdjusted09 AS AdjustedValue09, fcv.BudgetAdjusted10 AS AdjustedValue10, fcv.BudgetAdjusted11 AS AdjustedValue11, fcv.BudgetAdjusted12 AS AdjustedValue12, 
	fcv.BudgetAdjustedTotal AS AdjustedValueTotal,

	fcv.BudgetAdjusted01 AS FlexedValue01, fcv.BudgetAdjusted02 AS FlexedValue02, fcv.BudgetAdjusted03 AS FlexedValue03, fcv.BudgetAdjusted04 AS FlexedValue04, fcv.BudgetAdjusted05 AS FlexedValue05, fcv.BudgetAdjusted06 AS FlexedValue06, 
	fcv.BudgetAdjusted07 AS FlexedValue07, fcv.BudgetAdjusted08 AS FlexedValue08, fcv.BudgetAdjusted09 AS FlexedValue09, fcv.BudgetAdjusted10 AS FlexedValue10, fcv.BudgetAdjusted11 AS FlexedValue11, fcv.BudgetAdjusted12 AS FlexedValue12, 
	fcv.BudgetAdjustedTotal AS FlexedValueTotal,

	fcv.ProjectionAdjusted01 AS AdjustedProjectionValue01, fcv.ProjectionAdjusted02 AS AdjustedProjectionValue02, fcv.ProjectionAdjusted03 AS AdjustedProjectionValue03, fcv.ProjectionAdjusted04 AS AdjustedProjectionValue04, fcv.ProjectionAdjusted05 AS AdjustedProjectionValue05, fcv.ProjectionAdjusted06 AS AdjustedProjectionValue06, 
	fcv.ProjectionAdjusted07 AS AdjustedProjectionValue07, fcv.ProjectionAdjusted08 AS AdjustedProjectionValue08, fcv.ProjectionAdjusted09 AS AdjustedProjectionValue09, fcv.ProjectionAdjusted10 AS AdjustedProjectionValue10, fcv.ProjectionAdjusted11 AS AdjustedProjectionValue11, fcv.ProjectionAdjusted12 AS AdjustedProjectionValue12, 
	fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal,

	fcv.ProjectionAdjusted01 AS FlexedProjectionValue01, fcv.ProjectionAdjusted02 AS FlexedProjectionValue02, fcv.ProjectionAdjusted03 AS FlexedProjectionValue03, fcv.ProjectionAdjusted04 AS FlexedProjectionValue04, fcv.ProjectionAdjusted05 AS FlexedProjectionValue05, fcv.ProjectionAdjusted06 AS FlexedProjectionValue06, 
	fcv.ProjectionAdjusted07 AS FlexedProjectionValue07, fcv.ProjectionAdjusted08 AS FlexedProjectionValue08, fcv.ProjectionAdjusted09 AS FlexedProjectionValue09, fcv.ProjectionAdjusted10 AS FlexedProjectionValue10, fcv.ProjectionAdjusted11 AS FlexedProjectionValue11, fcv.ProjectionAdjusted12 AS FlexedProjectionValue12, 
	fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal,
	
	fcv.VariableDirectUnitCost
FROM fp.ChargeVolume fcv
GO


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

-- fp.viewFactChargeVolumeDollarsHistory_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2022-01-03  MD          JAZZ-29138  Initial
** 2    2023-05-18  MY          JAZZ-55153  Update to new structure
*************************************************************/
CREATE   VIEW [fp].[viewFactChargeVolumeDollarsHistory_Unpivoted_source]  
AS

-- Unpivot for PriorYearActual
SELECT 
	data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
	ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
	PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, 34 as UnitTypeID,
	1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
	SELECT 
		BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
		PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT 
			cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
			cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, 
			hist.PriorYearActualDollarValue01, hist.PriorYearActualDollarValue02, hist.PriorYearActualDollarValue03, hist.PriorYearActualDollarValue04, hist.PriorYearActualDollarValue05, hist.PriorYearActualDollarValue06, 
			hist.PriorYearActualDollarValue07, hist.PriorYearActualDollarValue08, hist.PriorYearActualDollarValue09, hist.PriorYearActualDollarValue10, hist.PriorYearActualDollarValue11, hist.PriorYearActualDollarValue12
		FROM [fp].[ChargeVolume] cv
		INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
		WHERE cv.UnitTypeID = 145) cv
		UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualDollarValue01, PriorYearActualDollarValue02, PriorYearActualDollarValue03, PriorYearActualDollarValue04, PriorYearActualDollarValue05, PriorYearActualDollarValue06, 
			PriorYearActualDollarValue07, PriorYearActualDollarValue08, PriorYearActualDollarValue09, PriorYearActualDollarValue10, PriorYearActualDollarValue11, PriorYearActualDollarValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
	INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
	
UNION ALL

-- Unpivot for ActualYTD
SELECT 
	data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
	ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
	PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, 34 as UnitTypeID,
	1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
	SELECT 
		BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
		PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT 
			cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
			cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, 
			hist.ActualYTDDollarValue01, hist.ActualYTDDollarValue02, hist.ActualYTDDollarValue03, hist.ActualYTDDollarValue04, hist.ActualYTDDollarValue05, hist.ActualYTDDollarValue06, 
			hist.ActualYTDDollarValue07, hist.ActualYTDDollarValue08, hist.ActualYTDDollarValue09, hist.ActualYTDDollarValue10, hist.ActualYTDDollarValue11, hist.ActualYTDDollarValue12
		FROM [fp].[ChargeVolume] cv
		INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
		WHERE cv.UnitTypeID = 145) cv
		UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDDollarValue01, ActualYTDDollarValue02, ActualYTDDollarValue03, ActualYTDDollarValue04, ActualYTDDollarValue05, ActualYTDDollarValue06, ActualYTDDollarValue07, ActualYTDDollarValue08, 
		ActualYTDDollarValue09, ActualYTDDollarValue10, ActualYTDDollarValue11, ActualYTDDollarValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
	INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for CurrentYearBudget
SELECT 
	data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
	ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
	PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, 34 as UnitTypeID,
	2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
	SELECT 
		BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
		PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT 
			cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
			cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, 
			hist.CurrentYearBudgetDollar01, hist.CurrentYearBudgetDollar02, hist.CurrentYearBudgetDollar03, hist.CurrentYearBudgetDollar04, hist.CurrentYearBudgetDollar05, hist.CurrentYearBudgetDollar06, 
			hist.CurrentYearBudgetDollar07, hist.CurrentYearBudgetDollar08, hist.CurrentYearBudgetDollar09, hist.CurrentYearBudgetDollar10, hist.CurrentYearBudgetDollar11, hist.CurrentYearBudgetDollar12
		FROM [fp].[ChargeVolume] cv
		INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
		WHERE cv.UnitTypeID = 145) cv
		UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudgetDollar01, CurrentYearBudgetDollar02, CurrentYearBudgetDollar03, CurrentYearBudgetDollar04, CurrentYearBudgetDollar05, CurrentYearBudgetDollar06, 
			CurrentYearBudgetDollar07, CurrentYearBudgetDollar08, CurrentYearBudgetDollar09, CurrentYearBudgetDollar10, CurrentYearBudgetDollar11, CurrentYearBudgetDollar12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data
	INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactChargeVolumeDollars_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2020-12-28  MD          JAZZ-29138  Initial
** 2    2023-05-18  MY          JAZZ-55153  Update to new structure
*************************************************************/
CREATE   VIEW [fp].[viewFactChargeVolumeDollars_Unpivoted_source]  
AS
	WITH chargevolume AS (
		SELECT  
			cv.BudgetConfigID,
			cv.EntityGroupConfigID, 
			cv.EntityID, 
			cv.DepartmentID, 
			cv.ServiceLineID, 
			cv.PatientClassID, 
			cv.AgeCohortID, 
			cv.MedicalSurgicalID, 
			cv.ChargeCodeID, 
			cv.ServiceEntityID,
			cv.MSDRGID,
			cv.UBRevCodeID,
			cv.PrimaryCPTID,
			cv.ServiceProviderID,
			cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID,
			cv.PerformingProviderSpecialtyID,
			cv.BillingCPTID,
			34 as UnitTypeID,
			SUM(cv.InitialBudgetDollars01) AS InitialBudget01, 
			SUM(cv.InitialBudgetDollars02) AS InitialBudget02, 
			SUM(cv.InitialBudgetDollars03) AS InitialBudget03, 
			SUM(cv.InitialBudgetDollars04) AS InitialBudget04, 
			SUM(cv.InitialBudgetDollars05) AS InitialBudget05, 
			SUM(cv.InitialBudgetDollars06) AS InitialBudget06, 
			SUM(cv.InitialBudgetDollars07) AS InitialBudget07, 
			SUM(cv.InitialBudgetDollars08) AS InitialBudget08,
			SUM(cv.InitialBudgetDollars09) AS InitialBudget09, 
			SUM(cv.InitialBudgetDollars10) AS InitialBudget10, 
			SUM(cv.InitialBudgetDollars11) AS InitialBudget11, 
			SUM(cv.InitialBudgetDollars12) AS InitialBudget12, 
			SUM(cv.InitialProjectionDollars01) AS InitialProjection01, 
			SUM(cv.InitialProjectionDollars02) AS InitialProjection02, 
			SUM(cv.InitialProjectionDollars03) AS InitialProjection03, 
			SUM(cv.InitialProjectionDollars04) AS InitialProjection04, 
			SUM(cv.InitialProjectionDollars05) AS InitialProjection05, 
			SUM(cv.InitialProjectionDollars06) AS InitialProjection06, 
			SUM(cv.InitialProjectionDollars07) AS InitialProjection07, 
			SUM(cv.InitialProjectionDollars08) AS InitialProjection08,
			SUM(cv.InitialProjectionDollars09) AS InitialProjection09, 
			SUM(cv.InitialProjectionDollars10) AS InitialProjection10, 
			SUM(cv.InitialProjectionDollars11) AS InitialProjection11, 
			SUM(cv.InitialProjectionDollars12) AS InitialProjection12,
			SUM(cv.TargetDollarsAdjusted01) AS TargetValue01, 
			SUM(cv.TargetDollarsAdjusted02) AS TargetValue02, 
			SUM(cv.TargetDollarsAdjusted03) AS TargetValue03, 
			SUM(cv.TargetDollarsAdjusted04) AS TargetValue04, 
			SUM(cv.TargetDollarsAdjusted05) AS TargetValue05, 
			SUM(cv.TargetDollarsAdjusted06) AS TargetValue06, 
			SUM(cv.TargetDollarsAdjusted07) AS TargetValue07, 
			SUM(cv.TargetDollarsAdjusted08) AS TargetValue08,
			SUM(cv.TargetDollarsAdjusted09) AS TargetValue09, 
			SUM(cv.TargetDollarsAdjusted10) AS TargetValue10, 
			SUM(cv.TargetDollarsAdjusted11) AS TargetValue11, 
			SUM(cv.TargetDollarsAdjusted12) AS TargetValue12,
			SUM(cv.BudgetDollarsAdjusted01) AS ManagerValue01, 
			SUM(cv.BudgetDollarsAdjusted02) AS ManagerValue02, 
			SUM(cv.BudgetDollarsAdjusted03) AS ManagerValue03, 
			SUM(cv.BudgetDollarsAdjusted04) AS ManagerValue04, 
			SUM(cv.BudgetDollarsAdjusted05) AS ManagerValue05, 
			SUM(cv.BudgetDollarsAdjusted06) AS ManagerValue06, 
			SUM(cv.BudgetDollarsAdjusted07) AS ManagerValue07, 
			SUM(cv.BudgetDollarsAdjusted08) AS ManagerValue08,
			SUM(cv.BudgetDollarsAdjusted09) AS ManagerValue09, 
			SUM(cv.BudgetDollarsAdjusted10) AS ManagerValue10, 
			SUM(cv.BudgetDollarsAdjusted11) AS ManagerValue11, 
			SUM(cv.BudgetDollarsAdjusted12) AS ManagerValue12,
			SUM(cv.ProjectionDollarsAdjusted01) AS ProjectedValue01, 
			SUM(cv.ProjectionDollarsAdjusted02) AS ProjectedValue02, 
			SUM(cv.ProjectionDollarsAdjusted03) AS ProjectedValue03, 
			SUM(cv.ProjectionDollarsAdjusted04) AS ProjectedValue04, 
			SUM(cv.ProjectionDollarsAdjusted05) AS ProjectedValue05, 
			SUM(cv.ProjectionDollarsAdjusted06) AS ProjectedValue06, 
			SUM(cv.ProjectionDollarsAdjusted07) AS ProjectedValue07, 
			SUM(cv.ProjectionDollarsAdjusted08) AS ProjectedValue08,
			SUM(cv.ProjectionDollarsAdjusted09) AS ProjectedValue09, 
			SUM(cv.ProjectionDollarsAdjusted10) AS ProjectedValue10, 
			SUM(cv.ProjectionDollarsAdjusted11) AS ProjectedValue11, 
			SUM(cv.ProjectionDollarsAdjusted12) AS ProjectedValue12
		FROM fp.ChargeVolume cv 
			INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID
			INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID			
		WHERE 
			bc.IsActive = 1
			AND cv.UnitTypeID = 145
		GROUP BY 
			cv.BudgetConfigID,
			cv.EntityGroupConfigID, 
			cv.EntityID, 
			cv.DepartmentID, 
			cv.ServiceLineID, 
			cv.PatientClassID, 
			cv.AgeCohortID, 
			cv.MedicalSurgicalID, 
			cv.ChargeCodeID, 
			cv.ServiceEntityID,
			cv.MSDRGID,
			cv.UBRevCodeID,
			cv.PrimaryCPTID,
			cv.ServiceProviderID,
			cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID,
			cv.PerformingProviderSpecialtyID,	
			cv.BillingCPTID,
			cv.UnitTypeID
	)
	SELECT 
		BudgetConfigID,
		EntityGroupConfigID, 
		EntityID, 
		DepartmentID, 
		ServiceLineID, 
		PatientClassID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		ChargeCodeID, 
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,	
		BillingCPTID,
		UnitTypeID,
		TimeClassID,
		FiscalMonthID,
		FiscalYearID,
		OriginalValue,
		Value,
		ManagerValue
	FROM (
		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID, 
			ov.EntityID, 
			ov.DepartmentID, 
			ov.ServiceLineID, 
			ov.PatientClassID, 
			ov.AgeCohortID, 
			ov.MedicalSurgicalID, 
			ov.ChargeCodeID, 
			ov.ServiceEntityID,
			ov.MSDRGID,
			ov.UBRevCodeID,
			ov.PrimaryCPTID,
			ov.ServiceProviderID,
			ov.ServiceProviderSpecialtyID,
			ov.PerformingProviderID,
			ov.PerformingProviderSpecialtyID,		
			ov.BillingCPTID,
			ov.UnitTypeID,			
			2 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID,
			ov.InitialValue as OriginalValue,
			v.Value,
			mgr.Value as ManagerValue
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12
				FROM chargevolume cv
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v
			ON 
				ov.BudgetConfigID = v.BudgetConfigID
				AND ov.EntityGroupConfigID = v.EntityGroupConfigID 
				AND ov.EntityID = v.EntityID 
				AND ov.DepartmentID = v.DepartmentID 
				AND ov.ServiceLineID = v.ServiceLineID 
				AND ov.PatientClassID = v.PatientClassID 
				AND ov.AgeCohortID = v.AgeCohortID 
				AND ov.MedicalSurgicalID = v.MedicalSurgicalID 
				AND ov.ChargeCodeID = v.ChargeCodeID 
				AND ov.ServiceEntityID = v.ServiceEntityID
				AND ov.MSDRGID = v.MSDRGID
				AND ov.UBRevCodeID = v.UBRevCodeID
				AND ov.PrimaryCPTID = v.PrimaryCPTID
				AND ov.ServiceProviderID = v.ServiceProviderID
				AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
				AND ov.PerformingProviderID = v.PerformingProviderID
				AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID   
				AND ov.BillingCPTID = v.BillingCPTID
				AND ov.UnitTypeID = v.UnitTypeID
				AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN (
			-- Unpivot for ManagerValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr
			ON 
				ov.BudgetConfigID = mgr.BudgetConfigID
				AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID 
				AND ov.EntityID = mgr.EntityID 
				AND ov.DepartmentID = mgr.DepartmentID 
				AND ov.ServiceLineID = mgr.ServiceLineID 
				AND ov.PatientClassID = mgr.PatientClassID 
				AND ov.AgeCohortID = mgr.AgeCohortID 
				AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID 
				AND ov.ChargeCodeID = mgr.ChargeCodeID 
				AND ov.ServiceEntityID = mgr.ServiceEntityID
				AND ov.MSDRGID = mgr.MSDRGID
				AND ov.UBRevCodeID = mgr.UBRevCodeID
				AND ov.PrimaryCPTID = mgr.PrimaryCPTID
				AND ov.ServiceProviderID = mgr.ServiceProviderID
				AND ov.ServiceProviderSpecialtyID = mgr.ServiceProviderSpecialtyID
				AND ov.PerformingProviderID = mgr.PerformingProviderID
				AND ov.PerformingProviderSpecialtyID = mgr.PerformingProviderSpecialtyID 
				AND ov.BillingCPTID = mgr.BillingCPTID
				AND ov.UnitTypeID = mgr.UnitTypeID
				AND ov.FiscalMonthID = mgr.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID


		UNION ALL

		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID, 
			ov.EntityID, 
			ov.DepartmentID, 
			ov.ServiceLineID, 
			ov.PatientClassID, 
			ov.AgeCohortID, 
			ov.MedicalSurgicalID, 
			ov.ChargeCodeID, 
			ov.ServiceEntityID,
			ov.MSDRGID,
			ov.UBRevCodeID,
			ov.PrimaryCPTID,
			ov.ServiceProviderID,
			ov.ServiceProviderSpecialtyID,
			ov.PerformingProviderID,
			ov.PerformingProviderSpecialtyID,	
			ov.BillingCPTID,
			ov.UnitTypeID,	
			12 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID - 1,
			ov.InitialValue as OriginalValue,
			v.Value,
			v.Value as ManagerValue -- Manager value is not different in CV for Projection
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 
				FROM chargevolume cv 
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v
			ON 
				ov.BudgetConfigID = v.BudgetConfigID
				AND ov.EntityGroupConfigID = v.EntityGroupConfigID 
				AND ov.EntityID = v.EntityID 
				AND ov.DepartmentID = v.DepartmentID 
				AND ov.ServiceLineID = v.ServiceLineID 
				AND ov.PatientClassID = v.PatientClassID 
				AND ov.AgeCohortID = v.AgeCohortID 
				AND ov.MedicalSurgicalID = v.MedicalSurgicalID 
				AND ov.ChargeCodeID = v.ChargeCodeID 
				AND ov.ServiceEntityID = v.ServiceEntityID
				AND ov.MSDRGID = v.MSDRGID
				AND ov.UBRevCodeID = v.UBRevCodeID
				AND ov.PrimaryCPTID = v.PrimaryCPTID
				AND ov.ServiceProviderID = v.ServiceProviderID
				AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
				AND ov.PerformingProviderID = v.PerformingProviderID
				AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID
				AND ov.BillingCPTID = v.BillingCPTID
				AND ov.UnitTypeID = v.UnitTypeID
				AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
	) cvData
GO


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

-- fp.viewFactChargeVolumeHistory_Unpivoted
CREATE   VIEW fp.viewFactChargeVolumeHistory_Unpivoted
AS
/**************************************************************
** Change History
**************************************************************
** CID   Date        Author  WI				Description
** 1	 2022-09-01	 JB		 JAZZ-32095		Remove Payor and PayorGroupID from joins.
** 2	 2023-05-18	 MY		 JAZZ-55153		Update to new structure
*************************************************************/	 

-- Unpivot for PriorYearActual
SELECT data.ChargeVolumeID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ServiceLineID, data.PatientClassID, data.AgeCohortID, data.MedicalSurgicalID, ChargeCodeID, data.UnitTypeID,
data.ServiceEntityID,
MSDRGID,
UBRevCodeID,
PrimaryCPTID,
BillingCPTID,
ServiceProviderID,
ServiceProviderSpecialtyID,
PerformingProviderID,
PerformingProviderSpecialtyID,
1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
ServiceEntityID,
MSDRGID,
UBRevCodeID,
PrimaryCPTID,
BillingCPTID,
ServiceProviderID,
ServiceProviderSpecialtyID,
PerformingProviderID,
PerformingProviderSpecialtyID,
UnitTypeID, m.FiscalMonthID, f.Value
FROM (
SELECT fs.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12
FROM fp.ChargeVolume fs
INNER JOIN fp.ChargeVolumeHistory hist ON fs.ChargeVolumeID = hist.ChargeVolumeID ) fs
UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f
LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for ActualYTD
SELECT data.ChargeVolumeID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ServiceLineID, data.PatientClassID, data.AgeCohortID, data.MedicalSurgicalID, ChargeCodeID, data.UnitTypeID,
ServiceEntityID,
MSDRGID,
UBRevCodeID,
PrimaryCPTID,
BillingCPTID,
ServiceProviderID,
ServiceProviderSpecialtyID,
PerformingProviderID,
PerformingProviderSpecialtyID,
1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
ServiceEntityID,
MSDRGID,
UBRevCodeID,
PrimaryCPTID,
BillingCPTID,
ServiceProviderID,
ServiceProviderSpecialtyID,
PerformingProviderID,
PerformingProviderSpecialtyID,
 UnitTypeID, m.FiscalMonthID, f.Value
FROM (
SELECT fs.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12
FROM fp.ChargeVolume fs
INNER JOIN fp.ChargeVolumeHistory hist ON fs.ChargeVolumeID = hist.ChargeVolumeID ) fs
UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f
LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for CurrentYearBudgetValue
SELECT data.ChargeVolumeID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ServiceLineID, data.PatientClassID, data.AgeCohortID, data.MedicalSurgicalID, ChargeCodeID, data.UnitTypeID,
ServiceEntityID,
MSDRGID,
UBRevCodeID,
PrimaryCPTID,
BillingCPTID,
ServiceProviderID,
ServiceProviderSpecialtyID,
PerformingProviderID,
PerformingProviderSpecialtyID,
2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
ServiceEntityID,
MSDRGID,
UBRevCodeID,
PrimaryCPTID,
BillingCPTID,
ServiceProviderID,
ServiceProviderSpecialtyID,
PerformingProviderID,
PerformingProviderSpecialtyID,
 UnitTypeID, m.FiscalMonthID, f.Value
FROM (
SELECT fs.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12
FROM fp.ChargeVolume fs
INNER JOIN fp.ChargeVolumeHistory hist ON fs.ChargeVolumeID = hist.ChargeVolumeID ) fs
UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f
LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data
INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactChargeVolumeHistory_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2022-01-03  MD          JAZZ-29138  Initial
** 2    2023-05-18  MY          JAZZ-55153  Update to new structure
*************************************************************/
CREATE   VIEW [fp].[viewFactChargeVolumeHistory_Unpivoted_source]  
AS

-- Unpivot for PriorYearActual
SELECT 
	data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
	ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
	PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID,
	1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
	SELECT 
		BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
		PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT 
			cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
			cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, 
			hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, 
			hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12
		FROM [fp].[ChargeVolume] cv
		INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
		WHERE cv.UnitTypeID = 145) cv
		UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, 
			PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
	INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
	
UNION ALL

-- Unpivot for ActualYTD
SELECT 
	data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
	ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
	PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID,
	1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
	SELECT 
		BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
		PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT 
			cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
			cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, 
			hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, 
			hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12
		FROM [fp].[ChargeVolume] cv
		INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
		WHERE cv.UnitTypeID = 145) cv
		UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, 
		ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
	INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for CurrentYearBudget
SELECT 
	data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
	ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
	PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID,
	2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
	SELECT 
		BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
		PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT 
			cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
			cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, 
			hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, 
			hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12
		FROM [fp].[ChargeVolume] cv
		INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID 
		WHERE cv.UnitTypeID = 145) cv
		UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, 
			CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data
	INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactChargeVolume_Totals
CREATE   VIEW fp.viewFactChargeVolume_Totals
AS
/**************************************************************
** Change History
**************************************************************
** CID   Date        Author  WI				Description
** 1	 2022-09-01	 JB		 JAZZ-32095		Remove Payor and PayorGroupID from joins.
** 2	 2023-05-18	 MY		 JAZZ-55153		Update to new structure
*************************************************************/	 
SELECT 
	fcv.BudgetConfigID,
	fcv.EntityGroupConfigID,
	fcv.EntityID,
	fcv.DepartmentID,
	fcv.ServiceLineID,
	fcv.PatientClassID,
	fcv.AgeCohortID,
	fcv.MedicalSurgicalID,
	fcv.ChargeCodeID,
	fcv.UnitTypeID,
	fcv.ServiceEntityID,
	fcv.MSDRGID,
	fcv.UBRevCodeID,
	fcv.PrimaryCPTID,
	fcv.BillingCPTID,
	fcv.ServiceProviderID,
	fcv.ServiceProviderSpecialtyID,
	fcv.PerformingProviderID,
	fcv.PerformingProviderSpecialtyID,
	2 AS BudgetPhaseID,
	fcv.BudgetLockType as BudgetLockType,
	fcv.BudgetLockFlag as BudgetLockFlag,
	fcv.ProjectionLockType as ProjectionLockType,
	fcv.ProjectionLockFlag as ProjectionLockFlag,
	fcv.TargetAdjustedTotal AS AdjustedValueTotal,
	fcv.TargetAdjustedTotal AS FlexedValueTotal,
	fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal,
	fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal,
	fcv.VariableDirectUnitCost
FROM fp.ChargeVolume fcv
UNION ALL
SELECT 
	fcv.BudgetConfigID,
	fcv.EntityGroupConfigID,
	fcv.EntityID,
	fcv.DepartmentID,
	fcv.ServiceLineID,
	fcv.PatientClassID,
	fcv.AgeCohortID,
	fcv.MedicalSurgicalID,
	fcv.ChargeCodeID,
	fcv.UnitTypeID,
	fcv.ServiceEntityID,
	fcv.MSDRGID,
	fcv.UBRevCodeID,
	fcv.PrimaryCPTID,
	fcv.BillingCPTID,
	fcv.ServiceProviderID,
	fcv.ServiceProviderSpecialtyID,
	fcv.PerformingProviderID,
	fcv.PerformingProviderSpecialtyID,
	3 AS BudgetPhaseID,
	fcv.BudgetLockType as BudgetLockType,
	fcv.BudgetLockFlag as BudgetLockFlag,
	fcv.ProjectionLockType as ProjectionLockType,
	fcv.ProjectionLockFlag as ProjectionLockFlag,
	fcv.BudgetAdjustedTotal AS AdjustedValueTotal,
	fcv.BudgetAdjustedTotal AS FlexedValueTotal,
	fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal,
	fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal,
	fcv.VariableDirectUnitCost
FROM fp.ChargeVolume fcv
GO


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

-- fp.viewFactChargeVolume_Unpivoted
CREATE   VIEW fp.viewFactChargeVolume_Unpivoted
AS
/**************************************************************
** Change History
**************************************************************
** CID   Date        Author  WI			 Description
** 1	 2022-09-01	 JB		 JAZZ-32095	 Remove Payor and PayorGroupID from joins.
** 2	 2023-05-18	 MY		 JAZZ-55153	 Update to new structure
*************************************************************/	 
SELECT 
	ov.ChargeVolumeID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.ServiceLineID,
	ov.PatientClassID,
	ov.AgeCohortID,
	ov.MedicalSurgicalID,
	ov.ChargeCodeID,
	ov.UnitTypeID,
	ov.ServiceEntityID,
	ov.MSDRGID,
	ov.UBRevCodeID,
	ov.PrimaryCPTID,
	ov.BillingCPTID,
	ov.ServiceProviderID,
	ov.ServiceProviderSpecialtyID,
	ov.PerformingProviderID,
	ov.PerformingProviderSpecialtyID,
	2 as TimeClassID,
	ov.FiscalMonthID,
	ov.InitialValue as OriginalValue,
	v.Value,
	mgrv.Value as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID,
	ServiceEntityID,
	MSDRGID,
	UBRevCodeID,
	PrimaryCPTID,
	BillingCPTID,
	ServiceProviderID,
	ServiceProviderSpecialtyID,
	PerformingProviderID,
	PerformingProviderSpecialtyID,
	m.FiscalMonthID,
	f.InitialValue
	FROM (
		SELECT cv.*
		FROM fp.ChargeVolume cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID,
	ServiceEntityID,
	MSDRGID,
	UBRevCodeID,
	PrimaryCPTID,
	BillingCPTID,
	ServiceProviderID,
	ServiceProviderSpecialtyID,
	PerformingProviderID,
	PerformingProviderSpecialtyID,
	m.FiscalMonthID,
	f.Value,
	LockType
	FROM (
		SELECT fcv.*, fcv.TargetLockType AS LockType, 
			fcv.TargetAdjusted01 AS AdjustedValue01, fcv.TargetAdjusted02 AS AdjustedValue02, fcv.TargetAdjusted03 AS AdjustedValue03, fcv.TargetAdjusted04 AS AdjustedValue04, fcv.TargetAdjusted05 AS AdjustedValue05, 
			fcv.TargetAdjusted06 AS AdjustedValue06, fcv.TargetAdjusted07 AS AdjustedValue07, fcv.TargetAdjusted08 AS AdjustedValue08, fcv.TargetAdjusted09 AS AdjustedValue09, fcv.TargetAdjusted10 AS AdjustedValue10, 
			fcv.TargetAdjusted11 AS AdjustedValue11, fcv.TargetAdjusted12 AS AdjustedValue12
		FROM fp.ChargeVolume fcv) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.ServiceLineID = v.ServiceLineID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.AgeCohortID = v.AgeCohortID
	AND ov.MedicalSurgicalID = v.MedicalSurgicalID
	AND ov.ChargeCodeID = v.ChargeCodeID
	AND ov.ServiceEntityID = v.ServiceEntityID
	AND ov.MSDRGID = v.MSDRGID
	AND ov.UBRevCodeID = v.UBRevCodeID
	AND ov.PrimaryCPTID = v.PrimaryCPTID
	AND ov.BillingCPTID = v.BillingCPTID
	AND ov.ServiceProviderID = v.ServiceProviderID
	AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
	AND ov.PerformingProviderID = v.PerformingProviderID
	AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for Manager Value
	SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID,
	ServiceEntityID,
	MSDRGID,
	UBRevCodeID,
	PrimaryCPTID,
	BillingCPTID,
	ServiceProviderID,
	ServiceProviderSpecialtyID,
	PerformingProviderID,
	PerformingProviderSpecialtyID, 
	m.FiscalMonthID, 
	f.Value, 
	LockType
	FROM (
		SELECT fcv.*, fcv.BudgetLockType AS LockType, 
			fcv.BudgetAdjusted01 AS AdjustedValue01, fcv.BudgetAdjusted02 AS AdjustedValue02, fcv.BudgetAdjusted03 AS AdjustedValue03, fcv.BudgetAdjusted04 AS AdjustedValue04, fcv.BudgetAdjusted05 AS AdjustedValue05, 
			fcv.BudgetAdjusted06 AS AdjustedValue06, fcv.BudgetAdjusted07 AS AdjustedValue07, fcv.BudgetAdjusted08 AS AdjustedValue08, fcv.BudgetAdjusted09 AS AdjustedValue09, fcv.BudgetAdjusted10 AS AdjustedValue10, 
			fcv.BudgetAdjusted11 AS AdjustedValue11, fcv.BudgetAdjusted12 AS AdjustedValue12
		FROM fp.ChargeVolume fcv) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.DepartmentID = mgrv.DepartmentID
	AND ov.ServiceLineID = mgrv.ServiceLineID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.AgeCohortID = mgrv.AgeCohortID
	AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID
	AND ov.ChargeCodeID = mgrv.ChargeCodeID
	AND ov.ChargeCodeID = v.ChargeCodeID
	AND ov.ServiceEntityID = v.ServiceEntityID
	AND ov.MSDRGID = v.MSDRGID
	AND ov.UBRevCodeID = v.UBRevCodeID
	AND ov.PrimaryCPTID = v.PrimaryCPTID
	AND ov.BillingCPTID = v.BillingCPTID
	AND ov.ServiceProviderID = v.ServiceProviderID
	AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
	AND ov.PerformingProviderID = v.PerformingProviderID
	AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID

UNION ALL

	SELECT
	ov.ChargeVolumeID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.ServiceLineID,
	ov.PatientClassID,
	ov.AgeCohortID,
	ov.MedicalSurgicalID,
	ov.ChargeCodeID,
	ov.UnitTypeID,	
	ov.ServiceEntityID,
	ov.MSDRGID,
	ov.UBRevCodeID,
	ov.PrimaryCPTID,
	ov.BillingCPTID,
	ov.ServiceProviderID,
	ov.ServiceProviderSpecialtyID,
	ov.PerformingProviderID,
	ov.PerformingProviderSpecialtyID,
	12 as TimeClassID,
	ov.FiscalMonthID,
	ov.InitialValue as OriginalValue,
	v.Value,
	mgrv.Value as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, 	
	ServiceEntityID,
	MSDRGID,
	UBRevCodeID,
	PrimaryCPTID,
	BillingCPTID,
	ServiceProviderID,
	ServiceProviderSpecialtyID,
	PerformingProviderID,
	PerformingProviderSpecialtyID,
	m.FiscalMonthID,
	f.InitialValue
	FROM (
		SELECT cv.*
		FROM fp.ChargeVolume cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, 
	ServiceEntityID,
	MSDRGID,
	UBRevCodeID,
	PrimaryCPTID,
	BillingCPTID,
	ServiceProviderID,
	ServiceProviderSpecialtyID,
	PerformingProviderID,
	PerformingProviderSpecialtyID, 
	m.FiscalMonthID, 
	f.Value, 
	LockType
	FROM (
		SELECT fcv.*, fcv.ProjectionLockType AS LockType, 
			fcv.ProjectionAdjusted01 AS AdjustedValue01, fcv.ProjectionAdjusted02 AS AdjustedValue02, fcv.ProjectionAdjusted03 AS AdjustedValue03, fcv.ProjectionAdjusted04 AS AdjustedValue04, fcv.ProjectionAdjusted05 AS AdjustedValue05, 
			fcv.ProjectionAdjusted06 AS AdjustedValue06, fcv.ProjectionAdjusted07 AS AdjustedValue07, fcv.ProjectionAdjusted08 AS AdjustedValue08, fcv.ProjectionAdjusted09 AS AdjustedValue09, fcv.ProjectionAdjusted10 AS AdjustedValue10, 
			fcv.ProjectionAdjusted11 AS AdjustedValue11, fcv.ProjectionAdjusted12 AS AdjustedValue12
		FROM fp.ChargeVolume fcv) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.ServiceLineID = v.ServiceLineID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.AgeCohortID = v.AgeCohortID
	AND ov.MedicalSurgicalID = v.MedicalSurgicalID
	AND ov.ChargeCodeID = v.ChargeCodeID
	AND ov.ServiceEntityID = v.ServiceEntityID
	AND ov.MSDRGID = v.MSDRGID
	AND ov.UBRevCodeID = v.UBRevCodeID
	AND ov.PrimaryCPTID = v.PrimaryCPTID
	AND ov.BillingCPTID = v.BillingCPTID
	AND ov.ServiceProviderID = v.ServiceProviderID
	AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
	AND ov.PerformingProviderID = v.PerformingProviderID
	AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for Manager Value
	SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, 
	ServiceEntityID,
	MSDRGID,
	UBRevCodeID,
	PrimaryCPTID,
	BillingCPTID,
	ServiceProviderID,
	ServiceProviderSpecialtyID,
	PerformingProviderID,
	PerformingProviderSpecialtyID, 
	m.FiscalMonthID, 
	f.Value, 
	LockType
	FROM (
		SELECT fcv.*, fcv.ProjectionLockType AS LockType, 
			fcv.ProjectionAdjusted01 AS AdjustedValue01, fcv.ProjectionAdjusted02 AS AdjustedValue02, fcv.ProjectionAdjusted03 AS AdjustedValue03, fcv.ProjectionAdjusted04 AS AdjustedValue04, fcv.ProjectionAdjusted05 AS AdjustedValue05, 
			fcv.ProjectionAdjusted06 AS AdjustedValue06, fcv.ProjectionAdjusted07 AS AdjustedValue07, fcv.ProjectionAdjusted08 AS AdjustedValue08, fcv.ProjectionAdjusted09 AS AdjustedValue09, fcv.ProjectionAdjusted10 AS AdjustedValue10, 
			fcv.ProjectionAdjusted11 AS AdjustedValue11, fcv.ProjectionAdjusted12 AS AdjustedValue12
		FROM fp.ChargeVolume fcv) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.DepartmentID = mgrv.DepartmentID
	AND ov.ServiceLineID = mgrv.ServiceLineID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.AgeCohortID = mgrv.AgeCohortID
	AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID
	AND ov.ChargeCodeID = mgrv.ChargeCodeID
	AND ov.ServiceEntityID = v.ServiceEntityID
	AND ov.MSDRGID = v.MSDRGID
	AND ov.UBRevCodeID = v.UBRevCodeID
	AND ov.PrimaryCPTID = v.PrimaryCPTID
	AND ov.BillingCPTID = v.BillingCPTID
	AND ov.ServiceProviderID = v.ServiceProviderID
	AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
	AND ov.PerformingProviderID = v.PerformingProviderID
	AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
GO


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

-- fp.viewFactChargeVolume_Unpivoted_source
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2020-12-28  MD          JAZZ-29138  Initial
** 2    2023-05-18  MY          JAZZ-55153  Update to new structure
*************************************************************/
CREATE   VIEW [fp].[viewFactChargeVolume_Unpivoted_source]  
AS
	WITH chargevolume AS (
		SELECT 
				cv.BudgetConfigID,
				cv.EntityGroupConfigID, 
				cv.EntityID, 
				cv.DepartmentID, 
				cv.ServiceLineID, 
				cv.PatientClassID, 
				cv.AgeCohortID, 
				cv.MedicalSurgicalID, 
				cv.ChargeCodeID, 
				cv.ServiceEntityID,
				cv.MSDRGID,
				cv.UBRevCodeID,
				cv.PrimaryCPTID,
				cv.ServiceProviderID,
				cv.ServiceProviderSpecialtyID,
				cv.PerformingProviderID,
				cv.PerformingProviderSpecialtyID,
				cv.BillingCPTID,
				cv.UnitTypeID,

				SUM(cv.InitialBudget01) AS InitialBudget01, 
				SUM(cv.InitialBudget02) AS InitialBudget02, 
				SUM(cv.InitialBudget03) AS InitialBudget03, 
				SUM(cv.InitialBudget04) AS InitialBudget04, 
				SUM(cv.InitialBudget05) AS InitialBudget05, 
				SUM(cv.InitialBudget06) AS InitialBudget06, 
				SUM(cv.InitialBudget07) AS InitialBudget07, 
				SUM(cv.InitialBudget08) AS InitialBudget08,
				SUM(cv.InitialBudget09) AS InitialBudget09, 
				SUM(cv.InitialBudget10) AS InitialBudget10, 
				SUM(cv.InitialBudget11) AS InitialBudget11, 
				SUM(cv.InitialBudget12) AS InitialBudget12, 
				SUM(cv.InitialProjection01) AS InitialProjection01, 
				SUM(cv.InitialProjection02) AS InitialProjection02, 
				SUM(cv.InitialProjection03) AS InitialProjection03, 
				SUM(cv.InitialProjection04) AS InitialProjection04, 
				SUM(cv.InitialProjection05) AS InitialProjection05, 
				SUM(cv.InitialProjection06) AS InitialProjection06, 
				SUM(cv.InitialProjection07) AS InitialProjection07, 
				SUM(cv.InitialProjection08) AS InitialProjection08,
				SUM(cv.InitialProjection09) AS InitialProjection09, 
				SUM(cv.InitialProjection10) AS InitialProjection10, 
				SUM(cv.InitialProjection11) AS InitialProjection11, 
				SUM(cv.InitialProjection12) AS InitialProjection12,
				SUM(cv.TargetAdjusted01) AS TargetValue01, 
				SUM(cv.TargetAdjusted02) AS TargetValue02, 
				SUM(cv.TargetAdjusted03) AS TargetValue03, 
				SUM(cv.TargetAdjusted04) AS TargetValue04, 
				SUM(cv.TargetAdjusted05) AS TargetValue05, 
				SUM(cv.TargetAdjusted06) AS TargetValue06, 
				SUM(cv.TargetAdjusted07) AS TargetValue07, 
				SUM(cv.TargetAdjusted08) AS TargetValue08,
				SUM(cv.TargetAdjusted09) AS TargetValue09, 
				SUM(cv.TargetAdjusted10) AS TargetValue10, 
				SUM(cv.TargetAdjusted11) AS TargetValue11, 
				SUM(cv.TargetAdjusted12) AS TargetValue12,
				SUM(cv.BudgetAdjusted01) AS ManagerValue01, 
				SUM(cv.BudgetAdjusted02) AS ManagerValue02, 
				SUM(cv.BudgetAdjusted03) AS ManagerValue03, 
				SUM(cv.BudgetAdjusted04) AS ManagerValue04, 
				SUM(cv.BudgetAdjusted05) AS ManagerValue05, 
				SUM(cv.BudgetAdjusted06) AS ManagerValue06, 
				SUM(cv.BudgetAdjusted07) AS ManagerValue07, 
				SUM(cv.BudgetAdjusted08) AS ManagerValue08,
				SUM(cv.BudgetAdjusted09) AS ManagerValue09, 
				SUM(cv.BudgetAdjusted10) AS ManagerValue10, 
				SUM(cv.BudgetAdjusted11) AS ManagerValue11, 
				SUM(cv.BudgetAdjusted12) AS ManagerValue12,
				SUM(cv.ProjectionAdjusted01) AS ProjectedValue01, 
				SUM(cv.ProjectionAdjusted02) AS ProjectedValue02, 
				SUM(cv.ProjectionAdjusted03) AS ProjectedValue03, 
				SUM(cv.ProjectionAdjusted04) AS ProjectedValue04, 
				SUM(cv.ProjectionAdjusted05) AS ProjectedValue05, 
				SUM(cv.ProjectionAdjusted06) AS ProjectedValue06, 
				SUM(cv.ProjectionAdjusted07) AS ProjectedValue07, 
				SUM(cv.ProjectionAdjusted08) AS ProjectedValue08,
				SUM(cv.ProjectionAdjusted09) AS ProjectedValue09, 
				SUM(cv.ProjectionAdjusted10) AS ProjectedValue10, 
				SUM(cv.ProjectionAdjusted11) AS ProjectedValue11, 
				SUM(cv.ProjectionAdjusted12) AS ProjectedValue12
		FROM fp.ChargeVolume cv 
			INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID
			INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID
		WHERE 
			bc.IsActive = 1
			AND cv.UnitTypeID = 145
		GROUP BY 
			cv.BudgetConfigID,
			cv.EntityGroupConfigID, 
			cv.EntityID, 
			cv.DepartmentID, 
			cv.ServiceLineID, 
			cv.PatientClassID, 
			cv.AgeCohortID, 
			cv.MedicalSurgicalID, 
			cv.ChargeCodeID, 
			cv.ServiceEntityID,
			cv.MSDRGID,
			cv.UBRevCodeID,
			cv.PrimaryCPTID,
			cv.ServiceProviderID,
			cv.ServiceProviderSpecialtyID,
			cv.PerformingProviderID,
			cv.PerformingProviderSpecialtyID,
			cv.BillingCPTID,
			cv.UnitTypeID
	)
	SELECT 
		BudgetConfigID,
		EntityGroupConfigID, 
		EntityID, 
		DepartmentID, 
		ServiceLineID, 
		PatientClassID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		ChargeCodeID, 
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,		
		BillingCPTID,
		UnitTypeID,
		TimeClassID,
		FiscalMonthID,
		FiscalYearID,
		OriginalValue,
		Value,
		ManagerValue
	FROM (
		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID, 
			ov.EntityID, 
			ov.DepartmentID, 
			ov.ServiceLineID, 
			ov.PatientClassID, 
			ov.AgeCohortID, 
			ov.MedicalSurgicalID, 
			ov.ChargeCodeID, 
			ov.ServiceEntityID,
			ov.MSDRGID,
			ov.UBRevCodeID,
			ov.PrimaryCPTID,
			ov.ServiceProviderID,
			ov.ServiceProviderSpecialtyID,
			ov.PerformingProviderID,
			ov.PerformingProviderSpecialtyID,	
			ov.BillingCPTID,
			ov.UnitTypeID,			
			2 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID,
			ov.InitialValue as OriginalValue,
			v.Value,
			mgr.Value as ManagerValue
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT 
					cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12
				FROM chargevolume cv
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v
			ON 
				ov.BudgetConfigID = v.BudgetConfigID
				AND ov.EntityGroupConfigID = v.EntityGroupConfigID 
				AND ov.EntityID = v.EntityID 
				AND ov.DepartmentID = v.DepartmentID 
				AND ov.ServiceLineID = v.ServiceLineID 
				AND ov.PatientClassID = v.PatientClassID 
				AND ov.AgeCohortID = v.AgeCohortID 
				AND ov.MedicalSurgicalID = v.MedicalSurgicalID 
				AND ov.ChargeCodeID = v.ChargeCodeID 
				AND ov.ServiceEntityID = v.ServiceEntityID
				AND ov.MSDRGID = v.MSDRGID
				AND ov.UBRevCodeID = v.UBRevCodeID
				AND ov.PrimaryCPTID = v.PrimaryCPTID
				AND ov.ServiceProviderID = v.ServiceProviderID
				AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
				AND ov.PerformingProviderID = v.PerformingProviderID
				AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID  
				AND ov.BillingCPTID = v.BillingCPTID
				AND ov.UnitTypeID = v.UnitTypeID
				AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN (
			-- Unpivot for ManagerValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr
			ON 
				ov.BudgetConfigID = mgr.BudgetConfigID
				AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID 
				AND ov.EntityID = mgr.EntityID 
				AND ov.DepartmentID = mgr.DepartmentID 
				AND ov.ServiceLineID = mgr.ServiceLineID 
				AND ov.PatientClassID = mgr.PatientClassID 
				AND ov.AgeCohortID = mgr.AgeCohortID 
				AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID 
				AND ov.ChargeCodeID = mgr.ChargeCodeID 
				AND ov.ServiceEntityID = mgr.ServiceEntityID
				AND ov.MSDRGID = mgr.MSDRGID
				AND ov.UBRevCodeID = mgr.UBRevCodeID
				AND ov.PrimaryCPTID = mgr.PrimaryCPTID
				AND ov.ServiceProviderID = mgr.ServiceProviderID
				AND ov.ServiceProviderSpecialtyID = mgr.ServiceProviderSpecialtyID
				AND ov.PerformingProviderID = mgr.PerformingProviderID
				AND ov.PerformingProviderSpecialtyID = mgr.PerformingProviderSpecialtyID
				AND ov.BillingCPTID = mgr.BillingCPTID
				AND ov.UnitTypeID = mgr.UnitTypeID
				AND ov.FiscalMonthID = mgr.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID


		UNION ALL

		SELECT 
			ov.BudgetConfigID,
			ov.EntityGroupConfigID, 
			ov.EntityID, 
			ov.DepartmentID, 
			ov.ServiceLineID, 
			ov.PatientClassID, 
			ov.AgeCohortID, 
			ov.MedicalSurgicalID, 
			ov.ChargeCodeID, 
			ov.ServiceEntityID,
			ov.MSDRGID,
			ov.UBRevCodeID,
			ov.PrimaryCPTID,
			ov.ServiceProviderID,
			ov.ServiceProviderSpecialtyID,
			ov.PerformingProviderID,
			ov.PerformingProviderSpecialtyID,
			ov.BillingCPTID,
			ov.UnitTypeID,	
			12 as TimeClassID,
			ov.FiscalMonthID,
			bc.FiscalYearID - 1,
			ov.InitialValue as OriginalValue,
			v.Value,
			v.Value as ManagerValue -- Manager value is not different in CV for Projection
		FROM (
			-- Unpivot for OriginalValue
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 
				FROM chargevolume cv 
				) cv
				UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
		INNER JOIN (
			-- Unpivot for Value
			SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
					ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID,
					PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value
			FROM (
				SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, 
					cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID,
					cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID,
					cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12
				FROM chargevolume cv
				) cv
				UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f
				LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v
			ON 
				ov.BudgetConfigID = v.BudgetConfigID
				AND ov.EntityGroupConfigID = v.EntityGroupConfigID 
				AND ov.EntityID = v.EntityID 
				AND ov.DepartmentID = v.DepartmentID 
				AND ov.ServiceLineID = v.ServiceLineID 
				AND ov.PatientClassID = v.PatientClassID 
				AND ov.AgeCohortID = v.AgeCohortID 
				AND ov.MedicalSurgicalID = v.MedicalSurgicalID 
				AND ov.ChargeCodeID = v.ChargeCodeID 
				AND ov.ServiceEntityID = v.ServiceEntityID
				AND ov.MSDRGID = v.MSDRGID
				AND ov.UBRevCodeID = v.UBRevCodeID
				AND ov.PrimaryCPTID = v.PrimaryCPTID
				AND ov.ServiceProviderID = v.ServiceProviderID
				AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID
				AND ov.PerformingProviderID = v.PerformingProviderID
				AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID   
				AND ov.BillingCPTID = v.BillingCPTID
				AND ov.UnitTypeID = v.UnitTypeID
				AND ov.FiscalMonthID = v.FiscalMonthID
		INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
	) cvData
GO


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

-- fp.viewFactEncounterHistory_Unpivoted_source
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2023-02-28   BW		   JAZZ-49992  Updated for new data model, use [fp].[ServiceLineEncounter]
*************************************************************/

CREATE   VIEW [fp].[viewFactEncounterHistory_Unpivoted_source]
AS
-- Unpivot for PriorYearActual
SELECT data.ServiceLineEncounterID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.PatientClassID, data.ServiceLineID, data.ServiceLineRollupID, 
data.AgeCohortID, data.MedicalSurgicalID, data.PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, data.UnitTypeID, 
1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT fe.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, 
		hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12
        FROM [fp].[ServiceLineEncounter] fe
        INNER JOIN [fp].[ServiceLineEncounterHistory] hist ON fe.ServiceLineEncounterID = hist.ServiceLineEncounterID ) fe
        UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, 
		PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f
        LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for ActualYTD
SELECT data.ServiceLineEncounterID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.PatientClassID, data.ServiceLineID, data.ServiceLineRollupID, 
data.AgeCohortID, data.MedicalSurgicalID, data.PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, data.UnitTypeID, 
1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT fe.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, 
		hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12
        FROM [fp].[ServiceLineEncounter] fe
        INNER JOIN [fp].[ServiceLineEncounterHistory] hist ON fe.ServiceLineEncounterID = hist.ServiceLineEncounterID ) fe
        UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, 
		ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f
        LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for CurrentYearBudget
SELECT data.ServiceLineEncounterID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.PatientClassID, data.ServiceLineID, data.ServiceLineRollupID, 
data.AgeCohortID, data.MedicalSurgicalID, data.PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, data.UnitTypeID, 2 as TimeClassID, 
bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT fe.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, 
		hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12
        FROM [fp].[ServiceLineEncounter] fe
        INNER JOIN [fp].[ServiceLineEncounterHistory] hist ON fe.ServiceLineEncounterID = hist.ServiceLineEncounterID ) fe
        UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, 
		CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f
        LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudget', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactEncounter_Unpivoted_BaselineOnly
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2022-07-18   MY        JAZZ-37944  Initial
** 2    2023-02-28   BW		   JAZZ-49992  Updated for new data model, use [fp].[ServiceLineEncounter]
** 3    2023-05-22   BW		   JAZZ-55391  Just a reapply
*************************************************************/
CREATE   VIEW [fp].[viewFactEncounter_Unpivoted_BaselineOnly]
AS
SELECT 
	ov.ServiceLineEncounterID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.ServiceLineID,
	ov.ServiceLineRollupID,
	ov.PatientClassID,
	ov.AgeCohortID,
	ov.MedicalSurgicalID,
	ov.PayorID,
	ov.PayorGroupID,
	ov.MSDRGID,
	ov.CPTID,
	ov.ProviderID,
	ov.PhysicianSpecialtyID,
	ov.UnitTypeID,
	2 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID,
	ov.InitialValue as OriginalValue
FROM (
	-- Unpivot for OriginalValue
	SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
			PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, 
			InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12
		FROM [fp].[ServiceLineEncounter] cv 
	) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactEncounter_Unpivoted_source
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-12-14  MD      JAZZ-47250		Remove projection inner join on budget phase ID 3
** 2    2023-02-28  BW		JAZZ-49992		Updated for new data model, use [fp].[ServiceLineEncounter]
*************************************************************/

CREATE VIEW [fp].[viewFactEncounter_Unpivoted_source]
AS
SELECT 
	ov.ServiceLineEncounterID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.ServiceLineID,
	ov.ServiceLineRollupID,
	ov.PatientClassID,
	ov.AgeCohortID,
	ov.MedicalSurgicalID,
	ov.PayorID,
	ov.PayorGroupID,
	ov.MSDRGID,
	ov.CPTID,
	ov.ProviderID,
	ov.PhysicianSpecialtyID,
	ov.UnitTypeID,
	2 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID,
	ov.InitialValue as OriginalValue,
	v.Value,
	mgrv.Value as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.*
		FROM [fp].[ServiceLineEncounter] cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f



		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, cv.TargetLockType AS LockType, cv.TargetAdjusted01 AS AdjustedValue01, cv.TargetAdjusted02 AS AdjustedValue02, cv.TargetAdjusted03 AS AdjustedValue03, cv.TargetAdjusted04 AS AdjustedValue04, cv.TargetAdjusted05 AS AdjustedValue05, cv.TargetAdjusted06 AS AdjustedValue06, cv.TargetAdjusted07 AS AdjustedValue07, 
		cv.TargetAdjusted08 AS AdjustedValue08, cv.TargetAdjusted09 AS AdjustedValue09, cv.TargetAdjusted10 AS AdjustedValue10, cv.TargetAdjusted11 AS AdjustedValue11, cv.TargetAdjusted12 AS AdjustedValue12
		FROM [fp].[ServiceLineEncounter] cv
		) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, 
		AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.ServiceLineID = v.ServiceLineID
	AND ov.ServiceLineRollupID = v.ServiceLineRollupID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.AgeCohortID = v.AgeCohortID
	AND ov.MedicalSurgicalID = v.MedicalSurgicalID
	AND ov.PayorID = v.PayorID
	AND ov.PayorGroupID = v.PayorGroupID
	AND ov.MSDRGID = v.MSDRGID
	AND ov.CPTID = v.CPTID
	AND ov.ProviderID = v.ProviderID
	AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for Manager Value
	SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, cv.BudgetLockType AS LockType, cv.BudgetAdjusted01 AS AdjustedValue01, cv.BudgetAdjusted02 AS AdjustedValue02, cv.BudgetAdjusted03 AS AdjustedValue03, cv.BudgetAdjusted04 AS AdjustedValue04, cv.BudgetAdjusted05 AS AdjustedValue05, cv.BudgetAdjusted06 AS AdjustedValue06, cv.BudgetAdjusted07 AS AdjustedValue07, 
		cv.BudgetAdjusted08 AS AdjustedValue08, cv.BudgetAdjusted09 AS AdjustedValue09, cv.BudgetAdjusted10 AS AdjustedValue10, cv.BudgetAdjusted11 AS AdjustedValue11, cv.BudgetAdjusted12 AS AdjustedValue12
		FROM [fp].[ServiceLineEncounter] cv
		) sle
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.DepartmentID = mgrv.DepartmentID
	AND ov.ServiceLineID = mgrv.ServiceLineID
	AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.AgeCohortID = mgrv.AgeCohortID
	AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID
	AND ov.PayorID = mgrv.PayorID
	AND ov.PayorGroupID = mgrv.PayorGroupID
	AND ov.MSDRGID = mgrv.MSDRGID
	AND ov.CPTID = mgrv.CPTID
	AND ov.ProviderID = mgrv.ProviderID
	AND ov.PhysicianSpecialtyID = mgrv.PhysicianSpecialtyID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID

UNION ALL

SELECT 
	ov.ServiceLineEncounterID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.ServiceLineID,
	ov.ServiceLineRollupID,
	ov.PatientClassID,
	ov.AgeCohortID,
	ov.MedicalSurgicalID,
	ov.PayorID,
	ov.PayorGroupID,
	ov.MSDRGID,
	ov.CPTID,
	ov.ProviderID,
	ov.PhysicianSpecialtyID,
	ov.UnitTypeID,
	12 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID - 1,
	ov.InitialValue as OriginalValue,
	v.Value,
	0 as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.*
		FROM [fp].[ServiceLineEncounter] cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07,
		InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, 
	PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, cv.ProjectionLockType AS LockType, cv.ProjectionAdjusted01 AS AdjustedValue01, cv.ProjectionAdjusted02 AS AdjustedValue02, cv.ProjectionAdjusted03 AS AdjustedValue03, cv.ProjectionAdjusted04 AS AdjustedValue04, cv.ProjectionAdjusted05 AS AdjustedValue05, cv.ProjectionAdjusted06 AS AdjustedValue06, cv.ProjectionAdjusted07 AS AdjustedValue07, 
		cv.ProjectionAdjusted08 AS AdjustedValue08, cv.ProjectionAdjusted09 AS AdjustedValue09, cv.ProjectionAdjusted10 AS AdjustedValue10, cv.ProjectionAdjusted11 AS AdjustedValue11, cv.ProjectionAdjusted12 AS AdjustedValue12
		FROM [fp].[ServiceLineEncounter] cv
		) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, 
		AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.ServiceLineID = v.ServiceLineID
	AND ov.ServiceLineRollupID = v.ServiceLineRollupID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.AgeCohortID = v.AgeCohortID
	AND ov.MedicalSurgicalID = v.MedicalSurgicalID
	AND ov.PayorID = v.PayorID
	AND ov.PayorGroupID = v.PayorGroupID
	AND ov.MSDRGID = v.MSDRGID
	AND ov.CPTID = v.CPTID
	AND ov.ProviderID = v.ProviderID
	AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactGeneralLedgerBudget_HistoryViewer
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	7-20-2023  MY      JAZZ-54785		Update to new structure
*************************************************************/
CREATE   VIEW fp.viewFactGeneralLedgerBudget_HistoryViewer
AS
SELECT
	ov.GeneralLedgerID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.APEModelSectionID, 
	ov.VariabilityID, 
	34 AS UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, 
		InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12
		FROM fp.GeneralLedger gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, 
		TargetLockType AS LockType, 
		TargetAdjusted01 AS AdjustedValue01, 
		TargetAdjusted02 AS AdjustedValue02, 
		TargetAdjusted03 AS AdjustedValue03, 
		TargetAdjusted04 AS AdjustedValue04, 
		TargetAdjusted05 AS AdjustedValue05, 
		TargetAdjusted06 AS AdjustedValue06, 
		TargetAdjusted07 AS AdjustedValue07, 
		TargetAdjusted08 AS AdjustedValue08, 
		TargetAdjusted09 AS AdjustedValue09, 
		TargetAdjusted10 AS AdjustedValue10, 
		TargetAdjusted11 AS AdjustedValue11, 
		TargetAdjusted12 AS AdjustedValue12
		FROM fp.GeneralLedger gl) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.VariabilityID = v.VariabilityID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, 
		BudgetLockType AS LockType, 
		BudgetAdjusted01 AS AdjustedValue01, 
		BudgetAdjusted02 AS AdjustedValue02, 
		BudgetAdjusted03 AS AdjustedValue03, 
		BudgetAdjusted04 AS AdjustedValue04, 
		BudgetAdjusted05 AS AdjustedValue05, 
		BudgetAdjusted06 AS AdjustedValue06, 
		BudgetAdjusted07 AS AdjustedValue07, 
		BudgetAdjusted08 AS AdjustedValue08, 
		BudgetAdjusted09 AS AdjustedValue09, 
		BudgetAdjusted10 AS AdjustedValue10, 
		BudgetAdjusted11 AS AdjustedValue11, 
		BudgetAdjusted12 AS AdjustedValue12
		FROM fp.GeneralLedger gl) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.VariabilityID = mgrv.VariabilityID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactGeneralLedgerHistory_Unpivoted
CREATE VIEW fp.viewFactGeneralLedgerHistory_Unpivoted 
AS
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI          Description  
 ** 1   2021-10-26   MD      JAZZ-JAZZ-28803  Adding union all for data transfer table
*************************************************************/ 
SELECT
	rgl.GeneralLedgerID,
	rgl.BudgetConfigID, 
	rgl.EntityGroupConfigID, 
	rgl.EntityID,
	rgl.DepartmentID,
	rgl.AccountID,
	rgl.FinancialReportingID,
	rgl.APEModelSectionID,
	rgl.VariabilityID,
	rgl.UnitTypeID,
	rgl.TimeClassID,
	rgl.FiscalYearID,
	rgl.FiscalMonthID, 
	rgl.Value
FROM fp.FactReportGeneralLedgerHistory rgl
WHERE rgl.UnitTypeID = 34

UNION ALL
  
-- Prior Year Actual and Current Year Budget - data transfer  
SELECT
	0 as GeneralLedgerID,
	dth.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dth.EntityID,  
	dth.DepartmentID,  
	dth.AccountID,  
	dth.FinancialReportingID,  
	2 as APEModelSectionID,
	dth.VariabilityID, 
	dth.UnitTypeID, 
	dth.TimeClassID, 
	dth.FiscalYearID,  
	dth.FiscalMonthID,
	dth.Value
FROM [fp].[FactReportGeneralLedgerHistoryDataTransfer] dth
WHERE dth.TimeClassID in(1, 2)
GO


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

-- fp.viewFactGeneralLedgerHistory_Unpivoted_archive
CREATE VIEW fp.viewFactGeneralLedgerHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedgerHistory_archive WHERE UnitTypeID = 34
GO


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

-- fp.viewFactGeneralLedgerHistory_Unpivoted_source
CREATE VIEW [fp].[viewFactGeneralLedgerHistory_Unpivoted_source]
AS
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2023-08-11   BK        JAZZ-58752  Update for new gl data structure
	*************************************************************/

SELECT
 gl.GeneralLedgerID
	,gl.BudgetConfigID
	,gl.EntityGroupConfigID
	,gl.EntityID
	,gl.DepartmentID
	,gl.AccountID
	,gl.FinancialReportingID
	,gl.APEModelSectionID
	,gl.VariabilityID
	,34 as UnitTypeID
	,TimeClassID
	,bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID
	,m.FiscalMonthID
	,hist.Value
FROM (
 SELECT hist.GeneralLedgerID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.GeneralLedgerHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
			(VALUES 
		(1, ActualYTDValue01),
		(2, ActualYTDValue02),
		(3, ActualYTDValue03),
		(4, ActualYTDValue04),
		(5, ActualYTDValue05),
		(6, ActualYTDValue06),
		(7, ActualYTDValue07),
		(8, ActualYTDValue08),
		(9, ActualYTDValue09),
		(10,ActualYTDValue10),
		(11,ActualYTDValue11),
		(12,ActualYTDValue12))	X (FiscalMonth,Value)
UNION
SELECT hist.GeneralLedgerID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.GeneralLedgerHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
			(VALUES 
		(1, CurrentYearBudget01),
		(2, CurrentYearBudget02),
		(3, CurrentYearBudget03),
		(4, CurrentYearBudget04),
		(5, CurrentYearBudget05),
		(6, CurrentYearBudget06),
		(7, CurrentYearBudget07),
		(8, CurrentYearBudget08),
		(9, CurrentYearBudget09),
		(10,CurrentYearBudget10),
		(11,CurrentYearBudget11),
		(12,CurrentYearBudget12))	X (FiscalMonth,Value)
UNION
SELECT hist.GeneralLedgerID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear 
 FROM fp.GeneralLedgerHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
			(VALUES 
		(1, PriorYearActualValue01),
		(2, PriorYearActualValue02),
		(3, PriorYearActualValue03),
		(4, PriorYearActualValue04),
		(5, PriorYearActualValue05),
		(6, PriorYearActualValue06),
		(7, PriorYearActualValue07),
		(8, PriorYearActualValue08),
		(9, PriorYearActualValue09),
		(10,PriorYearActualValue10),
		(11,PriorYearActualValue11),
		(12,PriorYearActualValue12))	X (FiscalMonth,Value) ) hist
INNER JOIN fp.GeneralLedger gl (READUNCOMMITTED) ON gl.GeneralLedgerID = hist.GeneralLedgerID
    INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth
    INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactGeneralLedgerProjection_HistoryViewer
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	7-20-2023  MY      JAZZ-54785		Update to new structure
*************************************************************/
CREATE   VIEW fp.viewFactGeneralLedgerProjection_HistoryViewer
AS
SELECT
	ov.GeneralLedgerID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.APEModelSectionID, 
	ov.VariabilityID, 
	34 AS UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	v.Value AS ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, 
		InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12
		FROM fp.GeneralLedger gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, 
		ProjectionLockType AS LockType, 
		ProjectionAdjusted01 AS AdjustedValue01, 
		ProjectionAdjusted02 AS AdjustedValue02, 
		ProjectionAdjusted03 AS AdjustedValue03, 
		ProjectionAdjusted04 AS AdjustedValue04, 
		ProjectionAdjusted05 AS AdjustedValue05, 
		ProjectionAdjusted06 AS AdjustedValue06, 
		ProjectionAdjusted07 AS AdjustedValue07, 
		ProjectionAdjusted08 AS AdjustedValue08, 
		ProjectionAdjusted09 AS AdjustedValue09, 
		ProjectionAdjusted10 AS AdjustedValue10, 
		ProjectionAdjusted11 AS AdjustedValue11, 
		ProjectionAdjusted12 AS AdjustedValue12
		FROM fp.GeneralLedger gl) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.VariabilityID = v.VariabilityID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactGeneralLedgerSnapshot_Unpivoted
CREATE   VIEW [fp].[viewFactGeneralLedgerSnapshot_Unpivoted] 
AS 
/*************************************************************
** Change History
**************************************************************
** CID    Date        Author      WI			Description
** 1      2024-11-04  MY          JAZZ-77737	Initial
***************************************************************/

------------------------------------
-- This is a copy of fp.viewReportGeneralLedger essentially except cleaned up and adopted for Snapshots.
-- Note: Excluded here is the Data Transfer stuff,
------------------------------------

SELECT 
	rgl.GeneralLedgerID,
	rgl.SnapshotID,
	rgl.BudgetConfigID, 
	rgl.EntityGroupConfigID, 
	rgl.EntityID,
	rgl.DepartmentID,
	rgl.AccountID,
	rgl.FinancialReportingID,
	rgl.APEModelSectionID,
	rgl.VariabilityID,
	rgl.UnitTypeID,
	rgl.TimeClassID,
	rgl.FiscalYearID,
	rgl.FiscalMonthID, 
	rgl.LockType,
	rgl.OriginalValue,
	rgl.Value,
	rgl.ManagerValue,
	rgl.Rate
FROM fp.FactReportGeneralLedgerSnapshot rgl
WHERE rgl.UnitTypeID = 34

UNION ALL

-- UK to US Data transfer queries start here --

-- Manager Projection - data transfer
SELECT  
	0 as GeneralLedgerID,
	dt.SnapshotID,
	bc.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	12 as TimeClassID, 
	bc.FiscalYearID-1 as FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt  
	INNER JOIN fp.BudgetConfig bc on dt.BudgetConfigID = bc.BudgetConfigID  
WHERE dt.TimeClassID = 12  
  
UNION ALL  
  
-- Initial Budget - data transfer  
SELECT  
	0 as GeneralLedgerID,
	dt.SnapshotID,
	dt.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	21 as TimeClassID, 
	dt.FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt 
WHERE dt.TimeClassID = 2  
  
UNION ALL 
  
-- Manager Budget - data transfer  
SELECT  
	0 as GeneralLedgerID,
	dt.SnapshotID,
	dt.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	2 as TimeClassID, 
	dt.FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt 
WHERE dt.TimeClassID = 2  
  
UNION ALL 
  
-- Baseline Budget - data transfer  
SELECT  
	0 as GeneralLedgerID,
	dt.SnapshotID,
	dt.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	22 as TimeClassID, 
	dt.FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt  
WHERE dt.TimeClassID = 2
GO


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

-- fp.viewFactGeneralLedger_Snapshot
CREATE   VIEW [fp].[viewFactGeneralLedger_Snapshot]
AS
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2024-10-22   MY        JAZZ-77735  Initial Creation
	*************************************************************/

	SELECT 
	SnapshotID,
	GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	34 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	gl.TargetLockType AS LockType,
	OriginalValue, Value, ManagerValue, Rate			
	FROM fp.GeneralLedgerSnapshot gl
	CROSS APPLY (		
		VALUES 
		(1,InitialBudget01,TargetAdjusted01,TargetPercentAdjustmentFactor01,BudgetAdjusted01),
		(2,InitialBudget02,TargetAdjusted02,TargetPercentAdjustmentFactor02,BudgetAdjusted02),
		(3,InitialBudget03,TargetAdjusted03,TargetPercentAdjustmentFactor03,BudgetAdjusted03),
		(4,InitialBudget04,TargetAdjusted04,TargetPercentAdjustmentFactor04,BudgetAdjusted04),
		(5,InitialBudget05,TargetAdjusted05,TargetPercentAdjustmentFactor05,BudgetAdjusted05),
		(6,InitialBudget06,TargetAdjusted06,TargetPercentAdjustmentFactor06,BudgetAdjusted06),
		(7,InitialBudget07,TargetAdjusted07,TargetPercentAdjustmentFactor07,BudgetAdjusted07),
		(8,InitialBudget08,TargetAdjusted08,TargetPercentAdjustmentFactor08,BudgetAdjusted08),
		(9,InitialBudget09,TargetAdjusted09,TargetPercentAdjustmentFactor09,BudgetAdjusted09),
		(10,InitialBudget10,TargetAdjusted10,TargetPercentAdjustmentFactor10,BudgetAdjusted10),
		(11,InitialBudget11,TargetAdjusted11,TargetPercentAdjustmentFactor11,BudgetAdjusted11),
		(12,InitialBudget12,TargetAdjusted12,TargetPercentAdjustmentFactor12,BudgetAdjusted12)) glx (FiscalMonth, OriginalValue,Value, Rate, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID

UNION ALL
	SELECT 
	SnapshotID,
	GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	33 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	gl.TargetLockType AS LockType,
	OriginalValue, Value, ManagerValue, Rate			
	FROM fp.GeneralLedgerSnapshot  gl
	CROSS APPLY (		
		VALUES 
		(1, InitialBudgetDollarsPerUOS01,TargetDollarsPerUOSAdjusted01,BudgetDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01),
		(2, InitialBudgetDollarsPerUOS02,TargetDollarsPerUOSAdjusted02,BudgetDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02),
		(3, InitialBudgetDollarsPerUOS03,TargetDollarsPerUOSAdjusted03,BudgetDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03),
		(4, InitialBudgetDollarsPerUOS04,TargetDollarsPerUOSAdjusted04,BudgetDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04),
		(5, InitialBudgetDollarsPerUOS05,TargetDollarsPerUOSAdjusted05,BudgetDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05),
		(6, InitialBudgetDollarsPerUOS06,TargetDollarsPerUOSAdjusted06,BudgetDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06),
		(7, InitialBudgetDollarsPerUOS07,TargetDollarsPerUOSAdjusted07,BudgetDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07),
		(8, InitialBudgetDollarsPerUOS08,TargetDollarsPerUOSAdjusted08,BudgetDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08),
		(9, InitialBudgetDollarsPerUOS09,TargetDollarsPerUOSAdjusted09,BudgetDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09),
		(10,InitialBudgetDollarsPerUOS10,TargetDollarsPerUOSAdjusted10,BudgetDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10),
		(11,InitialBudgetDollarsPerUOS11,TargetDollarsPerUOSAdjusted11,BudgetDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11),
		(12,InitialBudgetDollarsPerUOS12,TargetDollarsPerUOSAdjusted12,BudgetDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue, Value, ManagerValue, Rate) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
	 WHERE gl.VariabilityID = 2

UNION ALL
	SELECT 	
	SnapshotID,
	GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	34 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID-1, 
	m.FiscalMonthID,
	gl.ProjectionLockType AS LockType,
	OriginalValue, Value, Value as ManagerValue, Rate			
	FROM fp.GeneralLedgerSnapshot  gl
	CROSS APPLY (		
		VALUES 
		(1,InitialProjection01,ProjectionAdjusted01,ProjectionPercentAdjustmentFactor01),
		(2,InitialProjection02,ProjectionAdjusted02,ProjectionPercentAdjustmentFactor02),
		(3,InitialProjection03,ProjectionAdjusted03,ProjectionPercentAdjustmentFactor03),
		(4,InitialProjection04,ProjectionAdjusted04,ProjectionPercentAdjustmentFactor04),
		(5,InitialProjection05,ProjectionAdjusted05,ProjectionPercentAdjustmentFactor05),
		(6,InitialProjection06,ProjectionAdjusted06,ProjectionPercentAdjustmentFactor06),
		(7,InitialProjection07,ProjectionAdjusted07,ProjectionPercentAdjustmentFactor07),
		(8,InitialProjection08,ProjectionAdjusted08,ProjectionPercentAdjustmentFactor08),
		(9,InitialProjection09,ProjectionAdjusted09,ProjectionPercentAdjustmentFactor09),
		(10,InitialProjection10,ProjectionAdjusted10,ProjectionPercentAdjustmentFactor10),
		(11,InitialProjection11,ProjectionAdjusted11,ProjectionPercentAdjustmentFactor11),
		(12,InitialProjection12,ProjectionAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) 
	
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
UNION ALL
	SELECT 
	SnapshotID,
	GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	33 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID-1, 
	m.FiscalMonthID,
	gl.ProjectionLockType AS LockType,
	OriginalValue, Value, Value as ManagerValue, Rate			
	FROM fp.GeneralLedgerSnapshot  gl
	CROSS APPLY (		
		VALUES 
		(1, InitialProjectionDollarsPerUOS01,ProjectionDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01),
		(2, InitialProjectionDollarsPerUOS02,ProjectionDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02),
		(3, InitialProjectionDollarsPerUOS03,ProjectionDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03),
		(4, InitialProjectionDollarsPerUOS04,ProjectionDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04),
		(5, InitialProjectionDollarsPerUOS05,ProjectionDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05),
		(6, InitialProjectionDollarsPerUOS06,ProjectionDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06),
		(7, InitialProjectionDollarsPerUOS07,ProjectionDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07),
		(8, InitialProjectionDollarsPerUOS08,ProjectionDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08),
		(9, InitialProjectionDollarsPerUOS09,ProjectionDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09),
		(10,InitialProjectionDollarsPerUOS10,ProjectionDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10),
		(11,InitialProjectionDollarsPerUOS11,ProjectionDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11),
		(12,InitialProjectionDollarsPerUOS12,ProjectionDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) 
	
 LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
	 WHERE gl.VariabilityID = 2
GO


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

-- fp.viewFactGeneralLedger_Unpivoted
CREATE VIEW [fp].[viewFactGeneralLedger_Unpivoted] 
AS 
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI          Description  
 ** 1   2021-10-26   MD      JAZZ-JAZZ-28803  Adding union all for data transfer table
*************************************************************/

SELECT 
	rgl.GeneralLedgerID,
	rgl.BudgetConfigID, 
	rgl.EntityGroupConfigID, 
	rgl.EntityID,
	rgl.DepartmentID,
	rgl.AccountID,
	rgl.FinancialReportingID,
	rgl.APEModelSectionID,
	rgl.VariabilityID,
	rgl.UnitTypeID,
	rgl.TimeClassID,
	rgl.FiscalYearID,
	rgl.FiscalMonthID, 
	rgl.LockType,
	rgl.OriginalValue,
	rgl.Value,
	rgl.ManagerValue,
	rgl.Rate
FROM fp.FactReportGeneralLedger rgl
WHERE rgl.UnitTypeID = 34

UNION ALL

-- Data transfer queries start here --

-- Manager Projection - data transfer
SELECT  
	0 as GeneralLedgerID,
	bc.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	12 as TimeClassID, 
	bc.FiscalYearID-1 as FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransfer] dt  
INNER JOIN fp.BudgetConfig bc on dt.BudgetConfigID = bc.BudgetConfigID  
WHERE dt.TimeClassID=12  
  
UNION ALL  
  
-- Initial Budget - data transfer  
SELECT  
	0 as GeneralLedgerID,
	dt.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	21 as TimeClassID, 
	dt.FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransfer] dt 
WHERE dt.TimeClassID=2  
  
UNION ALL 
  
-- Manager Budget - data transfer  
SELECT  
	0 as GeneralLedgerID,
	dt.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	2 as TimeClassID, 
	dt.FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransfer] dt 
WHERE dt.TimeClassID=2  
  
UNION ALL 
  
-- Baseline Budget - data transfer  
SELECT  
	0 as GeneralLedgerID,
	dt.BudgetConfigID, 
	0 as EntityGroupConfigID,
	dt.EntityID,  
	dt.DepartmentID,  
	dt.AccountID,  
	dt.FinancialReportingID,  
	2 as APEModelSectionID,
	dt.VariabilityID, 
	dt.UnitTypeID, 
	22 as TimeClassID, 
	dt.FiscalYearID,  
	dt.FiscalMonthID,
	0 as LockType,
	dt.OriginalValue,
	dt.Value,
	dt.ManagerValue,
	dt.Rate 
FROM [fp].[FactReportGeneralLedgerDataTransfer] dt  
WHERE dt.TimeClassID=2
GO


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

-- fp.viewFactGeneralLedger_Unpivoted_archive
CREATE VIEW fp.viewFactGeneralLedger_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedger_archive WHERE UnitTypeID = 34
GO


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

-- fp.viewFactGeneralLedger_Unpivoted_source
CREATE VIEW [fp].[viewFactGeneralLedger_Unpivoted_source]
AS
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2023-08-11   BK        JAZZ-58752  Update for new gl data structure
	*************************************************************/

	SELECT GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	34 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	gl.TargetLockType AS LockType,
	OriginalValue, Value, ManagerValue, Rate			
	FROM fp.GeneralLedger  gl
	CROSS APPLY (		
		VALUES 
		(1,InitialBudget01,TargetAdjusted01,TargetPercentAdjustmentFactor01,BudgetAdjusted01),
		(2,InitialBudget02,TargetAdjusted02,TargetPercentAdjustmentFactor02,BudgetAdjusted02),
		(3,InitialBudget03,TargetAdjusted03,TargetPercentAdjustmentFactor03,BudgetAdjusted03),
		(4,InitialBudget04,TargetAdjusted04,TargetPercentAdjustmentFactor04,BudgetAdjusted04),
		(5,InitialBudget05,TargetAdjusted05,TargetPercentAdjustmentFactor05,BudgetAdjusted05),
		(6,InitialBudget06,TargetAdjusted06,TargetPercentAdjustmentFactor06,BudgetAdjusted06),
		(7,InitialBudget07,TargetAdjusted07,TargetPercentAdjustmentFactor07,BudgetAdjusted07),
		(8,InitialBudget08,TargetAdjusted08,TargetPercentAdjustmentFactor08,BudgetAdjusted08),
		(9,InitialBudget09,TargetAdjusted09,TargetPercentAdjustmentFactor09,BudgetAdjusted09),
		(10,InitialBudget10,TargetAdjusted10,TargetPercentAdjustmentFactor10,BudgetAdjusted10),
		(11,InitialBudget11,TargetAdjusted11,TargetPercentAdjustmentFactor11,BudgetAdjusted11),
		(12,InitialBudget12,TargetAdjusted12,TargetPercentAdjustmentFactor12,BudgetAdjusted12)) glx (FiscalMonth, OriginalValue,Value, Rate, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID

UNION ALL
	SELECT GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	33 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	gl.TargetLockType AS LockType,
	OriginalValue, Value, ManagerValue, Rate			
	FROM fp.GeneralLedger  gl
	CROSS APPLY (		
		VALUES 
		(1, InitialBudgetDollarsPerUOS01,TargetDollarsPerUOSAdjusted01,BudgetDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01),
		(2, InitialBudgetDollarsPerUOS02,TargetDollarsPerUOSAdjusted02,BudgetDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02),
		(3, InitialBudgetDollarsPerUOS03,TargetDollarsPerUOSAdjusted03,BudgetDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03),
		(4, InitialBudgetDollarsPerUOS04,TargetDollarsPerUOSAdjusted04,BudgetDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04),
		(5, InitialBudgetDollarsPerUOS05,TargetDollarsPerUOSAdjusted05,BudgetDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05),
		(6, InitialBudgetDollarsPerUOS06,TargetDollarsPerUOSAdjusted06,BudgetDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06),
		(7, InitialBudgetDollarsPerUOS07,TargetDollarsPerUOSAdjusted07,BudgetDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07),
		(8, InitialBudgetDollarsPerUOS08,TargetDollarsPerUOSAdjusted08,BudgetDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08),
		(9, InitialBudgetDollarsPerUOS09,TargetDollarsPerUOSAdjusted09,BudgetDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09),
		(10,InitialBudgetDollarsPerUOS10,TargetDollarsPerUOSAdjusted10,BudgetDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10),
		(11,InitialBudgetDollarsPerUOS11,TargetDollarsPerUOSAdjusted11,BudgetDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11),
		(12,InitialBudgetDollarsPerUOS12,TargetDollarsPerUOSAdjusted12,BudgetDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue, Value, ManagerValue, Rate) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
	 WHERE gl.VariabilityID = 2

UNION ALL
	SELECT GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	34 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID-1, 
	m.FiscalMonthID,
	gl.ProjectionLockType AS LockType,
	OriginalValue, Value, Value as ManagerValue, Rate			
	FROM fp.GeneralLedger  gl
	CROSS APPLY (		
		VALUES 
		(1,InitialProjection01,ProjectionAdjusted01,ProjectionPercentAdjustmentFactor01),
		(2,InitialProjection02,ProjectionAdjusted02,ProjectionPercentAdjustmentFactor02),
		(3,InitialProjection03,ProjectionAdjusted03,ProjectionPercentAdjustmentFactor03),
		(4,InitialProjection04,ProjectionAdjusted04,ProjectionPercentAdjustmentFactor04),
		(5,InitialProjection05,ProjectionAdjusted05,ProjectionPercentAdjustmentFactor05),
		(6,InitialProjection06,ProjectionAdjusted06,ProjectionPercentAdjustmentFactor06),
		(7,InitialProjection07,ProjectionAdjusted07,ProjectionPercentAdjustmentFactor07),
		(8,InitialProjection08,ProjectionAdjusted08,ProjectionPercentAdjustmentFactor08),
		(9,InitialProjection09,ProjectionAdjusted09,ProjectionPercentAdjustmentFactor09),
		(10,InitialProjection10,ProjectionAdjusted10,ProjectionPercentAdjustmentFactor10),
		(11,InitialProjection11,ProjectionAdjusted11,ProjectionPercentAdjustmentFactor11),
		(12,InitialProjection12,ProjectionAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) 
	
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
UNION ALL
	SELECT GeneralLedgerID,
	gl.BudgetConfigID, 
	gl.EntityGroupConfigID, 
	gl.EntityID, 
	gl.DepartmentID, 
	gl.AccountID, 
	gl.FinancialReportingID, 
	gl.APEModelSectionID, 
	gl.VariabilityID, 
	33 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID-1, 
	m.FiscalMonthID,
	gl.ProjectionLockType AS LockType,
	OriginalValue, Value, Value as ManagerValue, Rate			
	FROM fp.GeneralLedger  gl
	CROSS APPLY (		
		VALUES 
		(1, InitialProjectionDollarsPerUOS01,ProjectionDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01),
		(2, InitialProjectionDollarsPerUOS02,ProjectionDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02),
		(3, InitialProjectionDollarsPerUOS03,ProjectionDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03),
		(4, InitialProjectionDollarsPerUOS04,ProjectionDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04),
		(5, InitialProjectionDollarsPerUOS05,ProjectionDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05),
		(6, InitialProjectionDollarsPerUOS06,ProjectionDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06),
		(7, InitialProjectionDollarsPerUOS07,ProjectionDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07),
		(8, InitialProjectionDollarsPerUOS08,ProjectionDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08),
		(9, InitialProjectionDollarsPerUOS09,ProjectionDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09),
		(10,InitialProjectionDollarsPerUOS10,ProjectionDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10),
		(11,InitialProjectionDollarsPerUOS11,ProjectionDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11),
		(12,InitialProjectionDollarsPerUOS12,ProjectionDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) 
	
 LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
	 WHERE gl.VariabilityID = 2
GO


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

-- fp.viewFactReimbursementBudget_HistoryViewer
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-16-50  MY      JAZZ-32944		Initial
*************************************************************/
CREATE VIEW fp.viewFactReimbursementBudget_HistoryViewer
AS
	SELECT
		ov.ReimbursementChargesID AS ReimbursementID, 
		ov.BudgetConfigID, 
		ov.EntityGroupConfigID, 
		ov.EntityID, 
		ov.PatientClassID, 
		ov.ServiceLineID, 
		ov.ServiceLineRollupID, 
		ov.MedicalSurgicalID, 
		ov.PayorID,
		ov.PayorGroupID, 
		ov.MSDRGID, 
		ov.PrimaryCPTID, 
		ov.UBRevCodeID, 
		6 AS SubsectionID,
		34 as UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		ov.FiscalMonthID,
		ov.InitialValue AS OriginalValue, 
		mgrv.ManagerValue
	FROM (
		-- Unpivot for OriginalValue
		SELECT ReimbursementChargesID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.InitialValue
		FROM (
			SELECT gl.*
			FROM [fp].[FactReimbursementCharges] gl ) gl
			UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, 
													   InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudgetNetReimbursement', 'Month')) ov
	INNER JOIN (
		-- Unpivot for ManagerValue
		SELECT ReimbursementChargesID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.NetReimbursementValue AS ManagerValue
		FROM (
			SELECT gl.*, bdgt.AdjustedNetReimbursementValue01, bdgt.AdjustedNetReimbursementValue02, bdgt.AdjustedNetReimbursementValue03, bdgt.AdjustedNetReimbursementValue04, bdgt.AdjustedNetReimbursementValue05, bdgt.AdjustedNetReimbursementValue06, 
						 bdgt.AdjustedNetReimbursementValue07, bdgt.AdjustedNetReimbursementValue08, bdgt.AdjustedNetReimbursementValue09, bdgt.AdjustedNetReimbursementValue10, bdgt.AdjustedNetReimbursementValue11, bdgt.AdjustedNetReimbursementValue12
			FROM [fp].[FactReimbursementCharges] gl 
			INNER JOIN [fp].[FactReimbursementChargesBudget] bdgt ON gl.ReimbursementChargesID = bdgt.ReimbursementChargesID 
			WHERE bdgt.BudgetPhaseID = 3
			) gl
			UNPIVOT ( NetReimbursementValue FOR FiscalMonth IN (AdjustedNetReimbursementValue01, AdjustedNetReimbursementValue02, AdjustedNetReimbursementValue03, AdjustedNetReimbursementValue04, AdjustedNetReimbursementValue05, AdjustedNetReimbursementValue06, 
																AdjustedNetReimbursementValue07, AdjustedNetReimbursementValue08, AdjustedNetReimbursementValue09, AdjustedNetReimbursementValue10, AdjustedNetReimbursementValue11, AdjustedNetReimbursementValue12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedNetReimbursementValue', 'Month')) mgrv
		ON ov.EntityID = mgrv.EntityID
		AND ov.PatientClassID = mgrv.PatientClassID
		AND ov.BudgetConfigID = mgrv.BudgetConfigID
		AND ov.ServiceLineID = mgrv.ServiceLineID
		AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID
		AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID
		AND ov.PayorID = mgrv.PayorID
		AND ov.PayorGroupID = mgrv.PayorGroupID
		AND ov.MSDRGID = mgrv.MSDRGID
		AND ov.PrimaryCPTID = mgrv.PrimaryCPTID
		AND ov.UBRevCodeID = mgrv.UBRevCodeID
		AND ov.UnitTypeID = mgrv.UnitTypeID
		AND ov.FiscalMonthID = mgrv.FiscalMonthID
	INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
	UNION ALL
	SELECT
		ov.ReimbursementEncounterID AS ReimbursementID, 
		ov.BudgetConfigID, 
		ov.EntityGroupConfigID, 
		ov.EntityID, 
		ov.PatientClassID, 
		ov.ServiceLineID, 
		ov.ServiceLineRollupID, 
		ov.MedicalSurgicalID, 
		ov.PayorID,
		ov.PayorGroupID, 
		ov.MSDRGID, 
		ov.PrimaryCPTID, 
		ov.UBRevCodeID, 
		5 AS SubsectionID,
		34 as UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		ov.FiscalMonthID,
		ov.InitialValue AS OriginalValue, 
		mgrv.ManagerValue
	FROM (
		-- Unpivot for OriginalValue
		SELECT ReimbursementEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID AS PrimaryCPTID, 0 AS UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.InitialValue
		FROM (
			SELECT gl.*
			FROM [fp].[FactReimbursementEncounter] gl ) gl
			UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, 
													   InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudgetNetReimbursement', 'Month')) ov
	INNER JOIN (
		-- Unpivot for ManagerValue
		SELECT ReimbursementEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID AS PrimaryCPTID, 0 AS UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.NetReimbursementValue AS ManagerValue
		FROM (
			SELECT gl.*, bdgt.AdjustedNetReimbursementValue01, bdgt.AdjustedNetReimbursementValue02, bdgt.AdjustedNetReimbursementValue03, bdgt.AdjustedNetReimbursementValue04, bdgt.AdjustedNetReimbursementValue05, bdgt.AdjustedNetReimbursementValue06, 
						 bdgt.AdjustedNetReimbursementValue07, bdgt.AdjustedNetReimbursementValue08, bdgt.AdjustedNetReimbursementValue09, bdgt.AdjustedNetReimbursementValue10, bdgt.AdjustedNetReimbursementValue11, bdgt.AdjustedNetReimbursementValue12
			FROM [fp].[FactReimbursementEncounter] gl 
			INNER JOIN [fp].[FactReimbursementEncounterBudget] bdgt ON gl.ReimbursementEncounterID = bdgt.ReimbursementEncounterID 
			WHERE bdgt.BudgetPhaseID = 3
			) gl
			UNPIVOT ( NetReimbursementValue FOR FiscalMonth IN (AdjustedNetReimbursementValue01, AdjustedNetReimbursementValue02, AdjustedNetReimbursementValue03, AdjustedNetReimbursementValue04, AdjustedNetReimbursementValue05, AdjustedNetReimbursementValue06, 
																AdjustedNetReimbursementValue07, AdjustedNetReimbursementValue08, AdjustedNetReimbursementValue09, AdjustedNetReimbursementValue10, AdjustedNetReimbursementValue11, AdjustedNetReimbursementValue12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedNetReimbursementValue', 'Month')) mgrv
		ON ov.EntityID = mgrv.EntityID
		AND ov.PatientClassID = mgrv.PatientClassID
		AND ov.BudgetConfigID = mgrv.BudgetConfigID
		AND ov.ServiceLineID = mgrv.ServiceLineID
		AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID
		AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID
		AND ov.PayorID = mgrv.PayorID
		AND ov.PayorGroupID = mgrv.PayorGroupID
		AND ov.MSDRGID = mgrv.MSDRGID
		AND ov.PrimaryCPTID = mgrv.PrimaryCPTID
		AND ov.UBRevCodeID = mgrv.UBRevCodeID
		AND ov.UnitTypeID = mgrv.UnitTypeID
		AND ov.FiscalMonthID = mgrv.FiscalMonthID
	INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactReimbursementBudget_repo
/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1    2023-08-31  MD      JAZZ-59398		Remove filter to only pull budget
	*******************************************************/
CREATE   VIEW [fp].[viewFactReimbursementBudget_repo]
AS
	SELECT
		budg.RowID,
		budg.ReimbursementChargesID AS ReimbursementID,
		budg.BudgetPhaseID,
		frc.BudgetConfigID,
		frc.EntityID,
		frc.PatientClassID,
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.PayorID,
		frc.PayorGroupID,
		frc.MedicalSurgicalID,
		frc.MSDRGID,
		frc.PrimaryCPTID AS CPTID,
		frc.UBRevCodeID,
		budg.LockFlag,
		budg.LockType,
		CAST(2 AS TINYINT) AS TimeClassID,
		6 AS SubsectionID, -- Charges
	
		budg.AdjustedNetAsPercentOfCharge01 AS RateAdjustedValue01,
		budg.AdjustedNetAsPercentOfCharge02 AS RateAdjustedValue02,
		budg.AdjustedNetAsPercentOfCharge03 AS RateAdjustedValue03,
		budg.AdjustedNetAsPercentOfCharge04 AS RateAdjustedValue04,
		budg.AdjustedNetAsPercentOfCharge05 AS RateAdjustedValue05,
		budg.AdjustedNetAsPercentOfCharge06 AS RateAdjustedValue06,
		budg.AdjustedNetAsPercentOfCharge07 AS RateAdjustedValue07,
		budg.AdjustedNetAsPercentOfCharge08 AS RateAdjustedValue08,
		budg.AdjustedNetAsPercentOfCharge09 AS RateAdjustedValue09,
		budg.AdjustedNetAsPercentOfCharge10 AS RateAdjustedValue10,
		budg.AdjustedNetAsPercentOfCharge11 AS RateAdjustedValue11,
		budg.AdjustedNetAsPercentOfCharge12 AS RateAdjustedValue12,
		
		budg.AdjustedChargeDollars01 AS VolumeAdjustedValue01,
		budg.AdjustedChargeDollars02 AS VolumeAdjustedValue02,
		budg.AdjustedChargeDollars03 AS VolumeAdjustedValue03,
		budg.AdjustedChargeDollars04 AS VolumeAdjustedValue04,
		budg.AdjustedChargeDollars05 AS VolumeAdjustedValue05,
		budg.AdjustedChargeDollars06 AS VolumeAdjustedValue06,
		budg.AdjustedChargeDollars07 AS VolumeAdjustedValue07,
		budg.AdjustedChargeDollars08 AS VolumeAdjustedValue08,
		budg.AdjustedChargeDollars09 AS VolumeAdjustedValue09,
		budg.AdjustedChargeDollars10 AS VolumeAdjustedValue10,
		budg.AdjustedChargeDollars11 AS VolumeAdjustedValue11,
		budg.AdjustedChargeDollars12 AS VolumeAdjustedValue12,
		
		budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01,
		budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02,
		budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03,
		budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04,
		budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05,
		budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06,
		budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07,
		budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08,
		budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09,
		budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10,
		budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11,
		budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12
	FROM fp.FactReimbursementCharges frc
		INNER JOIN fp.FactReimbursementChargesBudget budg ON frc.ReimbursementChargesID = budg.ReimbursementChargesID
	UNION ALL
	SELECT
		budg.RowID,
		budg.ReimbursementEncounterID AS ReimbursementID,
		budg.BudgetPhaseID,
		frc.BudgetConfigID,
		frc.EntityID,
		frc.PatientClassID,
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.PayorID,
		frc.PayorGroupID,
		frc.MedicalSurgicalID,
		frc.MSDRGID,
		frc.CPTID,
		0 AS UBRevCodeID,
		budg.LockFlag,
		budg.LockType,
		CAST(2 AS TINYINT) AS TimeClassID,
		5 AS SubsectionID, -- Encounters
	
		budg.AdjustedNetPerEncounterValue01 AS RateAdjustedValue01,
		budg.AdjustedNetPerEncounterValue02 AS RateAdjustedValue02,
		budg.AdjustedNetPerEncounterValue03 AS RateAdjustedValue03,
		budg.AdjustedNetPerEncounterValue04 AS RateAdjustedValue04,
		budg.AdjustedNetPerEncounterValue05 AS RateAdjustedValue05,
		budg.AdjustedNetPerEncounterValue06 AS RateAdjustedValue06,
		budg.AdjustedNetPerEncounterValue07 AS RateAdjustedValue07,
		budg.AdjustedNetPerEncounterValue08 AS RateAdjustedValue08,
		budg.AdjustedNetPerEncounterValue09 AS RateAdjustedValue09,
		budg.AdjustedNetPerEncounterValue10 AS RateAdjustedValue10,
		budg.AdjustedNetPerEncounterValue11 AS RateAdjustedValue11,
		budg.AdjustedNetPerEncounterValue12 AS RateAdjustedValue12,
		
		budg.AdjustedEncounters01 AS VolumeAdjustedValue01,
		budg.AdjustedEncounters02 AS VolumeAdjustedValue02,
		budg.AdjustedEncounters03 AS VolumeAdjustedValue03,
		budg.AdjustedEncounters04 AS VolumeAdjustedValue04,
		budg.AdjustedEncounters05 AS VolumeAdjustedValue05,
		budg.AdjustedEncounters06 AS VolumeAdjustedValue06,
		budg.AdjustedEncounters07 AS VolumeAdjustedValue07,
		budg.AdjustedEncounters08 AS VolumeAdjustedValue08,
		budg.AdjustedEncounters09 AS VolumeAdjustedValue09,
		budg.AdjustedEncounters10 AS VolumeAdjustedValue10,
		budg.AdjustedEncounters11 AS VolumeAdjustedValue11,
		budg.AdjustedEncounters12 AS VolumeAdjustedValue12,
		
		budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01,
		budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02,
		budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03,
		budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04,
		budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05,
		budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06,
		budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07,
		budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08,
		budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09,
		budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10,
		budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11,
		budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12
	FROM fp.FactReimbursementEncounter frc
		INNER JOIN fp.FactReimbursementEncounterBudget budg ON frc.ReimbursementEncounterID = budg.ReimbursementEncounterID
GO


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

-- fp.viewFactReimbursementChargesHistory_Unpivoted_source
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2022-10-13   MD      JAZZ-32897		Adding union all for data transfer table
*************************************************************/
CREATE VIEW fp.viewFactReimbursementChargesHistory_Unpivoted_source
AS
SELECT 
	frc.BudgetConfigID,
	frc.EntityGroupConfigID,
	frc.EntityID,
	frc.PatientClassID, 
	frc.ServiceLineID,
	frc.ServiceLineRollupID,
	frc.MedicalSurgicalID,
	frc.PayorID, 
	frc.PayorGroupID,
	frc.MSDRGID,
	frc.PrimaryCPTID,
	1 AS TimeClassID,
	bc.FiscalYearID - 2 AS FiscalYearID,
	sum(frch.PriorYearActualNetReimbursementValue01) AS NetReimbursementValue01,
	sum(frch.PriorYearActualNetReimbursementValue02) AS NetReimbursementValue02,
	sum(frch.PriorYearActualNetReimbursementValue03) AS NetReimbursementValue03,
	sum(frch.PriorYearActualNetReimbursementValue04) AS NetReimbursementValue04,
	sum(frch.PriorYearActualNetReimbursementValue05) AS NetReimbursementValue05,
	sum(frch.PriorYearActualNetReimbursementValue06) AS NetReimbursementValue06,
	sum(frch.PriorYearActualNetReimbursementValue07) AS NetReimbursementValue07,
	sum(frch.PriorYearActualNetReimbursementValue08) AS NetReimbursementValue08,
	sum(frch.PriorYearActualNetReimbursementValue09) AS NetReimbursementValue09,
	sum(frch.PriorYearActualNetReimbursementValue10) AS NetReimbursementValue10,
	sum(frch.PriorYearActualNetReimbursementValue11) AS NetReimbursementValue11,
	sum(frch.PriorYearActualNetReimbursementValue12) AS NetReimbursementValue12,
	sum(frch.PriorYearActualChargeDollars01) AS ChargeDollarsValue01,
	sum(frch.PriorYearActualChargeDollars02) AS ChargeDollarsValue02,
	sum(frch.PriorYearActualChargeDollars03) AS ChargeDollarsValue03,
	sum(frch.PriorYearActualChargeDollars04) AS ChargeDollarsValue04,
	sum(frch.PriorYearActualChargeDollars05) AS ChargeDollarsValue05,
	sum(frch.PriorYearActualChargeDollars06) AS ChargeDollarsValue06,
	sum(frch.PriorYearActualChargeDollars07) AS ChargeDollarsValue07,
	sum(frch.PriorYearActualChargeDollars08) AS ChargeDollarsValue08,
	sum(frch.PriorYearActualChargeDollars09) AS ChargeDollarsValue09,
	sum(frch.PriorYearActualChargeDollars10) AS ChargeDollarsValue10,
	sum(frch.PriorYearActualChargeDollars11) AS ChargeDollarsValue11,
	sum(frch.PriorYearActualChargeDollars12) AS ChargeDollarsValue12
FROM fp.FactReimbursementCharges frc 
JOIN fp.FactReimbursementChargesHistory frch
	ON frc.ReimbursementChargesID = frch.ReimbursementChargesID
JOIN fp.BudgetConfig bc on frc.BudgetConfigID = bc.BudgetConfigID
GROUP BY
	frc.BudgetConfigID,
	frc.EntityGroupConfigID,
	frc.EntityID,
	frc.PatientClassID, 
	frc.ServiceLineID,
	frc.ServiceLineRollupID,
	frc.MedicalSurgicalID,
	frc.PayorID, 
	frc.PayorGroupID,
	frc.MSDRGID,
	frc.PrimaryCPTID,
	bc.FiscalYearID
GO


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

-- fp.viewFactReimbursementCharges_Pivoted
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			  Description
 ** 1 	 2022-03-01  BW  	 JAZZ-33273	  Adding net reimbursement calc'd columns for PriorYearActual, Budget, and Projection.
 ** 2 	 2022-03-15  BW  	 JAZZ-33273	  Adding rate columns
*************************************************************/	 


CREATE     VIEW [fp].[viewFactReimbursementCharges_Pivoted]
AS
SELECT
	frc.ReimbursementChargesID,
	frc.BudgetConfigID,
    frc.EntityGroupConfigID,
    frc.EntityID,
    frc.PatientClassID,
    frc.ServiceLineID,
    frc.ServiceLineRollupID,
    frc.MedicalSurgicalID,
    frc.PayorID,
    frc.PayorGroupID,
    frc.MSDRGID,
    frc.PrimaryCPTID,
    frc.UBRevCodeID,

	fbdgt.LockType as BudgetLockType,
	fbdgt.LockFlag as BudgetLockFlag,
	fproj.LockType as ProjectionLockType,
	fproj.LockFlag as ProjectionLockFlag,
	
	CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag,
	CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag,
	CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag,
		   
	fbdgt.AdjustedChargeDollarsTotal,
	dbdgt.AdjustedChargeDollarsTotal as ManagerAdjustedChargeDollarsTotal,
	
	fproj.AdjustedChargeDollarsTotal as AdjustedProjectionValueTotal,
	dproj.AdjustedChargeDollarsTotal as ManagerAdjustedChargeDollarsProjectionTotal,
	
	hist.PriorYearActualChargeDollarsTotal as PriorYearActualChargeDollarsTotal,
	hist.ActualYTDChargeDollarsTotal as ActualYTDValueTotal,
	hist.CurrentYearBudgetChargeDollarsTotal as CurrentYearBudgetTotal,
	
	frc.InitialBudgetChargeDollarsTotal,
	frc.InitialProjectionChargeDollarsTotal,
	
	dbdgt.AdjustedChargeDollars01 AS ManagerAdjustedChargeDollars01, dbdgt.AdjustedChargeDollars02 AS ManagerAdjustedChargeDollars02, 
	dbdgt.AdjustedChargeDollars03 AS ManagerAdjustedChargeDollars03, dbdgt.AdjustedChargeDollars04 AS ManagerAdjustedChargeDollars04, 
	dbdgt.AdjustedChargeDollars05 AS ManagerAdjustedChargeDollars05, dbdgt.AdjustedChargeDollars06 AS ManagerAdjustedChargeDollars06, 
	dbdgt.AdjustedChargeDollars07 AS ManagerAdjustedChargeDollars07, dbdgt.AdjustedChargeDollars08 AS ManagerAdjustedChargeDollars08, 
	dbdgt.AdjustedChargeDollars09 AS ManagerAdjustedChargeDollars09, dbdgt.AdjustedChargeDollars10 AS ManagerAdjustedChargeDollars10, 
	dbdgt.AdjustedChargeDollars11 AS ManagerAdjustedChargeDollars11, dbdgt.AdjustedChargeDollars12 AS ManagerAdjustedChargeDollars12,
	
	fbdgt.AdjustedChargeDollars01, fbdgt.AdjustedChargeDollars02, fbdgt.AdjustedChargeDollars03, fbdgt.AdjustedChargeDollars04, 
	fbdgt.AdjustedChargeDollars05, fbdgt.AdjustedChargeDollars06, fbdgt.AdjustedChargeDollars07, fbdgt.AdjustedChargeDollars08, 
	fbdgt.AdjustedChargeDollars09, fbdgt.AdjustedChargeDollars10, fbdgt.AdjustedChargeDollars11, fbdgt.AdjustedChargeDollars12,

	fproj.AdjustedChargeDollars01 as AdjustedProjectionValue01, fproj.AdjustedChargeDollars02 as AdjustedProjectionValue02, 
	fproj.AdjustedChargeDollars03 as AdjustedProjectionValue03, fproj.AdjustedChargeDollars04 as AdjustedProjectionValue04, 
	fproj.AdjustedChargeDollars05 as AdjustedProjectionValue05, fproj.AdjustedChargeDollars06 as AdjustedProjectionValue06, 
	fproj.AdjustedChargeDollars07 as AdjustedProjectionValue07, fproj.AdjustedChargeDollars08 as AdjustedProjectionValue08, 
	fproj.AdjustedChargeDollars09 as AdjustedProjectionValue09, fproj.AdjustedChargeDollars10 as AdjustedProjectionValue10, 
	fproj.AdjustedChargeDollars11 as AdjustedProjectionValue11, fproj.AdjustedChargeDollars12 as AdjustedProjectionValue12,

	dproj.AdjustedChargeDollars01 as ManagerAdjustedProjectionValue01, dproj.AdjustedChargeDollars02 as ManagerAdjustedProjectionValue02, 
	dproj.AdjustedChargeDollars03 as ManagerAdjustedProjectionValue03, dproj.AdjustedChargeDollars04 as ManagerAdjustedProjectionValue04, 
	dproj.AdjustedChargeDollars05 as ManagerAdjustedProjectionValue05, dproj.AdjustedChargeDollars06 as ManagerAdjustedProjectionValue06, 
	dproj.AdjustedChargeDollars07 as ManagerAdjustedProjectionValue07, dproj.AdjustedChargeDollars08 as ManagerAdjustedProjectionValue08, 
	dproj.AdjustedChargeDollars09 as ManagerAdjustedProjectionValue09, dproj.AdjustedChargeDollars10 as ManagerAdjustedProjectionValue10, 
	dproj.AdjustedChargeDollars11 as ManagerAdjustedProjectionValue11, dproj.AdjustedChargeDollars12 as ManagerAdjustedProjectionValue12,

	frc.InitialBudgetNetReimbursement01, frc.InitialBudgetNetReimbursement02, frc.InitialBudgetNetReimbursement03, frc.InitialBudgetNetReimbursement04, 
	frc.InitialBudgetNetReimbursement05, frc.InitialBudgetNetReimbursement06, frc.InitialBudgetNetReimbursement07, frc.InitialBudgetNetReimbursement08, 
	frc.InitialBudgetNetReimbursement09, frc.InitialBudgetNetReimbursement10, frc.InitialBudgetNetReimbursement11, frc.InitialBudgetNetReimbursement12, 

	frc.InitialProjectionNetReimbursement01, frc.InitialProjectionNetReimbursement02, frc.InitialProjectionNetReimbursement03, 
	frc.InitialProjectionNetReimbursement04, frc.InitialProjectionNetReimbursement05, frc.InitialProjectionNetReimbursement06, 
	frc.InitialProjectionNetReimbursement07, frc.InitialProjectionNetReimbursement08, frc.InitialProjectionNetReimbursement09, 
	frc.InitialProjectionNetReimbursement10, frc.InitialProjectionNetReimbursement11, frc.InitialProjectionNetReimbursement12, 
	
	fbdgt.AdjustedNetReimbursementValue01, fbdgt.AdjustedNetReimbursementValue02, fbdgt.AdjustedNetReimbursementValue03, 
	fbdgt.AdjustedNetReimbursementValue04, fbdgt.AdjustedNetReimbursementValue05, fbdgt.AdjustedNetReimbursementValue06, 
	fbdgt.AdjustedNetReimbursementValue07, fbdgt.AdjustedNetReimbursementValue08, fbdgt.AdjustedNetReimbursementValue09, 
	fbdgt.AdjustedNetReimbursementValue10, fbdgt.AdjustedNetReimbursementValue11, fbdgt.AdjustedNetReimbursementValue12, 
	
	dbdgt.AdjustedNetReimbursementValue01 AS ManagerAdjustedNetReimbursementValue01, dbdgt.AdjustedNetReimbursementValue02 AS ManagerAdjustedNetReimbursementValue02, 
	dbdgt.AdjustedNetReimbursementValue03 AS ManagerAdjustedNetReimbursementValue03, dbdgt.AdjustedNetReimbursementValue04 AS ManagerAdjustedNetReimbursementValue04, 
	dbdgt.AdjustedNetReimbursementValue05 AS ManagerAdjustedNetReimbursementValue05, dbdgt.AdjustedNetReimbursementValue06 AS ManagerAdjustedNetReimbursementValue06, 
	dbdgt.AdjustedNetReimbursementValue07 AS ManagerAdjustedNetReimbursementValue07, dbdgt.AdjustedNetReimbursementValue08 AS ManagerAdjustedNetReimbursementValue08, 
	dbdgt.AdjustedNetReimbursementValue09 AS ManagerAdjustedNetReimbursementValue09, dbdgt.AdjustedNetReimbursementValue10 AS ManagerAdjustedNetReimbursementValue10, 
	dbdgt.AdjustedNetReimbursementValue11 AS ManagerAdjustedNetReimbursementValue11, dbdgt.AdjustedNetReimbursementValue12 AS ManagerAdjustedNetReimbursementValue12,

	fproj.AdjustedNetReimbursementValue01 AS AdjustedProjectionNetReimbursementValue01, fproj.AdjustedNetReimbursementValue02 AS AdjustedProjectionNetReimbursementValue02, 
	fproj.AdjustedNetReimbursementValue03 AS AdjustedProjectionNetReimbursementValue03, fproj.AdjustedNetReimbursementValue04 AS AdjustedProjectionNetReimbursementValue04, 
	fproj.AdjustedNetReimbursementValue05 AS AdjustedProjectionNetReimbursementValue05, fproj.AdjustedNetReimbursementValue06 AS AdjustedProjectionNetReimbursementValue06, 
	fproj.AdjustedNetReimbursementValue07 AS AdjustedProjectionNetReimbursementValue07, fproj.AdjustedNetReimbursementValue08 AS AdjustedProjectionNetReimbursementValue08, 
	fproj.AdjustedNetReimbursementValue09 AS AdjustedProjectionNetReimbursementValue09, fproj.AdjustedNetReimbursementValue10 AS AdjustedProjectionNetReimbursementValue10, 
	fproj.AdjustedNetReimbursementValue11 AS AdjustedProjectionNetReimbursementValue11, fproj.AdjustedNetReimbursementValue12 AS AdjustedProjectionNetReimbursementValue12,
	
	dproj.AdjustedNetReimbursementValue01 AS ManagerAdjustedProjectionNetReimbursementValue01, dproj.AdjustedNetReimbursementValue02 AS ManagerAdjustedProjectionNetReimbursementValue02, 
	dproj.AdjustedNetReimbursementValue03 AS ManagerAdjustedProjectionNetReimbursementValue03, dproj.AdjustedNetReimbursementValue04 AS ManagerAdjustedProjectionNetReimbursementValue04, 
	dproj.AdjustedNetReimbursementValue05 AS ManagerAdjustedProjectionNetReimbursementValue05, dproj.AdjustedNetReimbursementValue06 AS ManagerAdjustedProjectionNetReimbursementValue06, 
	dproj.AdjustedNetReimbursementValue07 AS ManagerAdjustedProjectionNetReimbursementValue07, dproj.AdjustedNetReimbursementValue08 AS ManagerAdjustedProjectionNetReimbursementValue08, 
	dproj.AdjustedNetReimbursementValue09 AS ManagerAdjustedProjectionNetReimbursementValue09, dproj.AdjustedNetReimbursementValue10 AS ManagerAdjustedProjectionNetReimbursementValue10, 
	dproj.AdjustedNetReimbursementValue11 AS ManagerAdjustedProjectionNetReimbursementValue11, dproj.AdjustedNetReimbursementValue12 AS ManagerAdjustedProjectionNetReimbursementValue12,

	dbdgt.AdjustedNetAsPercentOfCharge01 AS ManagerAdjustedNetAsPercentOfCharge01, dbdgt.AdjustedNetAsPercentOfCharge02 AS ManagerAdjustedNetAsPercentOfCharge02, 
	dbdgt.AdjustedNetAsPercentOfCharge03 AS ManagerAdjustedNetAsPercentOfCharge03, dbdgt.AdjustedNetAsPercentOfCharge04 AS ManagerAdjustedNetAsPercentOfCharge04, 
	dbdgt.AdjustedNetAsPercentOfCharge05 AS ManagerAdjustedNetAsPercentOfCharge05, dbdgt.AdjustedNetAsPercentOfCharge06 AS ManagerAdjustedNetAsPercentOfCharge06, 
	dbdgt.AdjustedNetAsPercentOfCharge07 AS ManagerAdjustedNetAsPercentOfCharge07, dbdgt.AdjustedNetAsPercentOfCharge08 AS ManagerAdjustedNetAsPercentOfCharge08, 
	dbdgt.AdjustedNetAsPercentOfCharge09 AS ManagerAdjustedNetAsPercentOfCharge09, dbdgt.AdjustedNetAsPercentOfCharge10 AS ManagerAdjustedNetAsPercentOfCharge10, 
	dbdgt.AdjustedNetAsPercentOfCharge11 AS ManagerAdjustedNetAsPercentOfCharge11, dbdgt.AdjustedNetAsPercentOfCharge12 AS ManagerAdjustedNetAsPercentOfCharge12,

	fbdgt.AdjustedNetAsPercentOfCharge01, fbdgt.AdjustedNetAsPercentOfCharge02, fbdgt.AdjustedNetAsPercentOfCharge03, 
	fbdgt.AdjustedNetAsPercentOfCharge04, fbdgt.AdjustedNetAsPercentOfCharge05, fbdgt.AdjustedNetAsPercentOfCharge06, 
	fbdgt.AdjustedNetAsPercentOfCharge07, fbdgt.AdjustedNetAsPercentOfCharge08, fbdgt.AdjustedNetAsPercentOfCharge09, 
	fbdgt.AdjustedNetAsPercentOfCharge10, fbdgt.AdjustedNetAsPercentOfCharge11, fbdgt.AdjustedNetAsPercentOfCharge12, 

	fproj.AdjustedNetAsPercentOfCharge01 AS AdjustedProjectionNetAsPercentOfCharge01, fproj.AdjustedNetAsPercentOfCharge02 AS AdjustedProjectionNetAsPercentOfCharge02, 
	fproj.AdjustedNetAsPercentOfCharge03 AS AdjustedProjectionNetAsPercentOfCharge03, fproj.AdjustedNetAsPercentOfCharge04 AS AdjustedProjectionNetAsPercentOfCharge04, 
	fproj.AdjustedNetAsPercentOfCharge05 AS AdjustedProjectionNetAsPercentOfCharge05, fproj.AdjustedNetAsPercentOfCharge06 AS AdjustedProjectionNetAsPercentOfCharge06, 
	fproj.AdjustedNetAsPercentOfCharge07 AS AdjustedProjectionNetAsPercentOfCharge07, fproj.AdjustedNetAsPercentOfCharge08 AS AdjustedProjectionNetAsPercentOfCharge08, 
	fproj.AdjustedNetAsPercentOfCharge09 AS AdjustedProjectionNetAsPercentOfCharge09, fproj.AdjustedNetAsPercentOfCharge10 AS AdjustedProjectionNetAsPercentOfCharge10, 
	fproj.AdjustedNetAsPercentOfCharge11 AS AdjustedProjectionNetAsPercentOfCharge11, fproj.AdjustedNetAsPercentOfCharge12 AS AdjustedProjectionNetAsPercentOfCharge12,
	
	dproj.AdjustedNetAsPercentOfCharge01 AS ManagerAdjustedProjectionNetAsPercentOfCharge01, dproj.AdjustedNetAsPercentOfCharge02 AS ManagerAdjustedProjectionNetAsPercentOfCharge02, 
	dproj.AdjustedNetAsPercentOfCharge03 AS ManagerAdjustedProjectionNetAsPercentOfCharge03, dproj.AdjustedNetAsPercentOfCharge04 AS ManagerAdjustedProjectionNetAsPercentOfCharge04, 
	dproj.AdjustedNetAsPercentOfCharge05 AS ManagerAdjustedProjectionNetAsPercentOfCharge05, dproj.AdjustedNetAsPercentOfCharge06 AS ManagerAdjustedProjectionNetAsPercentOfCharge06, 
	dproj.AdjustedNetAsPercentOfCharge07 AS ManagerAdjustedProjectionNetAsPercentOfCharge07, dproj.AdjustedNetAsPercentOfCharge08 AS ManagerAdjustedProjectionNetAsPercentOfCharge08, 
	dproj.AdjustedNetAsPercentOfCharge09 AS ManagerAdjustedProjectionNetAsPercentOfCharge09, dproj.AdjustedNetAsPercentOfCharge10 AS ManagerAdjustedProjectionNetAsPercentOfCharge10, 
	dproj.AdjustedNetAsPercentOfCharge11 AS ManagerAdjustedProjectionNetAsPercentOfCharge11, dproj.AdjustedNetAsPercentOfCharge12 AS ManagerAdjustedProjectionNetAsPercentOfCharge12,

	hist.PriorYearActualNetReimbursementValue01, hist.PriorYearActualNetReimbursementValue02, hist.PriorYearActualNetReimbursementValue03, hist.PriorYearActualNetReimbursementValue04, 
	hist.PriorYearActualNetReimbursementValue05, hist.PriorYearActualNetReimbursementValue06, hist.PriorYearActualNetReimbursementValue07, hist.PriorYearActualNetReimbursementValue08, 
	hist.PriorYearActualNetReimbursementValue09, hist.PriorYearActualNetReimbursementValue10, hist.PriorYearActualNetReimbursementValue11, hist.PriorYearActualNetReimbursementValue12,
	
	hist.ActualYTDNetReimbursementValue01, hist.ActualYTDNetReimbursementValue02, hist.ActualYTDNetReimbursementValue03, hist.ActualYTDNetReimbursementValue04, 
	hist.ActualYTDNetReimbursementValue05, hist.ActualYTDNetReimbursementValue06, hist.ActualYTDNetReimbursementValue07, hist.ActualYTDNetReimbursementValue08, 
	hist.ActualYTDNetReimbursementValue09, hist.ActualYTDNetReimbursementValue10, hist.ActualYTDNetReimbursementValue11, hist.ActualYTDNetReimbursementValue12, 
	
	hist.CurrentYearNetReimbursementBudget01, hist.CurrentYearNetReimbursementBudget02, hist.CurrentYearNetReimbursementBudget03, hist.CurrentYearNetReimbursementBudget04, 
	hist.CurrentYearNetReimbursementBudget05, hist.CurrentYearNetReimbursementBudget06, hist.CurrentYearNetReimbursementBudget07, hist.CurrentYearNetReimbursementBudget08, 
	hist.CurrentYearNetReimbursementBudget09, hist.CurrentYearNetReimbursementBudget10, hist.CurrentYearNetReimbursementBudget11, hist.CurrentYearNetReimbursementBudget12

FROM 
	fp.FactReimbursementCharges frc
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON frc.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN fp.FactReimbursementChargesBudget fbdgt with (readuncommitted) ON frc.ReimbursementChargesID = fbdgt.ReimbursementChargesID and fbdgt.BudgetPhaseID = 2
	INNER JOIN fp.FactReimbursementChargesBudget dbdgt with (readuncommitted) ON frc.ReimbursementChargesID = dbdgt.ReimbursementChargesID and dbdgt.BudgetPhaseID = 3
	INNER JOIN fp.FactReimbursementChargesProjection fproj with (readuncommitted) ON frc.ReimbursementChargesID = fproj.ReimbursementChargesID and fproj.BudgetPhaseID = 2
	INNER JOIN fp.FactReimbursementChargesProjection dproj with (readuncommitted) ON frc.ReimbursementChargesID = dproj.ReimbursementChargesID and dproj.BudgetPhaseID = 3
	INNER JOIN fp.FactReimbursementChargesHistory hist with (readuncommitted) ON frc.ReimbursementChargesID = hist.ReimbursementChargesID
GO


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

-- fp.viewFactReimbursementCharges_Unpivoted_source
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2022-10-13   MD      JAZZ-32897		Adding union all for data transfer table
*************************************************************/
CREATE VIEW fp.viewFactReimbursementCharges_Unpivoted_source
AS
	SELECT 
		frc.BudgetConfigID,
		frc.EntityGroupConfigID,
		frc.EntityID,
		frc.PatientClassID, 
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.MedicalSurgicalID,
		frc.PayorID, 
		frc.PayorGroupID,
		frc.MSDRGID,
		frc.PrimaryCPTID,
		2 AS TimeClassID,
		bc.FiscalYearID AS FiscalYearID,
		sum(frcb.AdjustedNetReimbursementValue01) AS NetReimbursementValue01,
		sum(frcb.AdjustedNetReimbursementValue02) AS NetReimbursementValue02,
		sum(frcb.AdjustedNetReimbursementValue03) AS NetReimbursementValue03,
		sum(frcb.AdjustedNetReimbursementValue04) AS NetReimbursementValue04,
		sum(frcb.AdjustedNetReimbursementValue05) AS NetReimbursementValue05,
		sum(frcb.AdjustedNetReimbursementValue06) AS NetReimbursementValue06,
		sum(frcb.AdjustedNetReimbursementValue07) AS NetReimbursementValue07,
		sum(frcb.AdjustedNetReimbursementValue08) AS NetReimbursementValue08,
		sum(frcb.AdjustedNetReimbursementValue09) AS NetReimbursementValue09,
		sum(frcb.AdjustedNetReimbursementValue10) AS NetReimbursementValue10,
		sum(frcb.AdjustedNetReimbursementValue11) AS NetReimbursementValue11,
		sum(frcb.AdjustedNetReimbursementValue12) AS NetReimbursementValue12,
		sum(frcb.AdjustedChargeDollars01) AS ChargeDollarsValue01,
		sum(frcb.AdjustedChargeDollars02) AS ChargeDollarsValue02,
		sum(frcb.AdjustedChargeDollars03) AS ChargeDollarsValue03,
		sum(frcb.AdjustedChargeDollars04) AS ChargeDollarsValue04,
		sum(frcb.AdjustedChargeDollars05) AS ChargeDollarsValue05,
		sum(frcb.AdjustedChargeDollars06) AS ChargeDollarsValue06,
		sum(frcb.AdjustedChargeDollars07) AS ChargeDollarsValue07,
		sum(frcb.AdjustedChargeDollars08) AS ChargeDollarsValue08,
		sum(frcb.AdjustedChargeDollars09) AS ChargeDollarsValue09,
		sum(frcb.AdjustedChargeDollars10) AS ChargeDollarsValue10,
		sum(frcb.AdjustedChargeDollars11) AS ChargeDollarsValue11,
		sum(frcb.AdjustedChargeDollars12) AS ChargeDollarsValue12
	FROM fp.FactReimbursementCharges frc 
	JOIN fp.FactReimbursementChargesBudget frcb
		ON frc.ReimbursementChargesID = frcb.ReimbursementChargesID
	JOIN fp.BudgetConfig bc on frc.BudgetConfigID = bc.BudgetConfigID
	WHERE frcb.BudgetPhaseID = 3
	GROUP BY
		frc.BudgetConfigID,
		frc.EntityGroupConfigID,
		frc.EntityID,
		frc.PatientClassID, 
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.MedicalSurgicalID,
		frc.PayorID, 
		frc.PayorGroupID,
		frc.MSDRGID,
		frc.PrimaryCPTID,
		bc.FiscalYearID

	UNION ALL

	SELECT 
		frc.BudgetConfigID,
		frc.EntityGroupConfigID,
		frc.EntityID,
		frc.PatientClassID, 
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.MedicalSurgicalID,
		frc.PayorID, 
		frc.PayorGroupID,
		frc.MSDRGID,
		frc.PrimaryCPTID,
		12 AS TimeClassID,
		bc.FiscalYearID - 1 AS FiscalYearID,
		sum(frcp.AdjustedNetReimbursementValue01) AS NetReimbursementValue01,
		sum(frcp.AdjustedNetReimbursementValue02) AS NetReimbursementValue02,
		sum(frcp.AdjustedNetReimbursementValue03) AS NetReimbursementValue03,
		sum(frcp.AdjustedNetReimbursementValue04) AS NetReimbursementValue04,
		sum(frcp.AdjustedNetReimbursementValue05) AS NetReimbursementValue05,
		sum(frcp.AdjustedNetReimbursementValue06) AS NetReimbursementValue06,
		sum(frcp.AdjustedNetReimbursementValue07) AS NetReimbursementValue07,
		sum(frcp.AdjustedNetReimbursementValue08) AS NetReimbursementValue08,
		sum(frcp.AdjustedNetReimbursementValue09) AS NetReimbursementValue09,
		sum(frcp.AdjustedNetReimbursementValue10) AS NetReimbursementValue10,
		sum(frcp.AdjustedNetReimbursementValue11) AS NetReimbursementValue11,
		sum(frcp.AdjustedNetReimbursementValue12) AS NetReimbursementValue12,
		sum(frcp.AdjustedChargeDollars01) AS ChargeDollarsValue01,
		sum(frcp.AdjustedChargeDollars02) AS ChargeDollarsValue02,
		sum(frcp.AdjustedChargeDollars03) AS ChargeDollarsValue03,
		sum(frcp.AdjustedChargeDollars04) AS ChargeDollarsValue04,
		sum(frcp.AdjustedChargeDollars05) AS ChargeDollarsValue05,
		sum(frcp.AdjustedChargeDollars06) AS ChargeDollarsValue06,
		sum(frcp.AdjustedChargeDollars07) AS ChargeDollarsValue07,
		sum(frcp.AdjustedChargeDollars08) AS ChargeDollarsValue08,
		sum(frcp.AdjustedChargeDollars09) AS ChargeDollarsValue09,
		sum(frcp.AdjustedChargeDollars10) AS ChargeDollarsValue10,
		sum(frcp.AdjustedChargeDollars11) AS ChargeDollarsValue11,
		sum(frcp.AdjustedChargeDollars12) AS ChargeDollarsValue12
	FROM fp.FactReimbursementCharges frc 
	JOIN fp.FactReimbursementChargesProjection frcp
		ON frc.ReimbursementChargesID = frcp.ReimbursementChargesID
	JOIN fp.BudgetConfig bc on frc.BudgetConfigID = bc.BudgetConfigID
	WHERE frcp.BudgetPhaseID = 3
	GROUP BY
		frc.BudgetConfigID,
		frc.EntityGroupConfigID,
		frc.EntityID,
		frc.PatientClassID, 
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.MedicalSurgicalID,
		frc.PayorID, 
		frc.PayorGroupID,
		frc.MSDRGID,
		frc.PrimaryCPTID,
		bc.FiscalYearID
GO


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

-- fp.viewFactReimbursementEncounter_Pivoted
CREATE   VIEW [fp].[viewFactReimbursementEncounter_Pivoted]
AS
SELECT
	fre.ReimbursementEncounterID,
	fre.BudgetConfigID,
    fre.EntityGroupConfigID,
    fre.EntityID,
    fre.PatientClassID,
    fre.ServiceLineID,
    fre.ServiceLineRollupID,
    fre.MedicalSurgicalID,
    fre.PayorID,
    fre.PayorGroupID,
    fre.MSDRGID,
    fre.CPTID,

	fbdgt.LockType as BudgetLockType,
	fbdgt.LockFlag as BudgetLockFlag,
	fproj.LockType as ProjectionLockType,
	fproj.LockFlag as ProjectionLockFlag,
	
	CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag,
	CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag,
	CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag,
		   
	fbdgt.AdjustedEncountersTotal,
	dbdgt.AdjustedEncountersTotal as ManagerAdjustedEncountersTotal,
	
	fproj.AdjustedEncountersTotal as AdjustedProjectionEncountersTotal,
	dproj.AdjustedEncountersTotal as ManagerAdjustedProjectionEncountersTotal,
	
	hist.PriorYearActualEncountersTotal as PriorYearActualEncountersTotal,
	hist.ActualYTDEncountersTotal as ActualYTDEncountersTotal,
	hist.CurrentYearBudgetEncountersTotal as CurrentYearBudgetEncountersTotal,
	
	fre.InitialBudgetEncountersTotal,
	fre.InitialProjectionEncountersTotal,
	
	dbdgt.AdjustedEncounters01 AS ManagerAdjustedEncounters01, dbdgt.AdjustedEncounters02 AS ManagerAdjustedEncounters02, dbdgt.AdjustedEncounters03 AS ManagerAdjustedEncounters03, 
	dbdgt.AdjustedEncounters04 AS ManagerAdjustedEncounters04, dbdgt.AdjustedEncounters05 AS ManagerAdjustedEncounters05, dbdgt.AdjustedEncounters06 AS ManagerAdjustedEncounters06, 
	dbdgt.AdjustedEncounters07 AS ManagerAdjustedEncounters07, dbdgt.AdjustedEncounters08 AS ManagerAdjustedEncounters08, dbdgt.AdjustedEncounters09 AS ManagerAdjustedEncounters09, 
	dbdgt.AdjustedEncounters10 AS ManagerAdjustedEncounters10, dbdgt.AdjustedEncounters11 AS ManagerAdjustedEncounters11, dbdgt.AdjustedEncounters12 AS ManagerAdjustedEncounters12,
	
	fbdgt.AdjustedEncounters01, fbdgt.AdjustedEncounters02, fbdgt.AdjustedEncounters03, fbdgt.AdjustedEncounters04, fbdgt.AdjustedEncounters05, fbdgt.AdjustedEncounters06, 
	fbdgt.AdjustedEncounters07, fbdgt.AdjustedEncounters08, fbdgt.AdjustedEncounters09, fbdgt.AdjustedEncounters10, fbdgt.AdjustedEncounters11, fbdgt.AdjustedEncounters12,

	fproj.AdjustedEncounters01 as AdjustedProjectionEncounters01, fproj.AdjustedEncounters02 as AdjustedProjectionEncounters02, fproj.AdjustedEncounters03 as AdjustedProjectionEncounters03, 
	fproj.AdjustedEncounters04 as AdjustedProjectionEncounters04, fproj.AdjustedEncounters05 as AdjustedProjectionEncounters05, fproj.AdjustedEncounters06 as AdjustedProjectionEncounters06, 
	fproj.AdjustedEncounters07 as AdjustedProjectionEncounters07, fproj.AdjustedEncounters08 as AdjustedProjectionEncounters08, fproj.AdjustedEncounters09 as AdjustedProjectionEncounters09, 
	fproj.AdjustedEncounters10 as AdjustedProjectionEncounters10, fproj.AdjustedEncounters11 as AdjustedProjectionEncounters11, fproj.AdjustedEncounters12 as AdjustedProjectionEncounters12,

	dproj.AdjustedEncounters01 as ManagerAdjustedProjectionEncounters01, dproj.AdjustedEncounters02 as ManagerAdjustedProjectionEncounters02, dproj.AdjustedEncounters03 as ManagerAdjustedProjectionEncounters03, 
	dproj.AdjustedEncounters04 as ManagerAdjustedProjectionEncounters04, dproj.AdjustedEncounters05 as ManagerAdjustedProjectionEncounters05, dproj.AdjustedEncounters06 as ManagerAdjustedProjectionEncounters06, 
	dproj.AdjustedEncounters07 as ManagerAdjustedProjectionEncounters07, dproj.AdjustedEncounters08 as ManagerAdjustedProjectionEncounters08, dproj.AdjustedEncounters09 as ManagerAdjustedProjectionEncounters09, 
	dproj.AdjustedEncounters10 as ManagerAdjustedProjectionEncounters10, dproj.AdjustedEncounters11 as ManagerAdjustedProjectionEncounters11, dproj.AdjustedEncounters12 as ManagerAdjustedProjectionEncounters12,

	fre.InitialBudgetNetReimbursement01, fre.InitialBudgetNetReimbursement02, fre.InitialBudgetNetReimbursement03, fre.InitialBudgetNetReimbursement04, 
	fre.InitialBudgetNetReimbursement05, fre.InitialBudgetNetReimbursement06, fre.InitialBudgetNetReimbursement07, fre.InitialBudgetNetReimbursement08, 
	fre.InitialBudgetNetReimbursement09, fre.InitialBudgetNetReimbursement10, fre.InitialBudgetNetReimbursement11, fre.InitialBudgetNetReimbursement12, 

	fre.InitialProjectionNetReimbursement01, fre.InitialProjectionNetReimbursement02, fre.InitialProjectionNetReimbursement03, fre.InitialProjectionNetReimbursement04, 
	fre.InitialProjectionNetReimbursement05, fre.InitialProjectionNetReimbursement06, fre.InitialProjectionNetReimbursement07, fre.InitialProjectionNetReimbursement08, 
	fre.InitialProjectionNetReimbursement09, fre.InitialProjectionNetReimbursement10, fre.InitialProjectionNetReimbursement11, fre.InitialProjectionNetReimbursement12, 
	
	fbdgt.AdjustedNetReimbursementValue01, fbdgt.AdjustedNetReimbursementValue02, fbdgt.AdjustedNetReimbursementValue03, fbdgt.AdjustedNetReimbursementValue04, 
	fbdgt.AdjustedNetReimbursementValue05, fbdgt.AdjustedNetReimbursementValue06, fbdgt.AdjustedNetReimbursementValue07, fbdgt.AdjustedNetReimbursementValue08, 
	fbdgt.AdjustedNetReimbursementValue09, fbdgt.AdjustedNetReimbursementValue10, fbdgt.AdjustedNetReimbursementValue11, fbdgt.AdjustedNetReimbursementValue12, 
	
	dbdgt.AdjustedNetReimbursementValue01 AS ManagerAdjustedNetReimbursementValue01, dbdgt.AdjustedNetReimbursementValue02 AS ManagerAdjustedNetReimbursementValue02, 
	dbdgt.AdjustedNetReimbursementValue03 AS ManagerAdjustedNetReimbursementValue03, dbdgt.AdjustedNetReimbursementValue04 AS ManagerAdjustedNetReimbursementValue04, 
	dbdgt.AdjustedNetReimbursementValue05 AS ManagerAdjustedNetReimbursementValue05, dbdgt.AdjustedNetReimbursementValue06 AS ManagerAdjustedNetReimbursementValue06, 
	dbdgt.AdjustedNetReimbursementValue07 AS ManagerAdjustedNetReimbursementValue07, dbdgt.AdjustedNetReimbursementValue08 AS ManagerAdjustedNetReimbursementValue08, 
	dbdgt.AdjustedNetReimbursementValue09 AS ManagerAdjustedNetReimbursementValue09, dbdgt.AdjustedNetReimbursementValue10 AS ManagerAdjustedNetReimbursementValue10, 
	dbdgt.AdjustedNetReimbursementValue11 AS ManagerAdjustedNetReimbursementValue11, dbdgt.AdjustedNetReimbursementValue12 AS ManagerAdjustedNetReimbursementValue12,

	fproj.AdjustedNetReimbursementValue01 AS AdjustedProjectionNetReimbursementValue01, fproj.AdjustedNetReimbursementValue02 AS AdjustedProjectionNetReimbursementValue02, 
	fproj.AdjustedNetReimbursementValue03 AS AdjustedProjectionNetReimbursementValue03, fproj.AdjustedNetReimbursementValue04 AS AdjustedProjectionNetReimbursementValue04, 
	fproj.AdjustedNetReimbursementValue05 AS AdjustedProjectionNetReimbursementValue05, fproj.AdjustedNetReimbursementValue06 AS AdjustedProjectionNetReimbursementValue06, 
	fproj.AdjustedNetReimbursementValue07 AS AdjustedProjectionNetReimbursementValue07, fproj.AdjustedNetReimbursementValue08 AS AdjustedProjectionNetReimbursementValue08, 
	fproj.AdjustedNetReimbursementValue09 AS AdjustedProjectionNetReimbursementValue09, fproj.AdjustedNetReimbursementValue10 AS AdjustedProjectionNetReimbursementValue10, 
	fproj.AdjustedNetReimbursementValue11 AS AdjustedProjectionNetReimbursementValue11, fproj.AdjustedNetReimbursementValue12 AS AdjustedProjectionNetReimbursementValue12,
	
	dproj.AdjustedNetReimbursementValue01 AS ManagerAdjustedProjectionNetReimbursementValue01, dproj.AdjustedNetReimbursementValue02 AS ManagerAdjustedProjectionNetReimbursementValue02, 
	dproj.AdjustedNetReimbursementValue03 AS ManagerAdjustedProjectionNetReimbursementValue03, dproj.AdjustedNetReimbursementValue04 AS ManagerAdjustedProjectionNetReimbursementValue04, 
	dproj.AdjustedNetReimbursementValue05 AS ManagerAdjustedProjectionNetReimbursementValue05, dproj.AdjustedNetReimbursementValue06 AS ManagerAdjustedProjectionNetReimbursementValue06, 
	dproj.AdjustedNetReimbursementValue07 AS ManagerAdjustedProjectionNetReimbursementValue07, dproj.AdjustedNetReimbursementValue08 AS ManagerAdjustedProjectionNetReimbursementValue08, 
	dproj.AdjustedNetReimbursementValue09 AS ManagerAdjustedProjectionNetReimbursementValue09, dproj.AdjustedNetReimbursementValue10 AS ManagerAdjustedProjectionNetReimbursementValue10, 
	dproj.AdjustedNetReimbursementValue11 AS ManagerAdjustedProjectionNetReimbursementValue11, dproj.AdjustedNetReimbursementValue12 AS ManagerAdjustedProjectionNetReimbursementValue12,

	fbdgt.AdjustedNetPerEncounterValue01, fbdgt.AdjustedNetPerEncounterValue02, fbdgt.AdjustedNetPerEncounterValue03, fbdgt.AdjustedNetPerEncounterValue04, 
	fbdgt.AdjustedNetPerEncounterValue05, fbdgt.AdjustedNetPerEncounterValue06, fbdgt.AdjustedNetPerEncounterValue07, fbdgt.AdjustedNetPerEncounterValue08, 
	fbdgt.AdjustedNetPerEncounterValue09, fbdgt.AdjustedNetPerEncounterValue10, fbdgt.AdjustedNetPerEncounterValue11, fbdgt.AdjustedNetPerEncounterValue12, 

	dbdgt.AdjustedNetPerEncounterValue01 AS ManagerAdjustedNetPerEncounterValue01, dbdgt.AdjustedNetPerEncounterValue02 AS ManagerAdjustedNetPerEncounterValue02, 
	dbdgt.AdjustedNetPerEncounterValue03 AS ManagerAdjustedNetPerEncounterValue03, dbdgt.AdjustedNetPerEncounterValue04 AS ManagerAdjustedNetPerEncounterValue04, 
	dbdgt.AdjustedNetPerEncounterValue05 AS ManagerAdjustedNetPerEncounterValue05, dbdgt.AdjustedNetPerEncounterValue06 AS ManagerAdjustedNetPerEncounterValue06, 
	dbdgt.AdjustedNetPerEncounterValue07 AS ManagerAdjustedNetPerEncounterValue07, dbdgt.AdjustedNetPerEncounterValue08 AS ManagerAdjustedNetPerEncounterValue08, 
	dbdgt.AdjustedNetPerEncounterValue09 AS ManagerAdjustedNetPerEncounterValue09, dbdgt.AdjustedNetPerEncounterValue10 AS ManagerAdjustedNetPerEncounterValue10, 
	dbdgt.AdjustedNetPerEncounterValue11 AS ManagerAdjustedNetPerEncounterValue11, dbdgt.AdjustedNetPerEncounterValue12 AS ManagerAdjustedNetPerEncounterValue12,

	fproj.AdjustedNetPerEncounterValue01 AS AdjustedProjectionNetPerEncounterValue01, fproj.AdjustedNetPerEncounterValue02 AS AdjustedProjectionNetPerEncounterValue02, 
	fproj.AdjustedNetPerEncounterValue03 AS AdjustedProjectionNetPerEncounterValue03, fproj.AdjustedNetPerEncounterValue04 AS AdjustedProjectionNetPerEncounterValue04, 
	fproj.AdjustedNetPerEncounterValue05 AS AdjustedProjectionNetPerEncounterValue05, fproj.AdjustedNetPerEncounterValue06 AS AdjustedProjectionNetPerEncounterValue06, 
	fproj.AdjustedNetPerEncounterValue07 AS AdjustedProjectionNetPerEncounterValue07, fproj.AdjustedNetPerEncounterValue08 AS AdjustedProjectionNetPerEncounterValue08, 
	fproj.AdjustedNetPerEncounterValue09 AS AdjustedProjectionNetPerEncounterValue09, fproj.AdjustedNetPerEncounterValue10 AS AdjustedProjectionNetPerEncounterValue10, 
	fproj.AdjustedNetPerEncounterValue11 AS AdjustedProjectionNetPerEncounterValue11, fproj.AdjustedNetPerEncounterValue12 AS AdjustedProjectionNetPerEncounterValue12,
	
	dproj.AdjustedNetPerEncounterValue01 AS ManagerAdjustedProjectionNetPerEncounterValue01, dproj.AdjustedNetPerEncounterValue02 AS ManagerAdjustedProjectionNetPerEncounterValue02, 
	dproj.AdjustedNetPerEncounterValue03 AS ManagerAdjustedProjectionNetPerEncounterValue03, dproj.AdjustedNetPerEncounterValue04 AS ManagerAdjustedProjectionNetPerEncounterValue04, 
	dproj.AdjustedNetPerEncounterValue05 AS ManagerAdjustedProjectionNetPerEncounterValue05, dproj.AdjustedNetPerEncounterValue06 AS ManagerAdjustedProjectionNetPerEncounterValue06, 
	dproj.AdjustedNetPerEncounterValue07 AS ManagerAdjustedProjectionNetPerEncounterValue07, dproj.AdjustedNetPerEncounterValue08 AS ManagerAdjustedProjectionNetPerEncounterValue08, 
	dproj.AdjustedNetPerEncounterValue09 AS ManagerAdjustedProjectionNetPerEncounterValue09, dproj.AdjustedNetPerEncounterValue10 AS ManagerAdjustedProjectionNetPerEncounterValue10, 
	dproj.AdjustedNetPerEncounterValue11 AS ManagerAdjustedProjectionNetPerEncounterValue11, dproj.AdjustedNetPerEncounterValue12 AS ManagerAdjustedProjectionNetPerEncounterValue12,

	hist.PriorYearActualNetReimbursementValue01, hist.PriorYearActualNetReimbursementValue02, hist.PriorYearActualNetReimbursementValue03, hist.PriorYearActualNetReimbursementValue04, 
	hist.PriorYearActualNetReimbursementValue05, hist.PriorYearActualNetReimbursementValue06, hist.PriorYearActualNetReimbursementValue07, hist.PriorYearActualNetReimbursementValue08, 
	hist.PriorYearActualNetReimbursementValue09, hist.PriorYearActualNetReimbursementValue10, hist.PriorYearActualNetReimbursementValue11, hist.PriorYearActualNetReimbursementValue12,
	
	hist.ActualYTDNetReimbursementValue01, hist.ActualYTDNetReimbursementValue02, hist.ActualYTDNetReimbursementValue03, hist.ActualYTDNetReimbursementValue04, 
	hist.ActualYTDNetReimbursementValue05, hist.ActualYTDNetReimbursementValue06, hist.ActualYTDNetReimbursementValue07, hist.ActualYTDNetReimbursementValue08, 
	hist.ActualYTDNetReimbursementValue09, hist.ActualYTDNetReimbursementValue10, hist.ActualYTDNetReimbursementValue11, hist.ActualYTDNetReimbursementValue12, 
	
	hist.CurrentYearNetReimbursementBudget01, hist.CurrentYearNetReimbursementBudget02, hist.CurrentYearNetReimbursementBudget03, hist.CurrentYearNetReimbursementBudget04, 
	hist.CurrentYearNetReimbursementBudget05, hist.CurrentYearNetReimbursementBudget06, hist.CurrentYearNetReimbursementBudget07, hist.CurrentYearNetReimbursementBudget08, 
	hist.CurrentYearNetReimbursementBudget09, hist.CurrentYearNetReimbursementBudget10, hist.CurrentYearNetReimbursementBudget11, hist.CurrentYearNetReimbursementBudget12



FROM 
	fp.FactReimbursementEncounter fre
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fre.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN fp.FactReimbursementEncounterBudget fbdgt with (readuncommitted) ON fre.ReimbursementEncounterID = fbdgt.ReimbursementEncounterID and fbdgt.BudgetPhaseID = 2
	INNER JOIN fp.FactReimbursementEncounterBudget dbdgt with (readuncommitted) ON fre.ReimbursementEncounterID = dbdgt.ReimbursementEncounterID and dbdgt.BudgetPhaseID = 3
	INNER JOIN fp.FactReimbursementEncounterProjection fproj with (readuncommitted) ON fre.ReimbursementEncounterID = fproj.ReimbursementEncounterID and fproj.BudgetPhaseID = 2
	INNER JOIN fp.FactReimbursementEncounterProjection dproj with (readuncommitted) ON fre.ReimbursementEncounterID = dproj.ReimbursementEncounterID and dproj.BudgetPhaseID = 3
	INNER JOIN fp.FactReimbursementEncounterHistory hist with (readuncommitted) ON fre.ReimbursementEncounterID = hist.ReimbursementEncounterID
GO


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

-- fp.viewFactReimbursementEncountersHistory_Unpivoted_source
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2022-10-13   MD      JAZZ-32897		Adding union all for data transfer table
*************************************************************/
CREATE VIEW fp.viewFactReimbursementEncountersHistory_Unpivoted_source
AS
SELECT 
	fre.BudgetConfigID,
	fre.EntityGroupConfigID,
	fre.EntityID,
	fre.PatientClassID, 
	fre.ServiceLineID,
	fre.ServiceLineRollupID,
	fre.MedicalSurgicalID,
	fre.PayorID, 
	fre.PayorGroupID,
	fre.MSDRGID,
	fre.CPTID,
	1 AS TimeClassID,
	bc.FiscalYearID - 2 AS FiscalYearID,
	sum(freh.PriorYearActualNetReimbursementValue01) AS NetReimbursementValue01,
	sum(freh.PriorYearActualNetReimbursementValue02) AS NetReimbursementValue02,
	sum(freh.PriorYearActualNetReimbursementValue03) AS NetReimbursementValue03,
	sum(freh.PriorYearActualNetReimbursementValue04) AS NetReimbursementValue04,
	sum(freh.PriorYearActualNetReimbursementValue05) AS NetReimbursementValue05,
	sum(freh.PriorYearActualNetReimbursementValue06) AS NetReimbursementValue06,
	sum(freh.PriorYearActualNetReimbursementValue07) AS NetReimbursementValue07,
	sum(freh.PriorYearActualNetReimbursementValue08) AS NetReimbursementValue08,
	sum(freh.PriorYearActualNetReimbursementValue09) AS NetReimbursementValue09,
	sum(freh.PriorYearActualNetReimbursementValue10) AS NetReimbursementValue10,
	sum(freh.PriorYearActualNetReimbursementValue11) AS NetReimbursementValue11,
	sum(freh.PriorYearActualNetReimbursementValue12) AS NetReimbursementValue12
FROM fp.FactReimbursementEncounter fre 
JOIN fp.FactReimbursementEncounterHistory freh
	ON fre.ReimbursementEncounterID = freh.ReimbursementEncounterID
JOIN fp.BudgetConfig bc on fre.BudgetConfigID = bc.BudgetConfigID
GROUP BY
	fre.BudgetConfigID,
	fre.EntityGroupConfigID,
	fre.EntityID,
	fre.PatientClassID, 
	fre.ServiceLineID,
	fre.ServiceLineRollupID,
	fre.MedicalSurgicalID,
	fre.PayorID, 
	fre.PayorGroupID,
	fre.MSDRGID,
	fre.CPTID,
	bc.FiscalYearID
GO


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

-- fp.viewFactReimbursementEncounters_Unpivoted_source
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2022-10-13   MD      JAZZ-32897		Adding union all for data transfer table
*************************************************************/
CREATE VIEW fp.viewFactReimbursementEncounters_Unpivoted_source
AS
	SELECT 
		fre.BudgetConfigID,
		fre.EntityGroupConfigID,
		fre.EntityID,
		fre.PatientClassID, 
		fre.ServiceLineID,
		fre.ServiceLineRollupID,
		fre.MedicalSurgicalID,
		fre.PayorID, 
		fre.PayorGroupID,
		fre.MSDRGID,
		fre.CPTID,
		2 AS TimeClassID,
		bc.FiscalYearID AS FiscalYearID,
		sum(freb.AdjustedNetReimbursementValue01) AS NetReimbursementValue01,
		sum(freb.AdjustedNetReimbursementValue02) AS NetReimbursementValue02,
		sum(freb.AdjustedNetReimbursementValue03) AS NetReimbursementValue03,
		sum(freb.AdjustedNetReimbursementValue04) AS NetReimbursementValue04,
		sum(freb.AdjustedNetReimbursementValue05) AS NetReimbursementValue05,
		sum(freb.AdjustedNetReimbursementValue06) AS NetReimbursementValue06,
		sum(freb.AdjustedNetReimbursementValue07) AS NetReimbursementValue07,
		sum(freb.AdjustedNetReimbursementValue08) AS NetReimbursementValue08,
		sum(freb.AdjustedNetReimbursementValue09) AS NetReimbursementValue09,
		sum(freb.AdjustedNetReimbursementValue10) AS NetReimbursementValue10,
		sum(freb.AdjustedNetReimbursementValue11) AS NetReimbursementValue11,
		sum(freb.AdjustedNetReimbursementValue12) AS NetReimbursementValue12
	FROM fp.FactReimbursementEncounter fre 
	JOIN fp.FactReimbursementEncounterBudget freb
		ON fre.ReimbursementEncounterID = freb.ReimbursementEncounterID
	JOIN fp.BudgetConfig bc on fre.BudgetConfigID = bc.BudgetConfigID
	WHERE freb.BudgetPhaseID = 3
	GROUP BY
		fre.BudgetConfigID,
		fre.EntityGroupConfigID,
		fre.EntityID,
		fre.PatientClassID, 
		fre.ServiceLineID,
		fre.ServiceLineRollupID,
		fre.MedicalSurgicalID,
		fre.PayorID, 
		fre.PayorGroupID,
		fre.MSDRGID,
		fre.CPTID,
		bc.FiscalYearID

	UNION ALL

	SELECT 
		fre.BudgetConfigID,
		fre.EntityGroupConfigID,
		fre.EntityID,
		fre.PatientClassID, 
		fre.ServiceLineID,
		fre.ServiceLineRollupID,
		fre.MedicalSurgicalID,
		fre.PayorID, 
		fre.PayorGroupID,
		fre.MSDRGID,
		fre.CPTID,
		12 AS TimeClassID,
		bc.FiscalYearID - 1 AS FiscalYearID,
		sum(frep.AdjustedNetReimbursementValue01) AS NetReimbursementValue01,
		sum(frep.AdjustedNetReimbursementValue02) AS NetReimbursementValue02,
		sum(frep.AdjustedNetReimbursementValue03) AS NetReimbursementValue03,
		sum(frep.AdjustedNetReimbursementValue04) AS NetReimbursementValue04,
		sum(frep.AdjustedNetReimbursementValue05) AS NetReimbursementValue05,
		sum(frep.AdjustedNetReimbursementValue06) AS NetReimbursementValue06,
		sum(frep.AdjustedNetReimbursementValue07) AS NetReimbursementValue07,
		sum(frep.AdjustedNetReimbursementValue08) AS NetReimbursementValue08,
		sum(frep.AdjustedNetReimbursementValue09) AS NetReimbursementValue09,
		sum(frep.AdjustedNetReimbursementValue10) AS NetReimbursementValue10,
		sum(frep.AdjustedNetReimbursementValue11) AS NetReimbursementValue11,
		sum(frep.AdjustedNetReimbursementValue12) AS NetReimbursementValue12
	FROM fp.FactReimbursementEncounter fre 
	JOIN fp.FactReimbursementEncounterProjection frep
		ON fre.ReimbursementEncounterID = frep.ReimbursementEncounterID
	JOIN fp.BudgetConfig bc on fre.BudgetConfigID = bc.BudgetConfigID
	WHERE frep.BudgetPhaseID = 3
	GROUP BY
		fre.BudgetConfigID,
		fre.EntityGroupConfigID,
		fre.EntityID,
		fre.PatientClassID, 
		fre.ServiceLineID,
		fre.ServiceLineRollupID,
		fre.MedicalSurgicalID,
		fre.PayorID, 
		fre.PayorGroupID,
		fre.MSDRGID,
		fre.CPTID,
		bc.FiscalYearID
GO


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

-- fp.viewFactReimbursementProjection_repo
CREATE VIEW fp.viewFactReimbursementProjection_repo
AS
	SELECT
		budg.RowID,
		budg.ReimbursementChargesID AS ReimbursementID,
		budg.BudgetPhaseID,
		frc.BudgetConfigID,
		frc.EntityID,
		frc.PatientClassID,
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.PayorID,
		frc.PayorGroupID,
		frc.MedicalSurgicalID,
		frc.MSDRGID,
		frc.PrimaryCPTID AS CPTID,
		frc.UBRevCodeID,
		budg.LockFlag,
		budg.LockType,
		CAST(12 AS TINYINT) AS TimeClassID,
		6 AS SubsectionID, -- Charges
	
		budg.AdjustedNetAsPercentOfCharge01 AS RateAdjustedValue01,
		budg.AdjustedNetAsPercentOfCharge02 AS RateAdjustedValue02,
		budg.AdjustedNetAsPercentOfCharge03 AS RateAdjustedValue03,
		budg.AdjustedNetAsPercentOfCharge04 AS RateAdjustedValue04,
		budg.AdjustedNetAsPercentOfCharge05 AS RateAdjustedValue05,
		budg.AdjustedNetAsPercentOfCharge06 AS RateAdjustedValue06,
		budg.AdjustedNetAsPercentOfCharge07 AS RateAdjustedValue07,
		budg.AdjustedNetAsPercentOfCharge08 AS RateAdjustedValue08,
		budg.AdjustedNetAsPercentOfCharge09 AS RateAdjustedValue09,
		budg.AdjustedNetAsPercentOfCharge10 AS RateAdjustedValue10,
		budg.AdjustedNetAsPercentOfCharge11 AS RateAdjustedValue11,
		budg.AdjustedNetAsPercentOfCharge12 AS RateAdjustedValue12,
		
		budg.AdjustedChargeDollars01 AS VolumeAdjustedValue01,
		budg.AdjustedChargeDollars02 AS VolumeAdjustedValue02,
		budg.AdjustedChargeDollars03 AS VolumeAdjustedValue03,
		budg.AdjustedChargeDollars04 AS VolumeAdjustedValue04,
		budg.AdjustedChargeDollars05 AS VolumeAdjustedValue05,
		budg.AdjustedChargeDollars06 AS VolumeAdjustedValue06,
		budg.AdjustedChargeDollars07 AS VolumeAdjustedValue07,
		budg.AdjustedChargeDollars08 AS VolumeAdjustedValue08,
		budg.AdjustedChargeDollars09 AS VolumeAdjustedValue09,
		budg.AdjustedChargeDollars10 AS VolumeAdjustedValue10,
		budg.AdjustedChargeDollars11 AS VolumeAdjustedValue11,
		budg.AdjustedChargeDollars12 AS VolumeAdjustedValue12,
		
		budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01,
		budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02,
		budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03,
		budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04,
		budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05,
		budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06,
		budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07,
		budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08,
		budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09,
		budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10,
		budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11,
		budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12
	FROM fp.FactReimbursementCharges frc
		INNER JOIN fp.FactReimbursementChargesProjection budg ON frc.ReimbursementChargesID = budg.ReimbursementChargesID
	WHERE budg.BudgetPhaseID = 3
	UNION ALL
	SELECT
		budg.RowID,
		budg.ReimbursementEncounterID AS ReimbursementID,
		budg.BudgetPhaseID,
		frc.BudgetConfigID,
		frc.EntityID,
		frc.PatientClassID,
		frc.ServiceLineID,
		frc.ServiceLineRollupID,
		frc.PayorID,
		frc.PayorGroupID,
		frc.MedicalSurgicalID,
		frc.MSDRGID,
		frc.CPTID,
		0 AS UBRevCodeID,
		budg.LockFlag,
		budg.LockType,
		CAST(12 AS TINYINT) AS TimeClassID,
		5 AS SubsectionID, -- Encounters
	
		budg.AdjustedNetPerEncounterValue01 AS RateAdjustedValue01,
		budg.AdjustedNetPerEncounterValue02 AS RateAdjustedValue02,
		budg.AdjustedNetPerEncounterValue03 AS RateAdjustedValue03,
		budg.AdjustedNetPerEncounterValue04 AS RateAdjustedValue04,
		budg.AdjustedNetPerEncounterValue05 AS RateAdjustedValue05,
		budg.AdjustedNetPerEncounterValue06 AS RateAdjustedValue06,
		budg.AdjustedNetPerEncounterValue07 AS RateAdjustedValue07,
		budg.AdjustedNetPerEncounterValue08 AS RateAdjustedValue08,
		budg.AdjustedNetPerEncounterValue09 AS RateAdjustedValue09,
		budg.AdjustedNetPerEncounterValue10 AS RateAdjustedValue10,
		budg.AdjustedNetPerEncounterValue11 AS RateAdjustedValue11,
		budg.AdjustedNetPerEncounterValue12 AS RateAdjustedValue12,
		
		budg.AdjustedEncounters01 AS VolumeAdjustedValue01,
		budg.AdjustedEncounters02 AS VolumeAdjustedValue02,
		budg.AdjustedEncounters03 AS VolumeAdjustedValue03,
		budg.AdjustedEncounters04 AS VolumeAdjustedValue04,
		budg.AdjustedEncounters05 AS VolumeAdjustedValue05,
		budg.AdjustedEncounters06 AS VolumeAdjustedValue06,
		budg.AdjustedEncounters07 AS VolumeAdjustedValue07,
		budg.AdjustedEncounters08 AS VolumeAdjustedValue08,
		budg.AdjustedEncounters09 AS VolumeAdjustedValue09,
		budg.AdjustedEncounters10 AS VolumeAdjustedValue10,
		budg.AdjustedEncounters11 AS VolumeAdjustedValue11,
		budg.AdjustedEncounters12 AS VolumeAdjustedValue12,
		
		budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01,
		budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02,
		budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03,
		budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04,
		budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05,
		budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06,
		budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07,
		budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08,
		budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09,
		budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10,
		budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11,
		budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12
	FROM fp.FactReimbursementEncounter frc
		INNER JOIN fp.FactReimbursementEncounterProjection budg ON frc.ReimbursementEncounterID = budg.ReimbursementEncounterID
	WHERE budg.BudgetPhaseID = 3
GO


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

-- fp.viewFactReimbursement_Unpivoted
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2022-10-13   MD      JAZZ-32897		Adding union all for data transfer table
*************************************************************/
CREATE VIEW fp.viewFactReimbursement_Unpivoted
AS
	SELECT 
		fr.BudgetConfigID,
		fr.EntityID,
		fr.PatientClassID,
		fr.PayorID,
		fr.PayorGroupID,
		fr.ServiceLineID,
		fr.ServiceLineRollupID,
		fr.MSDRGID,
		fr.MedicalSurgicalID,
		fr.PrimaryCPTID,
		fr.UnitTypeID, 
		fr.TimeClassID,
		fr.FiscalYearID,
		fr.FiscalMonthID,
		fr.Value as Total
	FROM fp.FactReportReimbursement fr
GO


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

-- fp.viewFactReportAdjustmentsHistory
CREATE VIEW [fp].[viewFactReportAdjustmentsHistory]
AS
SELECT	
	RowID,
	SectionID,
	CASE	WHEN AdjustmentType = 0                     THEN 'Incremental'
			WHEN AdjustmentType = 1                     THEN 'Percent'
			WHEN AdjustmentType = 2                     THEN 'Set Value'
			WHEN AdjustmentType = 3                     THEN 'Final'
			WHEN AdjustmentType = 4                     THEN 'Import'
			WHEN AdjustmentType = 5                     THEN 'Mix'
			WHEN AdjustmentType = 6                     THEN 'Add FTE'
			WHEN AdjustmentType = 7                     THEN 'My Budgets'
			WHEN AdjustmentType = 8                     THEN 'Set Value'
			WHEN AdjustmentType = 9                     THEN 'Spread Unlock'
			WHEN AdjustmentType = 10                    THEN 'Lock'
			WHEN AdjustmentType = 11                    THEN 'Unlock'
			WHEN AdjustmentType = 12                    THEN 'Set Value'
			WHEN AdjustmentType = 13                    THEN 'Final Value'
			WHEN AdjustmentType = 14                    THEN 'Incremental'
			WHEN AdjustmentType = 15                    THEN 'Add Provider'
			WHEN AdjustmentType = 16 AND IsSetValue = 0 THEN 'My Budgets Itemized'
			WHEN AdjustmentType = 16 AND IsSetValue = 1 THEN 'My Budgets'
			WHEN AdjustmentType = 17                    THEN 'Add Employee'
			WHEN AdjustmentType = 18                    THEN 'Sub-Account Detail'
			WHEN AdjustmentType = 19                    THEN 'Add Account'
			WHEN AdjustmentType = 20                    THEN 'My Budgets'
		   ELSE ''
		  END AS [Adjustment Type], 
	Months, 
	AdjustmentValue AS [Adjustment Value], 
	AdjustedLevel AS [Adjustment Level], 
	UnitTypeID, 
	TimeClassID, 
	CAST(LastModifiedDateUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' AS DateTime) AS [Date/time last edited], 
	CAST(DateCreatedUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' AS DateTime) AS [Date/time created], 
	Comment,
	AuthorFullName AS [Author Full Name], 
	ClassificationGroupID, 
	ClassificationCategoryID, 
	IsErrored, 
	IsRecordDeleted AS IsDeleted
FROM fp.FactReportAdjustmentHistory
GO


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

-- fp.viewFactReportChargeVolume
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	6-12-2023  MY      JAZZ-54952		Projection data for charges data source not populating
*************************************************************/
CREATE   VIEW fp.viewFactReportChargeVolume
AS
	SELECT
		[BudgetConfigID],
		[EntityID],
		[DepartmentID],
		[ServiceLineID],
		[PatientClassID],
		[AgeCohortID],
		[MedicalSurgicalID],
		[ChargeCodeID],
		[ServiceEntityID],
		[MSDRGID],
		[UBRevCodeID],
		[PrimaryCPTID],
		[ServiceProviderID],
		[ServiceProviderSpecialtyID],
		[PerformingProviderID],
		[PerformingProviderSpecialtyID],
		[BillingCPTID],
		[UnitTypeID],
		[InitialBudget01] AS [Initial Month 01],
		[InitialBudget02] AS [Initial Month 02],
		[InitialBudget03] AS [Initial Month 03],
		[InitialBudget04] AS [Initial Month 04],
		[InitialBudget05] AS [Initial Month 05],
		[InitialBudget06] AS [Initial Month 06],
		[InitialBudget07] AS [Initial Month 07],
		[InitialBudget08] AS [Initial Month 08],
		[InitialBudget09] AS [Initial Month 09],
		[InitialBudget10] AS [Initial Month 10],
		[InitialBudget11] AS [Initial Month 11],
		[InitialBudget12] AS [Initial Month 12],
		[InitialBudgetTotal] AS [Initial Total],
		[Target01] AS [Target Month 01],
		[Target02] AS [Target Month 02],
		[Target03] AS [Target Month 03],
		[Target04] AS [Target Month 04],
		[Target05] AS [Target Month 05],
		[Target06] AS [Target Month 06],
		[Target07] AS [Target Month 07],
		[Target08] AS [Target Month 08],
		[Target09] AS [Target Month 09],
		[Target10] AS [Target Month 10],
		[Target11] AS [Target Month 11],
		[Target12] AS [Target Month 12],
		[TargetTotal] AS [Target Total],
		[Budget01] AS [Budget Month 01],
		[Budget02] AS [Budget Month 02],
		[Budget03] AS [Budget Month 03],
		[Budget04] AS [Budget Month 04],
		[Budget05] AS [Budget Month 05],
		[Budget06] AS [Budget Month 06],
		[Budget07] AS [Budget Month 07],
		[Budget08] AS [Budget Month 08],
		[Budget09] AS [Budget Month 09],
		[Budget10] AS [Budget Month 10],
		[Budget11] AS [Budget Month 11],
		[Budget12] AS [Budget Month 12],
		[BudgetTotal] AS [Budget Total],
		[Projection01] AS [Projection Month 01],
		[Projection02] AS [Projection Month 02],
		[Projection03] AS [Projection Month 03],
		[Projection04] AS [Projection Month 04],
		[Projection05] AS [Projection Month 05],
		[Projection06] AS [Projection Month 06],
		[Projection07] AS [Projection Month 07],
		[Projection08] AS [Projection Month 08],
		[Projection09] AS [Projection Month 09],
		[Projection10] AS [Projection Month 10],
		[Projection11] AS [Projection Month 11],
		[Projection12] AS [Projection Month 12],
		[ProjectionTotal] AS [Projection Total]
	FROM [fp].[FactReportChargeVolume]
GO


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

-- fp.viewFactReportChargesNotCrosswalkedData
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	05-19-2023  MY      JAZZ-54654		Initial
** 2	07-11-2023  MY      JAZZ-57364		Add PayorGroupID
*************************************************************/
CREATE   VIEW fp.viewFactReportChargesNotCrosswalkedData
AS
	SELECT
		DepartmentID,
		ChargeCodeID,
		PatientClassID,
		BudgetConfigID,
		PayorGroupID,
		ProjectionDollarsAdjustedTotal AS 'Projection Total',
		TargetDollarsAdjustedTotal AS 'Target Total',
		BudgetDollarsAdjustedTotal AS 'Budget Total'
	FROM fp.FactReportChargesNotCrosswalkedData
GO


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

-- fp.viewFactReportEncountersToChargeDollars
CREATE   VIEW fp.viewFactReportEncountersToChargeDollars
AS
SELECT
	BudgetConfigID, 
	ServiceEntityID, 
	EntityID, 
	PatientClassID, 
	AgeCohortID, 
	MedicalSurgicalID, 
	MSDRGID, 
	PrimaryCPTID, 
	ServiceProviderID, 
	ServiceProviderSpecialtyID, 
	ServiceLineID, 
	ServiceLineRollupID, 
	DepartmentID, 
	UBRevCodeID, 
	PayorID, 
	PayorGroupID, 
	TimeClassID, 
	AdjustmentID, 
	AdjustmentDate, 
	AdjustmentAuthor, 
	AdjustmentClassificationCategoryID, 
	AdjustmentClassificationGroupID, 
	AdjustmentComment, 
	dc.CalendarDateTime as AdjustmentCreatedDate,
	DollarImpact01 AS [Dollar Impact Month01], 
	DollarImpact02 AS [Dollar Impact Month02], 
	DollarImpact03 AS [Dollar Impact Month03], 
	DollarImpact04 AS [Dollar Impact Month04], 
	DollarImpact05 AS [Dollar Impact Month05], 
	DollarImpact06 AS [Dollar Impact Month06], 
	DollarImpact07 AS [Dollar Impact Month07], 
	DollarImpact08 AS [Dollar Impact Month08], 
	DollarImpact09 AS [Dollar Impact Month09], 
	DollarImpact10 AS [Dollar Impact Month10], 
	DollarImpact11 AS [Dollar Impact Month11], 
	DollarImpact12 AS [Dollar Impact Month12],
	DollarImpactTotal AS [Dollar Impact Total]
FROM fp.FactReportEncountersToChargeDollars ec
	INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime
UNION ALL
SELECT
	BudgetConfigID, 
	ServiceEntityID, 
	EntityID, 
	PatientClassID, 
	AgeCohortID, 
	MedicalSurgicalID, 
	MSDRGID, 
	PrimaryCPTID, 
	ServiceProviderID, 
	ServiceProviderSpecialtyID, 
	ServiceLineID, 
	ServiceLineRollupID, 
	DepartmentID, 
	UBRevCodeID, 
	PayorID, 
	PayorGroupID, 
	TimeClassID, 
	AdjustmentID, 
	AdjustmentDate, 
	AdjustmentAuthor, 
	AdjustmentClassificationCategoryID, 
	AdjustmentClassificationGroupID, 
	AdjustmentComment, 
	dc.CalendarDateTime as AdjustmentCreatedDate,
	DollarImpact01 AS [Dollar Impact Month01], 
	DollarImpact02 AS [Dollar Impact Month02], 
	DollarImpact03 AS [Dollar Impact Month03], 
	DollarImpact04 AS [Dollar Impact Month04], 
	DollarImpact05 AS [Dollar Impact Month05], 
	DollarImpact06 AS [Dollar Impact Month06], 
	DollarImpact07 AS [Dollar Impact Month07], 
	DollarImpact08 AS [Dollar Impact Month08], 
	DollarImpact09 AS [Dollar Impact Month09], 
	DollarImpact10 AS [Dollar Impact Month10], 
	DollarImpact11 AS [Dollar Impact Month11], 
	DollarImpact12 AS [Dollar Impact Month12],
	DollarImpactTotal AS [Dollar Impact Total]
FROM fp.FactReportEncountersToChargeDollars_Initial ec
	INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime
GO


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

-- fp.viewFactReportEncountersToStats
CREATE VIEW [fp].[viewFactReportEncountersToStats]
AS
SELECT BudgetConfigID, 
	ServiceEntityID, 
	EntityID, 
	PatientClassID,
	AgeCohortID,
	MedicalSurgicalID,
	MSDRGID,
	PrimaryCPTID,
 	PerformingProviderID,
	ProviderID,
	DepartmentID,
	AccountID,
	PayorID,
	FinancialReportingID,
	TimeClassID,
	FiscalMonthID,
	AdjustmentID,
	AdjustmentDate,
	AdjustmentAuthor,
	AdjustmentClassificationCategoryID,
	AdjustmentClassificationGroupID,
	AdjustmentComment,
	StatisticsImpact, 
	EncountersImpact, 
	ChargeVolumeImpact, 
	dc.CalendarDateTime as AdjustmentCreatedDate,
	ServiceLineID,
	ServiceLineRollupID
FROM fp.FactReportEncountersToStats ec
INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime
UNION ALL
SELECT BudgetConfigID, 
	ServiceEntityID, 
	EntityID, 
	PatientClassID,
	AgeCohortID,
	MedicalSurgicalID,
	MSDRGID,
	PrimaryCPTID,
 	PerformingProviderID,
	ProviderID,
	DepartmentID,
	AccountID,
	PayorID,
	FinancialReportingID,
	TimeClassID,
	FiscalMonthID,
	AdjustmentID,
	AdjustmentDate,
	AdjustmentAuthor,
	AdjustmentClassificationCategoryID,
	AdjustmentClassificationGroupID,
	AdjustmentComment,
	StatisticsImpact, 
	EncountersImpact, 
	ChargeVolumeImpact, 
	dc.CalendarDateTime as AdjustmentCreatedDate,
	ServiceLineID,
	ServiceLineRollupID
FROM fp.FactReportEncountersToStats_Initial ec
INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime
GO


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

-- fp.viewFactServiceLineEncounterInitialValue_Unpivoted
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    10-19-2020  MY      JAZZ-6489	Created Initial Value view to retrieve the initial value unpivoted from FactServiceLineEncounters
** 2    05-18-2023  MY      JAZZ-55153	Update to new structure
*************************************************************/
CREATE   VIEW fp.viewFactServiceLineEncounterInitialValue_Unpivoted
AS
SELECT
	initial.ServiceLineEncounterID, 
	initial.BudgetConfigID, 
	initial.EntityGroupConfigID, 
	initial.EntityID, 
	initial.PatientClassID, 
	initial.ServiceLineID, 
	initial.ServiceLineRollupID, 
	initial.AgeCohortID, 
	initial.MedicalSurgicalID, 
	initial.DepartmentID, 
	initial.PayorID, 
	initial.PayorGroupID, 
	initial.MSDRGID, 
	initial.CPTID, 
	initial.ProviderID, 
	initial.PhysicianSpecialtyID,
	initial.UnitTypeID, 
	2 as TimeClassID,
	initial.FiscalMonthID,
	initial.InitialValue AS InitialValue
FROM (
		SELECT 
			ServiceLineEncounterID, 
			BudgetConfigID, 
			EntityGroupConfigID, 
			EntityID, 
			PatientClassID, 
			ServiceLineID, 
			ServiceLineRollupID, 
			AgeCohortID, 
			MedicalSurgicalID, 
			DepartmentID, 
			PayorID, 
			PayorGroupID, 
			MSDRGID, 
			CPTID, 
			ProviderID, 
			PhysicianSpecialtyID, 
			UnitTypeID, 
			m.FiscalMonthID, 
			f.InitialValue
		FROM ( 
				SELECT 
					sle.ServiceLineEncounterID, 
					sle.BudgetConfigID, 
					sle.EntityGroupConfigID, 
					sle.EntityID, 
					sle.PatientClassID, 
					sle.ServiceLineID, 
					sle.ServiceLineRollupID, 
					sle.AgeCohortID, 
					sle.MedicalSurgicalID, 
					sle.DepartmentID, 
					sle.PayorID, 
					sle.PayorGroupID, 
					sle.MSDRGID, 
					sle.CPTID, 
					sle.ProviderID, 
					sle.PhysicianSpecialtyID, 
					sle.UnitTypeID, 
					sle.InitialBudget01, 
					sle.InitialBudget02, 
					sle.InitialBudget03, 
					sle.InitialBudget04, 
					sle.InitialBudget05, 
					sle.InitialBudget06, 
					sle.InitialBudget07, 
					sle.InitialBudget08, 
					sle.InitialBudget09, 
					sle.InitialBudget10, 
					sle.InitialBudget11, 
					sle.InitialBudget12
				FROM fp.ServiceLineEncounter sle 
				) sle
					UNPIVOT (
						InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)
					) as f
					LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')
			) initial
GO


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

-- fp.viewFactServiceLineEncounter_HistoryViewer
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	5-18-2023  MY      JAZZ-55153		Updated view to restructure
*************************************************************/
CREATE   VIEW fp.viewFactServiceLineEncounter_HistoryViewer
AS
SELECT
	ov.ServiceLineEncounterID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.PatientClassID, 
	ov.ServiceLineID, 
	ov.ServiceLineRollupID, 
	ov.AgeCohortID, 
	ov.MedicalSurgicalID, 
	ov.DepartmentID, 
	ov.PayorID, 
	ov.PayorGroupID, 
	ov.MSDRGID, 
	ov.CPTID, 
	ov.ProviderID, 
	ov.PhysicianSpecialtyID,
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT 
		ServiceLineEncounterID, 
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		PatientClassID, 
		ServiceLineID, 
		ServiceLineRollupID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		DepartmentID, 
		PayorID, 
		PayorGroupID, 
		MSDRGID, 
		CPTID, 
		ProviderID, 
		PhysicianSpecialtyID, 
		UnitTypeID, 
		m.FiscalMonthID, 
		f.InitialValue
	FROM (
		SELECT sle.*
		FROM fp.ServiceLineEncounter sle ) sle
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT 
		ServiceLineEncounterID, 
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		PatientClassID, 
		ServiceLineID, 
		ServiceLineRollupID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		DepartmentID, 
		PayorID, 
		PayorGroupID, 
		MSDRGID, 
		CPTID, 
		ProviderID, 
		PhysicianSpecialtyID, 
		UnitTypeID, 
		m.FiscalMonthID, 
		f.Value, 
		LockType
	FROM (
			SELECT sle.*, TargetLockType AS LockType, 
				sle.TargetAdjusted01 AS AdjustedValue01, sle.TargetAdjusted02 AS AdjustedValue02, sle.TargetAdjusted03 AS AdjustedValue03, sle.TargetAdjusted04 AS AdjustedValue04, 
				sle.TargetAdjusted05 AS AdjustedValue05, sle.TargetAdjusted06 AS AdjustedValue06, sle.TargetAdjusted07 AS AdjustedValue07, sle.TargetAdjusted08 AS AdjustedValue08, 
				sle.TargetAdjusted09 AS AdjustedValue09, sle.TargetAdjusted10 AS AdjustedValue10, sle.TargetAdjusted11 AS AdjustedValue11, sle.TargetAdjusted12 AS AdjustedValue12
			FROM fp.ServiceLineEncounter sle
		) sle
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
		AND ov.EntityGroupConfigID = v.EntityGroupConfigID
		AND ov.EntityID = v.EntityID
		AND ov.PatientClassID = v.PatientClassID
		AND ov.ServiceLineID = v.ServiceLineID
		AND ov.ServiceLineRollupID = v.ServiceLineRollupID
		AND ov.AgeCohortID = v.AgeCohortID
		AND ov.MedicalSurgicalID = v.MedicalSurgicalID
		AND ov.DepartmentID = v.DepartmentID
		AND ov.PayorID = v.PayorID
		AND ov.PayorGroupID = v.PayorGroupID
		AND ov.MSDRGID = v.MSDRGID 
		AND ov.CPTID = v.CPTID 
		AND ov.ProviderID = v.ProviderID
		AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID 
		AND ov.UnitTypeID = v.UnitTypeID
		AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT 
		ServiceLineEncounterID, 
		BudgetConfigID, 
		EntityGroupConfigID, 
		EntityID, 
		PatientClassID, 
		ServiceLineID, 
		ServiceLineRollupID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		DepartmentID, 
		PayorID, 
		PayorGroupID, 
		MSDRGID, 
		CPTID, 
		ProviderID, 
		PhysicianSpecialtyID,  
		UnitTypeID, 
		m.FiscalMonthID, 
		f.Value AS ManagerValue
	FROM (
			SELECT sle.*, BudgetLockType AS LockType, 
				sle.BudgetAdjusted01 AS AdjustedValue01, sle.BudgetAdjusted02 AS AdjustedValue02, sle.BudgetAdjusted03 AS AdjustedValue03, sle.BudgetAdjusted04 AS AdjustedValue04, 
				sle.BudgetAdjusted05 AS AdjustedValue05, sle.BudgetAdjusted06 AS AdjustedValue06, sle.BudgetAdjusted07 AS AdjustedValue07, sle.BudgetAdjusted08 AS AdjustedValue08, 
				sle.BudgetAdjusted09 AS AdjustedValue09, sle.BudgetAdjusted10 AS AdjustedValue10, sle.BudgetAdjusted11 AS AdjustedValue11, sle.BudgetAdjusted12 AS AdjustedValue12
			FROM fp.ServiceLineEncounter sle
		) sle
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
		AND ov.EntityGroupConfigID = mgrv.EntityGroupConfigID
		AND ov.EntityID = mgrv.EntityID
		AND ov.PatientClassID = mgrv.PatientClassID
		AND ov.ServiceLineID = mgrv.ServiceLineID
		AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID
		AND ov.AgeCohortID = mgrv.AgeCohortID
		AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID
		AND ov.DepartmentID = mgrv.DepartmentID
		AND ov.PayorID = mgrv.PayorID
		AND ov.PayorGroupID = mgrv.PayorGroupID
		AND ov.MSDRGID = mgrv.MSDRGID 
		AND ov.CPTID = mgrv.CPTID 
		AND ov.ProviderID = mgrv.ProviderID
		AND ov.PhysicianSpecialtyID = mgrv.PhysicianSpecialtyID 
		AND ov.UnitTypeID = mgrv.UnitTypeID
		AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactServiceLineEncounter_Pivoted
CREATE   VIEW [fp].[viewFactServiceLineEncounter_Pivoted]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2022-04-25   MD  	  JAZZ-20817    Remove Budget Phase 3 from projection in SLE
 ** 2 	 2023-05-19   MY  	  JAZZ-55153    Update to restructure
 *************************************************************/
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	sl.TargetLockType as TargetLockType,
	sl.TargetLockFlag as TargetLockFlag,
	sl.BudgetLockType as BudgetLockType,
	sl.BudgetLockFlag as BudgetLockFlag,
	sl.ProjectionLockType AS ProjectionLockType,
   	sl.ProjectionLockFlag AS ProjectionLockFlag,
	
	CASE WHEN sl.TargetLockType = 6 THEN 1 ELSE 0 END AS TargetSpreadsLockFlag,

	sl.TargetAdjustedTotal AS AdjustedValueTotal,
    sl.BudgetAdjustedTotal as ManagerAdjustedValueTotal,
    sl.ProjectionAdjustedTotal as AdjustedProjectionValueTotal,

    hist.PriorYearActualValueTotal as PriorYearActualValueTotal,
    hist.ActualYTDValueTotal as ActualYTDValueTotal,
    hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal,

	sl.SampledBudgetTotal,
    sl.InitialBudgetTotal,
    sl.InitialProjectionTotal,

    sl.TargetAdjusted01 AS AdjustedValue01, sl.TargetAdjusted02 AS AdjustedValue02, sl.TargetAdjusted03 AS AdjustedValue03, 
	sl.TargetAdjusted04 AS AdjustedValue04, sl.TargetAdjusted05 AS AdjustedValue05, sl.TargetAdjusted06 AS AdjustedValue06, 
	sl.TargetAdjusted07 AS AdjustedValue07, sl.TargetAdjusted08 AS AdjustedValue08, sl.TargetAdjusted09 AS AdjustedValue09, 
	sl.TargetAdjusted10 AS AdjustedValue10, sl.TargetAdjusted11 AS AdjustedValue11, sl.TargetAdjusted12 AS AdjustedValue12,

    sl.BudgetAdjusted01 AS ManagerAdjustedValue01, sl.BudgetAdjusted02 AS ManagerAdjustedValue02, sl.BudgetAdjusted03 AS ManagerAdjustedValue03, 
	sl.BudgetAdjusted04 AS ManagerAdjustedValue04, sl.BudgetAdjusted05 AS ManagerAdjustedValue05, sl.BudgetAdjusted06 AS ManagerAdjustedValue06, 
	sl.BudgetAdjusted07 AS ManagerAdjustedValue07, sl.BudgetAdjusted08 AS ManagerAdjustedValue08, sl.BudgetAdjusted09 AS ManagerAdjustedValue09, 
	sl.BudgetAdjusted10 AS ManagerAdjustedValue10, sl.BudgetAdjusted11 AS ManagerAdjustedValue11, sl.BudgetAdjusted12 AS ManagerAdjustedValue12,

    sl.ProjectionAdjusted01 AS AdjustedProjectionValue01, sl.ProjectionAdjusted02 AS AdjustedProjectionValue02, sl.ProjectionAdjusted03 AS AdjustedProjectionValue03, 
	sl.ProjectionAdjusted04 AS AdjustedProjectionValue04, sl.ProjectionAdjusted05 AS AdjustedProjectionValue05, sl.ProjectionAdjusted06 AS AdjustedProjectionValue06, 
	sl.ProjectionAdjusted07 AS AdjustedProjectionValue07, sl.ProjectionAdjusted08 AS AdjustedProjectionValue08, sl.ProjectionAdjusted09 AS AdjustedProjectionValue09, 
	sl.ProjectionAdjusted10 AS AdjustedProjectionValue10, sl.ProjectionAdjusted11 AS AdjustedProjectionValue11, sl.ProjectionAdjusted12 AS AdjustedProjectionValue12

From fp.ServiceLineEncounter sl
	INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewFactStaffingHistory
CREATE   VIEW [fp].[viewFactStaffingHistory]
AS
	-- Dollars
	SELECT
		fs.StaffingID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		34 AS UnitTypeID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderSpecialtyID,
		fs.ProviderTypeID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.AddDate,
		fs.SampledBudgetDollars01, 
		fs.SampledBudgetDollars02, 
		fs.SampledBudgetDollars03, 
		fs.SampledBudgetDollars04,
		fs.SampledBudgetDollars05,
		fs.SampledBudgetDollars06, 
		fs.SampledBudgetDollars07, 
		fs.SampledBudgetDollars08, 
		fs.SampledBudgetDollars09, 
		fs.SampledBudgetDollars10, 
		fs.SampledBudgetDollars11, 
		fs.SampledBudgetDollars12, 
		fs.SampledBudgetDollarsTotal,
		fs.SampledProjectionDollars01, 
		fs.SampledProjectionDollars02, 
		fs.SampledProjectionDollars03, 
		fs.SampledProjectionDollars04, 
		fs.SampledProjectionDollars05, 
		fs.SampledProjectionDollars06, 
		fs.SampledProjectionDollars07, 
		fs.SampledProjectionDollars08, 
		fs.SampledProjectionDollars09, 
		fs.SampledProjectionDollars10, 
		fs.SampledProjectionDollars11, 
		fs.SampledProjectionDollars12, 
		fs.SampledProjectionDollarsTotal,
		fs.InitialBudgetDollars01, 
		fs.InitialBudgetDollars02, 
		fs.InitialBudgetDollars03, 
		fs.InitialBudgetDollars04, 
		fs.InitialBudgetDollars05, 
		fs.InitialBudgetDollars06, 
		fs.InitialBudgetDollars07, 
		fs.InitialBudgetDollars08, 
		fs.InitialBudgetDollars09, 
		fs.InitialBudgetDollars10, 
		fs.InitialBudgetDollars11, 
		fs.InitialBudgetDollars12, 
		fs.InitialBudgetDollarsTotal,
		fs.InitialProjectionDollars01, 
		fs.InitialProjectionDollars02, 
		fs.InitialProjectionDollars03, 
		fs.InitialProjectionDollars04, 
		fs.InitialProjectionDollars05, 
		fs.InitialProjectionDollars06, 
		fs.InitialProjectionDollars07, 
		fs.InitialProjectionDollars08, 
		fs.InitialProjectionDollars09, 
		fs.InitialProjectionDollars10, 
		fs.InitialProjectionDollars11, 
		fs.InitialProjectionDollars12, 
		fs.InitialProjectionDollarsTotal,
		hist.PriorYearActualDollars01, 
		hist.PriorYearActualDollars02, 
		hist.PriorYearActualDollars03, 
		hist.PriorYearActualDollars04, 
		hist.PriorYearActualDollars05, 
		hist.PriorYearActualDollars06, 
		hist.PriorYearActualDollars07, 
		hist.PriorYearActualDollars08, 
		hist.PriorYearActualDollars09, 
		hist.PriorYearActualDollars10, 
		hist.PriorYearActualDollars11, 
		hist.PriorYearActualDollars12, 
		hist.PriorYearActualDollarsTotal,
		hist.ActualYTDDollars01, 
		hist.ActualYTDDollars02, 
		hist.ActualYTDDollars03, 
		hist.ActualYTDDollars04, 
		hist.ActualYTDDollars05, 
		hist.ActualYTDDollars06, 
		hist.ActualYTDDollars07, 
		hist.ActualYTDDollars08, 
		hist.ActualYTDDollars09, 
		hist.ActualYTDDollars10, 
		hist.ActualYTDDollars11, 
		hist.ActualYTDDollars12, 
		hist.ActualYTDDollarsTotal,
		hist.CurrentYearBudgetDollars01, 
		hist.CurrentYearBudgetDollars02, 
		hist.CurrentYearBudgetDollars03, 
		hist.CurrentYearBudgetDollars04, 
		hist.CurrentYearBudgetDollars05, 
		hist.CurrentYearBudgetDollars06, 
		hist.CurrentYearBudgetDollars07, 
		hist.CurrentYearBudgetDollars08, 
		hist.CurrentYearBudgetDollars09, 
		hist.CurrentYearBudgetDollars10, 
		hist.CurrentYearBudgetDollars11, 
		hist.CurrentYearBudgetDollars12, 
		hist.CurrentYearBudgetDollarsTotal
	FROM [fp].[Staffing] fs
		INNER JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID

	UNION

	-- Hours
	SELECT
		fs.StaffingID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		34 AS UnitTypeID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderSpecialtyID,
		fs.ProviderTypeID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.AddDate,
		fs.SampledBudgetHours01, 
		fs.SampledBudgetHours02, 
		fs.SampledBudgetHours03, 
		fs.SampledBudgetHours04,
		fs.SampledBudgetHours05,
		fs.SampledBudgetHours06, 
		fs.SampledBudgetHours07, 
		fs.SampledBudgetHours08, 
		fs.SampledBudgetHours09, 
		fs.SampledBudgetHours10, 
		fs.SampledBudgetHours11, 
		fs.SampledBudgetHours12, 
		fs.SampledBudgetHoursTotal,
		fs.SampledProjectionHours01, 
		fs.SampledProjectionHours02, 
		fs.SampledProjectionHours03, 
		fs.SampledProjectionHours04, 
		fs.SampledProjectionHours05, 
		fs.SampledProjectionHours06, 
		fs.SampledProjectionHours07, 
		fs.SampledProjectionHours08, 
		fs.SampledProjectionHours09, 
		fs.SampledProjectionHours10, 
		fs.SampledProjectionHours11, 
		fs.SampledProjectionHours12, 
		fs.SampledProjectionHoursTotal,
		fs.InitialBudgetHours01, 
		fs.InitialBudgetHours02, 
		fs.InitialBudgetHours03, 
		fs.InitialBudgetHours04, 
		fs.InitialBudgetHours05, 
		fs.InitialBudgetHours06, 
		fs.InitialBudgetHours07, 
		fs.InitialBudgetHours08, 
		fs.InitialBudgetHours09, 
		fs.InitialBudgetHours10, 
		fs.InitialBudgetHours11, 
		fs.InitialBudgetHours12, 
		fs.InitialBudgetHoursTotal,
		fs.InitialProjectionHours01, 
		fs.InitialProjectionHours02, 
		fs.InitialProjectionHours03, 
		fs.InitialProjectionHours04, 
		fs.InitialProjectionHours05, 
		fs.InitialProjectionHours06, 
		fs.InitialProjectionHours07, 
		fs.InitialProjectionHours08, 
		fs.InitialProjectionHours09, 
		fs.InitialProjectionHours10, 
		fs.InitialProjectionHours11, 
		fs.InitialProjectionHours12, 
		fs.InitialProjectionHoursTotal,
		hist.PriorYearActualHours01, 
		hist.PriorYearActualHours02, 
		hist.PriorYearActualHours03, 
		hist.PriorYearActualHours04, 
		hist.PriorYearActualHours05, 
		hist.PriorYearActualHours06, 
		hist.PriorYearActualHours07, 
		hist.PriorYearActualHours08, 
		hist.PriorYearActualHours09, 
		hist.PriorYearActualHours10, 
		hist.PriorYearActualHours11, 
		hist.PriorYearActualHours12, 
		hist.PriorYearActualHoursTotal,
		hist.ActualYTDHours01, 
		hist.ActualYTDHours02, 
		hist.ActualYTDHours03, 
		hist.ActualYTDHours04, 
		hist.ActualYTDHours05, 
		hist.ActualYTDHours06, 
		hist.ActualYTDHours07, 
		hist.ActualYTDHours08, 
		hist.ActualYTDHours09, 
		hist.ActualYTDHours10, 
		hist.ActualYTDHours11, 
		hist.ActualYTDHours12, 
		hist.ActualYTDHoursTotal,
		hist.CurrentYearBudgetHours01, 
		hist.CurrentYearBudgetHours02, 
		hist.CurrentYearBudgetHours03, 
		hist.CurrentYearBudgetHours04, 
		hist.CurrentYearBudgetHours05, 
		hist.CurrentYearBudgetHours06, 
		hist.CurrentYearBudgetHours07, 
		hist.CurrentYearBudgetHours08, 
		hist.CurrentYearBudgetHours09, 
		hist.CurrentYearBudgetHours10, 
		hist.CurrentYearBudgetHours11, 
		hist.CurrentYearBudgetHours12, 
		hist.CurrentYearBudgetHoursTotal
	FROM [fp].[Staffing] fs
		INNER JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID

	UNION
	
	SELECT
		fs.StaffingID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		144 as UnitTypeID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderSpecialtyID,
		fs.ProviderTypeID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.AddDate,
		fs.SampledBudgetFTEs01, 
		fs.SampledBudgetFTEs02, 
		fs.SampledBudgetFTEs03, 
		fs.SampledBudgetFTEs04, 
		fs.SampledBudgetFTEs05, 
		fs.SampledBudgetFTEs06, 
		fs.SampledBudgetFTEs07, 
		fs.SampledBudgetFTEs08, 
		fs.SampledBudgetFTEs09, 
		fs.SampledBudgetFTEs10, 
		fs.SampledBudgetFTEs11, 
		fs.SampledBudgetFTEs12,
		fs.SampledBudgetHoursTotal / whBudg.MonthYearly as SampledBudgetTotal,
		fs.SampledProjectionFTEs01, 
		fs.SampledProjectionFTEs02, 
		fs.SampledProjectionFTEs03, 
		fs.SampledProjectionFTEs04, 
		fs.SampledProjectionFTEs05, 
		fs.SampledProjectionFTEs06, 
		fs.SampledProjectionFTEs07, 
		fs.SampledProjectionFTEs08, 
		fs.SampledProjectionFTEs09, 
		fs.SampledProjectionFTEs10, 
		fs.SampledProjectionFTEs11, 
		fs.SampledProjectionFTEs12,
		fs.SampledProjectionHoursTotal / whBudg.MonthYearly as SampledProjectionTotal,
		fs.InitialBudgetFTEs01, 
		fs.InitialBudgetFTEs02, 
		fs.InitialBudgetFTEs03, 
		fs.InitialBudgetFTEs04, 
		fs.InitialBudgetFTEs05, 
		fs.InitialBudgetFTEs06, 
		fs.InitialBudgetFTEs07, 
		fs.InitialBudgetFTEs08, 
		fs.InitialBudgetFTEs09, 
		fs.InitialBudgetFTEs10,
		fs.InitialBudgetFTEs11, 
		fs.InitialBudgetFTEs12,
		fs.InitialBudgetHoursTotal / whBudg.MonthYearly as InitialBudgetTotal,
		fs.InitialProjectionFTEs01, 
		fs.InitialProjectionFTEs02, 
		fs.InitialProjectionFTEs03, 
		fs.InitialProjectionFTEs04, 
		fs.InitialProjectionFTEs05, 
		fs.InitialProjectionFTEs06, 
		fs.InitialProjectionFTEs07, 
		fs.InitialProjectionFTEs08, 
		fs.InitialProjectionFTEs09, 
		fs.InitialProjectionFTEs10, 
		fs.InitialProjectionFTEs11, 
		fs.InitialProjectionFTEs12,
		fs.InitialProjectionHoursTotal / whBudg.MonthYearly as InitialProjectionTotal,
		hist.PriorYearActualFTEs01, 
		hist.PriorYearActualFTEs02, 
		hist.PriorYearActualFTEs03, 
		hist.PriorYearActualFTEs04, 
		hist.PriorYearActualFTEs05, 
		hist.PriorYearActualFTEs06, 
		hist.PriorYearActualFTEs07, 
		hist.PriorYearActualFTEs08, 
		hist.PriorYearActualFTEs09, 
		hist.PriorYearActualFTEs10, 
		hist.PriorYearActualFTEs11, 
		hist.PriorYearActualFTEs12,
		hist.PriorYearActualHoursTotal / whPrior.MonthYearly as PriorYearActualValueTotal,
		hist.ActualYTDFTEs01, 
		hist.ActualYTDFTEs02, 
		hist.ActualYTDFTEs03, 
		hist.ActualYTDFTEs04, 
		hist.ActualYTDFTEs05, 
		hist.ActualYTDFTEs06, 
		hist.ActualYTDFTEs07, 
		hist.ActualYTDFTEs08, 
		hist.ActualYTDFTEs09, 
		hist.ActualYTDFTEs10, 
		hist.ActualYTDFTEs11, 
		hist.ActualYTDFTEs12,
		hist.ActualYTDHoursTotal / [dbo].[GetDaysInMonthsLoaded](bc.FiscalYearID - 2) as ActualYTDValueTotal,
		hist.CurrentYearBudgetFTEs01, 
		hist.CurrentYearBudgetFTEs02, 
		hist.CurrentYearBudgetFTEs03, 
		hist.CurrentYearBudgetFTEs04, 
		hist.CurrentYearBudgetFTEs05, 
		hist.CurrentYearBudgetFTEs06, 
		hist.CurrentYearBudgetFTEs07, 
		hist.CurrentYearBudgetFTEs08, 
		hist.CurrentYearBudgetFTEs09, 
		hist.CurrentYearBudgetFTEs10, 
		hist.CurrentYearBudgetFTEs11, 
		hist.CurrentYearBudgetFTEs12,
		hist.CurrentYearBudgetHoursTotal / whCurr.MonthYearly as CurrentYearBudgetTotal
	FROM [fp].[Staffing] fs
		INNER JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID
		INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN [client].[FactWorkingHoursPerMonth] whBudg ON whBudg.FiscalYearID = bc.FiscalYearID
		LEFT JOIN [client].[FactWorkingHoursPerMonth] whCurr ON whCurr.FiscalYearID = bc.FiscalYearID - 1
		LEFT JOIN [client].[FactWorkingHoursPerMonth] whPrior ON whPrior.FiscalYearID = bc.FiscalYearID - 2
GO


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

-- fp.viewFactStaffingHistory_Unpivoted
CREATE VIEW [fp].[viewFactStaffingHistory_Unpivoted] 
AS 
	SELECT
		BudgetConfigID,
		EntityGroupConfigID,
		EntityID,
		DepartmentID,
		JobCodeID,
		PayCodeGroupID,
		ProductiveClassID,
		VariabilityID, 
		UnitTypeID, 
		TimeClassID, 
		FiscalYearID,
		FiscalMonthID,
		Value,
		EmployeeID,
		ProviderID,
		ProviderLineItemID,
		ProviderTypeID,
		ProviderSpecialtyID
	FROM fp.FactReportStaffingHistory
GO


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

-- fp.viewFactStaffingHistory_Unpivoted_archive
CREATE VIEW fp.viewFactStaffingHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffingHistory_archive
GO


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

-- fp.viewFactStaffingHistory_Unpivoted_source
CREATE   VIEW [fp].[viewFactStaffingHistory_Unpivoted_source]
AS
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2023-11-14   BW        JAZZ-62798  New data model update
	*************************************************************/

SELECT
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	34 as UnitTypeID,
	TimeClassID,
	bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID,
	m.FiscalMonthID,
	hist.Value
FROM (
 SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, ActualYTDDollars01),
		(2, ActualYTDDollars02),
		(3, ActualYTDDollars03),
		(4, ActualYTDDollars04),
		(5, ActualYTDDollars05),
		(6, ActualYTDDollars06),
		(7, ActualYTDDollars07),
		(8, ActualYTDDollars08),
		(9, ActualYTDDollars09),
		(10,ActualYTDDollars10),
		(11,ActualYTDDollars11),
		(12,ActualYTDDollars12))	X (FiscalMonth,Value)
UNION
SELECT hist.StaffingID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, CurrentYearBudgetDollars01),
		(2, CurrentYearBudgetDollars02),
		(3, CurrentYearBudgetDollars03),
		(4, CurrentYearBudgetDollars04),
		(5, CurrentYearBudgetDollars05),
		(6, CurrentYearBudgetDollars06),
		(7, CurrentYearBudgetDollars07),
		(8, CurrentYearBudgetDollars08),
		(9, CurrentYearBudgetDollars09),
		(10,CurrentYearBudgetDollars10),
		(11,CurrentYearBudgetDollars11),
		(12,CurrentYearBudgetDollars12))	X (FiscalMonth,Value)
UNION
SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, PriorYearActualDollars01),
		(2, PriorYearActualDollars02),
		(3, PriorYearActualDollars03),
		(4, PriorYearActualDollars04),
		(5, PriorYearActualDollars05),
		(6, PriorYearActualDollars06),
		(7, PriorYearActualDollars07),
		(8, PriorYearActualDollars08),
		(9, PriorYearActualDollars09),
		(10,PriorYearActualDollars10),
		(11,PriorYearActualDollars11),
		(12,PriorYearActualDollars12))	X (FiscalMonth,Value) ) hist
INNER JOIN fp.Staffing fs (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
    INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth
    INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

UNION ALL

SELECT
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	51 as UnitTypeID,
	TimeClassID,
	bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID,
	m.FiscalMonthID,
	hist.Value
FROM (
 SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, ActualYTDHours01),
		(2, ActualYTDHours02),
		(3, ActualYTDHours03),
		(4, ActualYTDHours04),
		(5, ActualYTDHours05),
		(6, ActualYTDHours06),
		(7, ActualYTDHours07),
		(8, ActualYTDHours08),
		(9, ActualYTDHours09),
		(10,ActualYTDHours10),
		(11,ActualYTDHours11),
		(12,ActualYTDHours12))	X (FiscalMonth,Value)
UNION
SELECT hist.StaffingID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, CurrentYearBudgetHours01),
		(2, CurrentYearBudgetHours02),
		(3, CurrentYearBudgetHours03),
		(4, CurrentYearBudgetHours04),
		(5, CurrentYearBudgetHours05),
		(6, CurrentYearBudgetHours06),
		(7, CurrentYearBudgetHours07),
		(8, CurrentYearBudgetHours08),
		(9, CurrentYearBudgetHours09),
		(10,CurrentYearBudgetHours10),
		(11,CurrentYearBudgetHours11),
		(12,CurrentYearBudgetHours12))	X (FiscalMonth,Value)
UNION
SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, PriorYearActualHours01),
		(2, PriorYearActualHours02),
		(3, PriorYearActualHours03),
		(4, PriorYearActualHours04),
		(5, PriorYearActualHours05),
		(6, PriorYearActualHours06),
		(7, PriorYearActualHours07),
		(8, PriorYearActualHours08),
		(9, PriorYearActualHours09),
		(10,PriorYearActualHours10),
		(11,PriorYearActualHours11),
		(12,PriorYearActualHours12))	X (FiscalMonth,Value) ) hist
INNER JOIN fp.Staffing fs (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
    INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth
    INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

UNION ALL

SELECT
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	144 as UnitTypeID,
	TimeClassID,
	bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID,
	m.FiscalMonthID,
	hist.Value
FROM (
 SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, ActualYTDFTEs01),
		(2, ActualYTDFTEs02),
		(3, ActualYTDFTEs03),
		(4, ActualYTDFTEs04),
		(5, ActualYTDFTEs05),
		(6, ActualYTDFTEs06),
		(7, ActualYTDFTEs07),
		(8, ActualYTDFTEs08),
		(9, ActualYTDFTEs09),
		(10,ActualYTDFTEs10),
		(11,ActualYTDFTEs11),
		(12,ActualYTDFTEs12))	X (FiscalMonth,Value)
UNION
SELECT hist.StaffingID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, CurrentYearBudgetFTEs01),
		(2, CurrentYearBudgetFTEs02),
		(3, CurrentYearBudgetFTEs03),
		(4, CurrentYearBudgetFTEs04),
		(5, CurrentYearBudgetFTEs05),
		(6, CurrentYearBudgetFTEs06),
		(7, CurrentYearBudgetFTEs07),
		(8, CurrentYearBudgetFTEs08),
		(9, CurrentYearBudgetFTEs09),
		(10,CurrentYearBudgetFTEs10),
		(11,CurrentYearBudgetFTEs11),
		(12,CurrentYearBudgetFTEs12))	X (FiscalMonth,Value)
UNION
SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear 
 FROM fp.StaffingHistory hist (READUNCOMMITTED) 
		CROSS APPLY 
		(VALUES 
		(1, PriorYearActualFTEs01),
		(2, PriorYearActualFTEs02),
		(3, PriorYearActualFTEs03),
		(4, PriorYearActualFTEs04),
		(5, PriorYearActualFTEs05),
		(6, PriorYearActualFTEs06),
		(7, PriorYearActualFTEs07),
		(8, PriorYearActualFTEs08),
		(9, PriorYearActualFTEs09),
		(10,PriorYearActualFTEs10),
		(11,PriorYearActualFTEs11),
		(12,PriorYearActualFTEs12))	X (FiscalMonth,Value) ) hist
INNER JOIN fp.Staffing fs (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
    INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth
    INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactStaffingVariability
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2022-04-28	MY		JAZZ-28395	Cache Variability Percentage on FactStaffing
** 2	2022-10-18	MD		JAZZ-44889	Add EGC ID to view
** 3	2022-11-07   MY      JAZZ-35951	Add EmployeeID to FactStaffingVariabilityDetail
** 4	2023-09-20   BK      JAZZ-60973	Update for new data structure
*************************************************************/
CREATE VIEW [fp].[viewFactStaffingVariability]
AS
SELECT DISTINCT
	pv.BudgetConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.SubsectionID,
	pv.DepartmentID, 
	pv.ProviderLineItemID,
	pv.JobCodeID,
	pv.PayCodeGroupID,
	pv.EmployeeID,
	pv.EntityGroupConfigID,
	ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage
FROM [fp].[Staffing] pv
	INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID
WHERE pv.VariabilityID = 2
GROUP BY pv.BudgetConfigID, 
	pv.EntityGroupConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.SubsectionID,
	pv.DepartmentID, 
	pv.JobCodeID,
	pv.ProviderLineItemID,
	pv.PayCodeGroupID,
	pv.EmployeeID
GO


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

-- fp.viewFactStaffingVariabilityForAdjustments
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	11-07-2022  MY      JAZZ-35951		Add EmployeeID to FactStaffingVariabilityDetail
** 2	01-03-2023  MY      JAZZ-63564		Final Pass Of Fact References (SQL)
*************************************************************/
CREATE   VIEW [fp].[viewFactStaffingVariabilityForAdjustments]
AS
SELECT DISTINCT
	bc.BudgetConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.DepartmentID, 
	pv.JobCodeID, -- Eventually need to add PayCodeGroup level here for when ABB clients use this.
	ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage
FROM [fp].[Staffing] pv
	INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
	INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID
WHERE pv.ProviderLineItemID = 0 -- Filtering out Provider Line Item lvl variability because they don't have manager adjustments. 
	AND pv.VariabilityID = 2
	AND pv.ProductiveClassID != 4 -- Exclude Dollars as these are always fixed
	AND pv.EmployeeID = 0 -- Variable records are always EmployeeID = 0
GROUP BY bc.BudgetConfigID, 
	pv.EntityGroupConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.DepartmentID, 
	pv.JobCodeID
GO


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

-- fp.viewFactStaffing_Unpivoted
CREATE VIEW fp.viewFactStaffing_Unpivoted AS SELECT * FROM fp.FactReportStaffing
GO


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

-- fp.viewFactStaffing_Unpivoted_BaselineOnly
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2022-07-18   MY        JAZZ-37944  Initial
** 2    2023-12-07   BW        JAZZ-63600  Data model restructure
*************************************************************/
CREATE   VIEW [fp].[viewFactStaffing_Unpivoted_BaselineOnly]
AS
	SELECT	staff.StaffingID,
	staff.BudgetConfigID,
	staff.EntityGroupConfigID,
	staff.EntityID,
	staff.DepartmentID,
	staff.JobCodeID,
	staff.PayCodeGroupID,
	staff.VariabilityID,
	staff.ProductiveClassID,
	staff.EmployeeID,
	staff.ProviderID,
	staff.ProviderTypeID,
	staff.ProviderSpecialtyID,
	staff.ProviderLineItemID,
	staff.SubsectionID,
	UT.UnitTypeID,
	TimeClassID = 2,
	m.FiscalMonthID,
	bc.FiscalYearID,
	Value as OriginalValue
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
	CROSS APPLY (
	VALUES
		(1, 34, InitialBudgetDollars01),
		(2, 34, InitialBudgetDollars02),
		(3, 34, InitialBudgetDollars03),
		(4, 34, InitialBudgetDollars04),
		(5, 34, InitialBudgetDollars05),
		(6, 34, InitialBudgetDollars06),
		(7, 34, InitialBudgetDollars07),
		(8, 34, InitialBudgetDollars08),
		(9, 34, InitialBudgetDollars09),
		(10, 34, InitialBudgetDollars10),
		(11, 34, InitialBudgetDollars11),
		(12, 34, InitialBudgetDollars12),
		(1, 51, InitialBudgetHours01),
		(2, 51, InitialBudgetHours02),
		(3, 51, InitialBudgetHours03),
		(4, 51, InitialBudgetHours04),
		(5, 51, InitialBudgetHours05),
		(6, 51, InitialBudgetHours06),
		(7, 51, InitialBudgetHours07),
		(8, 51, InitialBudgetHours08),
		(9, 51, InitialBudgetHours09),
		(10, 51, InitialBudgetHours10),
		(11, 51, InitialBudgetHours11),
		(12, 51, InitialBudgetHours12),
		(1, 144, InitialBudgetFTEs01),
		(2, 144, InitialBudgetFTEs02),
		(3, 144, InitialBudgetFTEs03),
		(4, 144, InitialBudgetFTEs04),
		(5, 144, InitialBudgetFTEs05),
		(6, 144, InitialBudgetFTEs06),
		(7, 144, InitialBudgetFTEs07),
		(8, 144, InitialBudgetFTEs08),
		(9, 144, InitialBudgetFTEs09),
		(10, 144, InitialBudgetFTEs10),
		(11, 144, InitialBudgetFTEs11),
		(12, 144, InitialBudgetFTEs12)
	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
		LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
		LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth
		INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
	UNION ALL
	SELECT	staff.StaffingID,
	staff.BudgetConfigID,
	staff.EntityGroupConfigID,
	staff.EntityID,
	staff.DepartmentID,
	staff.JobCodeID,
	staff.PayCodeGroupID,
	staff.VariabilityID,
	staff.ProductiveClassID,
	staff.EmployeeID,
	staff.ProviderID,
	staff.ProviderTypeID,
	staff.ProviderSpecialtyID,
	staff.ProviderLineItemID,
	staff.SubsectionID,
	UT.UnitTypeID,
	TimeClassID = 2,
	m.FiscalMonthID,
	bc.FiscalYearID,
	Value as OriginalValue
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
	INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) ON staff.StaffingWageRateID = wr.StaffingWageRateID
	AND staff.VariabilityID = 1
	CROSS APPLY (
	VALUES
		(1, 159, InitialBudget01),
		(2, 159, InitialBudget02),
		(3, 159, InitialBudget03),
		(4, 159, InitialBudget04),
		(5, 159, InitialBudget05),
		(6, 159, InitialBudget06),
		(7, 159, InitialBudget07),
		(8, 159, InitialBudget08),
		(9, 159, InitialBudget09),
		(10, 159, InitialBudget10),
		(11, 159, InitialBudget11),
		(12, 159, InitialBudget12)
	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
		LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
		LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth
		INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactStaffing_Unpivoted_archive
CREATE VIEW fp.viewFactStaffing_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffing_archive
GO


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

-- fp.viewFactStaffing_Unpivoted_source
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2020-08-07   MY        JAZZ-2849   Added Entity Group Config to view for Snowflake reporting
** 2    2021-02-18   MY        JAZZ-15374  Added Provider to view
** 3    2023-11-01   BW        JAZZ-62798  New data model update
*************************************************************/
CREATE   VIEW [fp].[viewFactStaffing_Unpivoted_source]
AS
SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	34 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialBudgetDollars01, TargetAdjustedDollars01, BudgetAdjustedDollars01),
		(2,InitialBudgetDollars02, TargetAdjustedDollars02, BudgetAdjustedDollars02),
		(3,InitialBudgetDollars03, TargetAdjustedDollars03, BudgetAdjustedDollars03),
		(4,InitialBudgetDollars04, TargetAdjustedDollars04, BudgetAdjustedDollars04),
		(5,InitialBudgetDollars05, TargetAdjustedDollars05, BudgetAdjustedDollars05),
		(6,InitialBudgetDollars06, TargetAdjustedDollars06, BudgetAdjustedDollars06),
		(7,InitialBudgetDollars07, TargetAdjustedDollars07, BudgetAdjustedDollars07),
		(8,InitialBudgetDollars08, TargetAdjustedDollars08, BudgetAdjustedDollars08),
		(9,InitialBudgetDollars09, TargetAdjustedDollars09, BudgetAdjustedDollars09),
		(10,InitialBudgetDollars10, TargetAdjustedDollars10, BudgetAdjustedDollars10),
		(11,InitialBudgetDollars11, TargetAdjustedDollars11, BudgetAdjustedDollars11),
		(12,InitialBudgetDollars12, TargetAdjustedDollars12, BudgetAdjustedDollars12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

UNION ALL
SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	34 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID - 1, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialProjectionDollars01, ProjectionAdjustedDollars01, ProjectionAdjustedDollars01),
		(2,InitialProjectionDollars02, ProjectionAdjustedDollars02, ProjectionAdjustedDollars02),
		(3,InitialProjectionDollars03, ProjectionAdjustedDollars03, ProjectionAdjustedDollars03),
		(4,InitialProjectionDollars04, ProjectionAdjustedDollars04, ProjectionAdjustedDollars04),
		(5,InitialProjectionDollars05, ProjectionAdjustedDollars05, ProjectionAdjustedDollars05),
		(6,InitialProjectionDollars06, ProjectionAdjustedDollars06, ProjectionAdjustedDollars06),
		(7,InitialProjectionDollars07, ProjectionAdjustedDollars07, ProjectionAdjustedDollars07),
		(8,InitialProjectionDollars08, ProjectionAdjustedDollars08, ProjectionAdjustedDollars08),
		(9,InitialProjectionDollars09, ProjectionAdjustedDollars09, ProjectionAdjustedDollars09),
		(10,InitialProjectionDollars10, ProjectionAdjustedDollars10, ProjectionAdjustedDollars10),
		(11,InitialProjectionDollars11, ProjectionAdjustedDollars11, ProjectionAdjustedDollars11),
		(12,InitialProjectionDollars12, ProjectionAdjustedDollars12, ProjectionAdjustedDollars12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

UNION ALL

SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	51 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialBudgetHours01, TargetAdjustedHours01, BudgetAdjustedHours01),
		(2,InitialBudgetHours02, TargetAdjustedHours02, BudgetAdjustedHours02),
		(3,InitialBudgetHours03, TargetAdjustedHours03, BudgetAdjustedHours03),
		(4,InitialBudgetHours04, TargetAdjustedHours04, BudgetAdjustedHours04),
		(5,InitialBudgetHours05, TargetAdjustedHours05, BudgetAdjustedHours05),
		(6,InitialBudgetHours06, TargetAdjustedHours06, BudgetAdjustedHours06),
		(7,InitialBudgetHours07, TargetAdjustedHours07, BudgetAdjustedHours07),
		(8,InitialBudgetHours08, TargetAdjustedHours08, BudgetAdjustedHours08),
		(9,InitialBudgetHours09, TargetAdjustedHours09, BudgetAdjustedHours09),
		(10,InitialBudgetHours10, TargetAdjustedHours10, BudgetAdjustedHours10),
		(11,InitialBudgetHours11, TargetAdjustedHours11, BudgetAdjustedHours11),
		(12,InitialBudgetHours12, TargetAdjustedHours12, BudgetAdjustedHours12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

UNION ALL
SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	51 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID - 1, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialProjectionHours01, ProjectionAdjustedHours01, ProjectionAdjustedHours01),
		(2,InitialProjectionHours02, ProjectionAdjustedHours02, ProjectionAdjustedHours02),
		(3,InitialProjectionHours03, ProjectionAdjustedHours03, ProjectionAdjustedHours03),
		(4,InitialProjectionHours04, ProjectionAdjustedHours04, ProjectionAdjustedHours04),
		(5,InitialProjectionHours05, ProjectionAdjustedHours05, ProjectionAdjustedHours05),
		(6,InitialProjectionHours06, ProjectionAdjustedHours06, ProjectionAdjustedHours06),
		(7,InitialProjectionHours07, ProjectionAdjustedHours07, ProjectionAdjustedHours07),
		(8,InitialProjectionHours08, ProjectionAdjustedHours08, ProjectionAdjustedHours08),
		(9,InitialProjectionHours09, ProjectionAdjustedHours09, ProjectionAdjustedHours09),
		(10,InitialProjectionHours10, ProjectionAdjustedHours10, ProjectionAdjustedHours10),
		(11,InitialProjectionHours11, ProjectionAdjustedHours11, ProjectionAdjustedHours11),
		(12,InitialProjectionHours12, ProjectionAdjustedHours12, ProjectionAdjustedHours12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

UNION ALL

SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	144 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialBudgetFTEs01, TargetAdjustedFTEs01, BudgetAdjustedFTEs01),
		(2,InitialBudgetFTEs02, TargetAdjustedFTEs02, BudgetAdjustedFTEs02),
		(3,InitialBudgetFTEs03, TargetAdjustedFTEs03, BudgetAdjustedFTEs03),
		(4,InitialBudgetFTEs04, TargetAdjustedFTEs04, BudgetAdjustedFTEs04),
		(5,InitialBudgetFTEs05, TargetAdjustedFTEs05, BudgetAdjustedFTEs05),
		(6,InitialBudgetFTEs06, TargetAdjustedFTEs06, BudgetAdjustedFTEs06),
		(7,InitialBudgetFTEs07, TargetAdjustedFTEs07, BudgetAdjustedFTEs07),
		(8,InitialBudgetFTEs08, TargetAdjustedFTEs08, BudgetAdjustedFTEs08),
		(9,InitialBudgetFTEs09, TargetAdjustedFTEs09, BudgetAdjustedFTEs09),
		(10,InitialBudgetFTEs10, TargetAdjustedFTEs10, BudgetAdjustedFTEs10),
		(11,InitialBudgetFTEs11, TargetAdjustedFTEs11, BudgetAdjustedFTEs11),
		(12,InitialBudgetFTEs12, TargetAdjustedFTEs12, BudgetAdjustedFTEs12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

UNION ALL
SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	144 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID - 1, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialProjectionFTEs01, ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs01),
		(2,InitialProjectionFTEs02, ProjectionAdjustedFTEs02, ProjectionAdjustedFTEs02),
		(3,InitialProjectionFTEs03, ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs03),
		(4,InitialProjectionFTEs04, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs04),
		(5,InitialProjectionFTEs05, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs05),
		(6,InitialProjectionFTEs06, ProjectionAdjustedFTEs06, ProjectionAdjustedFTEs06),
		(7,InitialProjectionFTEs07, ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs07),
		(8,InitialProjectionFTEs08, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs08),
		(9,InitialProjectionFTEs09, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs09),
		(10,InitialProjectionFTEs10, ProjectionAdjustedFTEs10, ProjectionAdjustedFTEs10),
		(11,InitialProjectionFTEs11, ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs11),
		(12,InitialProjectionFTEs12, ProjectionAdjustedFTEs12, ProjectionAdjustedFTEs12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID

-- Wage Rate
UNION ALL

SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	3 AS VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	159 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	INNER JOIN fp.StaffingWageRate wr ON fs.StaffingWageRateID = wr.StaffingWageRateID
	CROSS APPLY (		
		VALUES 
		(1,InitialBudget01, TargetAdjusted01, BudgetAdjusted01),
		(2,InitialBudget02, TargetAdjusted02, BudgetAdjusted02),
		(3,InitialBudget03, TargetAdjusted03, BudgetAdjusted03),
		(4,InitialBudget04, TargetAdjusted04, BudgetAdjusted04),
		(5,InitialBudget05, TargetAdjusted05, BudgetAdjusted05),
		(6,InitialBudget06, TargetAdjusted06, BudgetAdjusted06),
		(7,InitialBudget07, TargetAdjusted07, BudgetAdjusted07),
		(8,InitialBudget08, TargetAdjusted08, BudgetAdjusted08),
		(9,InitialBudget09, TargetAdjusted09, BudgetAdjusted09),
		(10,InitialBudget10, TargetAdjusted10, BudgetAdjusted10),
		(11,InitialBudget11, TargetAdjusted11, BudgetAdjusted11),
		(12,InitialBudget12, TargetAdjusted12, BudgetAdjusted12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
WHERE fs.VariabilityID = 1

UNION ALL
SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	3 AS VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	159 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID - 1, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	INNER JOIN fp.StaffingWageRate wr ON fs.StaffingWageRateID = wr.StaffingWageRateID
	CROSS APPLY (		
		VALUES 
		(1,InitialProjection01, ProjectionAdjusted01, ProjectionAdjusted01),
		(2,InitialProjection02, ProjectionAdjusted02, ProjectionAdjusted02),
		(3,InitialProjection03, ProjectionAdjusted03, ProjectionAdjusted03),
		(4,InitialProjection04, ProjectionAdjusted04, ProjectionAdjusted04),
		(5,InitialProjection05, ProjectionAdjusted05, ProjectionAdjusted05),
		(6,InitialProjection06, ProjectionAdjusted06, ProjectionAdjusted06),
		(7,InitialProjection07, ProjectionAdjusted07, ProjectionAdjusted07),
		(8,InitialProjection08, ProjectionAdjusted08, ProjectionAdjusted08),
		(9,InitialProjection09, ProjectionAdjusted09, ProjectionAdjusted09),
		(10,InitialProjection10, ProjectionAdjusted10, ProjectionAdjusted10),
		(11,InitialProjection11, ProjectionAdjusted11, ProjectionAdjusted11),
		(12,InitialProjection12, ProjectionAdjusted12, ProjectionAdjusted12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
WHERE fs.VariabilityID = 1

UNION ALL

SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	172 as UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialBudgetRate01, TargetAdjustedRate01, BudgetAdjustedRate01),
		(2,InitialBudgetRate02, TargetAdjustedRate02, BudgetAdjustedRate02),
		(3,InitialBudgetRate03, TargetAdjustedRate03, BudgetAdjustedRate03),
		(4,InitialBudgetRate04, TargetAdjustedRate04, BudgetAdjustedRate04),
		(5,InitialBudgetRate05, TargetAdjustedRate05, BudgetAdjustedRate05),
		(6,InitialBudgetRate06, TargetAdjustedRate06, BudgetAdjustedRate06),
		(7,InitialBudgetRate07, TargetAdjustedRate07, BudgetAdjustedRate07),
		(8,InitialBudgetRate08, TargetAdjustedRate08, BudgetAdjustedRate08),
		(9,InitialBudgetRate09, TargetAdjustedRate09, BudgetAdjustedRate09),
		(10,InitialBudgetRate10, TargetAdjustedRate10, BudgetAdjustedRate10),
		(11,InitialBudgetRate11, TargetAdjustedRate11, BudgetAdjustedRate11),
		(12,InitialBudgetRate12, TargetAdjustedRate12, BudgetAdjustedRate12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
WHERE fs.VariabilityID = 2

UNION ALL
SELECT 
	fs.StaffingID,
	fs.BudgetConfigID,
	fs.EntityGroupConfigID,
	fs.EntityID,
	fs.DepartmentID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.VariabilityID,
	fs.ProductiveClassID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	fs.ProviderLineItemID,
	fs.SubsectionID,
	172 as UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID - 1, 
	m.FiscalMonthID,
	OriginalValue, Value, ManagerValue			
	FROM fp.Staffing  fs
	CROSS APPLY (		
		VALUES 
		(1,InitialProjectionRate01, ProjectionAdjustedRate01, ProjectionAdjustedRate01),
		(2,InitialProjectionRate02, ProjectionAdjustedRate02, ProjectionAdjustedRate02),
		(3,InitialProjectionRate03, ProjectionAdjustedRate03, ProjectionAdjustedRate03),
		(4,InitialProjectionRate04, ProjectionAdjustedRate04, ProjectionAdjustedRate04),
		(5,InitialProjectionRate05, ProjectionAdjustedRate05, ProjectionAdjustedRate05),
		(6,InitialProjectionRate06, ProjectionAdjustedRate06, ProjectionAdjustedRate06),
		(7,InitialProjectionRate07, ProjectionAdjustedRate07, ProjectionAdjustedRate07),
		(8,InitialProjectionRate08, ProjectionAdjustedRate08, ProjectionAdjustedRate08),
		(9,InitialProjectionRate09, ProjectionAdjustedRate09, ProjectionAdjustedRate09),
		(10,InitialProjectionRate10, ProjectionAdjustedRate10, ProjectionAdjustedRate10),
		(11,InitialProjectionRate11, ProjectionAdjustedRate11, ProjectionAdjustedRate11),
		(12,InitialProjectionRate12, ProjectionAdjustedRate12, ProjectionAdjustedRate12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) 
LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth 
INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
WHERE fs.VariabilityID = 2
GO


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

-- fp.viewFactStatistics
CREATE VIEW fp.viewFactStatistics
AS
/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1 	2022-10-04	JB		JAZZ-43489	Remove FlexedValue references
	*************************************************************/
SELECT 
	stat.StatisticsID,
	stat.BudgetConfigID,
	stat.EntityGroupConfigID,
	stat.DepartmentID,
	stat.FinancialReportingID,
	stat.EntityID,
	stat.AccountID,
	stat.ProviderID,
	stat.ProviderSpecialtyID,
	stat.ProviderTypeID,
	stat.ProviderLineItemID,
	bc.FiscalYearID,
	stat.UnitTypeID,
	bdgt.LockType as BudgetLockType,
	bdgt.LockFlag as BudgetLockFlag,
	bdgt.BudgetPhaseID as BudgetPhaseID,
	proj.LockType as ProjectionLockType,
	proj.LockFlag as ProjectionLockFlag,
	stat.SampledBudget01, stat.SampledBudget02, stat.SampledBudget03, stat.SampledBudget04, stat.SampledBudget05, stat.SampledBudget06, stat.SampledBudget07, stat.SampledBudget08, stat.SampledBudget09, stat.SampledBudget10, stat.SampledBudget11, stat.SampledBudget12, stat.SampledBudgetTotal,
	stat.InitialBudget01, stat.InitialBudget02, stat.InitialBudget03, stat.InitialBudget04, stat.InitialBudget05, stat.InitialBudget06, stat.InitialBudget07, stat.InitialBudget08, stat.InitialBudget09, stat.InitialBudget10, stat.InitialBudget11, stat.InitialBudget12, stat.InitialBudgetTotal,
	stat.SampledProjection01, stat.SampledProjection02, stat.SampledProjection03, stat.SampledProjection04, stat.SampledProjection05, stat.SampledProjection06, stat.SampledProjection07, stat.SampledProjection08, stat.SampledProjection09, stat.SampledProjection10, stat.SampledProjection11, stat.SampledProjection12, stat.SampledProjectionTotal,
	stat.InitialProjection01, stat.InitialProjection02, stat.InitialProjection03, stat.InitialProjection04, stat.InitialProjection05, stat.InitialProjection06, stat.InitialProjection07, stat.InitialProjection08, stat.InitialProjection09, stat.InitialProjection10, stat.InitialProjection11, stat.InitialProjection12, stat.InitialProjectionTotal,bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12, bdgt.AdjustedValueTotal,
	proj.AdjustedValue01 AS AdjustedProjectionValue01, proj.AdjustedValue02 AS AdjustedProjectionValue02, proj.AdjustedValue03 AS AdjustedProjectionValue03, proj.AdjustedValue04 AS AdjustedProjectionValue04, proj.AdjustedValue05 AS AdjustedProjectionValue05, proj.AdjustedValue06 AS AdjustedProjectionValue06, proj.AdjustedValue07 AS AdjustedProjectionValue07, proj.AdjustedValue08 AS AdjustedProjectionValue08, proj.AdjustedValue09 AS AdjustedProjectionValue09, proj.AdjustedValue10 AS AdjustedProjectionValue10, proj.AdjustedValue11 AS AdjustedProjectionValue11, proj.AdjustedValue12 AS AdjustedProjectionValue12, proj.AdjustedValueTotal AS AdjustedProjectionValueTotal
FROM fp.FactStatistics stat
	INNER JOIN [fp].[BudgetConfig] bc ON stat.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [fp].[FactStatisticsBudget] bdgt ON stat.StatisticsID = bdgt.StatisticsID
	INNER JOIN [fp].[FactStatisticsProjection] proj ON stat.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = bdgt.BudgetPhaseID
GO


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

-- fp.viewFactStatisticsBudget_HistoryViewer
CREATE VIEW [fp].[viewFactStatistics_HistoryViewer]
AS
SELECT
	ov.StatisticsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.PatientClassID, 
	ov.PayorID,
	ov.ProviderID,
	ov.ProviderTypeID,
	ov.ProviderLineItemID,
	ov.ProviderSpecialtyID,
	ov.SubSectionID,
	ov.UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.FactStatistics gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics gl 
		INNER JOIN fp.FactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.SubSectionID = v.SubSectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics gl 
		INNER JOIN fp.FactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.ProviderID = mgrv.ProviderID
	AND ov.ProviderTypeID = mgrv.ProviderTypeID
	AND ov.ProviderLineItemID = mgrv.ProviderLineItemID
	AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID
	AND ov.SubSectionID = mgrv.SubSectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactStatisticsBudget_repo
CREATE VIEW fp.viewFactStatisticsBudget_repo
AS
SELECT
    fsb.RowID,
    stat.StatisticsID,
    stat.BudgetConfigID,
    stat.EntityGroupConfigID,
    fsb.BudgetPhaseID,
    stat.EntityID,
    stat.DepartmentID,
    stat.AccountID,
    stat.FinancialReportingID,
    stat.PayorID,
    stat.PatientClassID,
    stat.UnitTypeID,
    stat.ProviderID,
    stat.ProviderSpecialtyID,
    stat.ProviderTypeID,
    stat.ProviderLineItemID,
    fsb.LockFlag,
    fsb.LockType,
    CAST(2 AS TINYINT) AS TimeClassID,
    fsb.AdjustedValue01, fsb.AdjustedValue02, fsb.AdjustedValue03, fsb.AdjustedValue04, fsb.AdjustedValue05, fsb.AdjustedValue06, fsb.AdjustedValue07, fsb.AdjustedValue08, fsb.AdjustedValue09, fsb.AdjustedValue10, fsb.AdjustedValue11, fsb.AdjustedValue12,
    fsb.RateAdjustedValue01, fsb.RateAdjustedValue02, fsb.RateAdjustedValue03, fsb.RateAdjustedValue04, fsb.RateAdjustedValue05, fsb.RateAdjustedValue06, fsb.RateAdjustedValue07, fsb.RateAdjustedValue08, fsb.RateAdjustedValue09, fsb.RateAdjustedValue10, fsb.RateAdjustedValue11, fsb.RateAdjustedValue12,
    stat.SubsectionID,
	stat.GroupingGuid
FROM fp.FactStatistics stat
    INNER JOIN fp.FactStatisticsBudget fsb ON stat.StatisticsID = fsb.StatisticsID;
GO


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

-- fp.viewFactStatisticsByGeneralLedgerID
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	08-25-2023  MY      JAZZ-59500		Updated view to restructure
*************************************************************/
CREATE   VIEW fp.viewFactStatisticsByGeneralLedgerID
AS
SELECT 
 	gl.GeneralLedgerID,
	gl.BudgetConfigID,
	gl.EntityGroupConfigID,
	gl.FlexingTypeID,
 	SUM(tgt.AdjustedValue01) AS TargetStats01,
	SUM(tgt.AdjustedValue02) AS TargetStats02,
	SUM(tgt.AdjustedValue03) AS TargetStats03,
	SUM(tgt.AdjustedValue04) AS TargetStats04,
	SUM(tgt.AdjustedValue05) AS TargetStats05,
	SUM(tgt.AdjustedValue06) AS TargetStats06,
	SUM(tgt.AdjustedValue07) AS TargetStats07,
	SUM(tgt.AdjustedValue08) AS TargetStats08,
	SUM(tgt.AdjustedValue09) AS TargetStats09,
	SUM(tgt.AdjustedValue10) AS TargetStats10,
	SUM(tgt.AdjustedValue11) AS TargetStats11,
	SUM(tgt.AdjustedValue12) AS TargetStats12,
 	SUM(bdgt.AdjustedValue01) AS BudgetStats01,
	SUM(bdgt.AdjustedValue02) AS BudgetStats02,
	SUM(bdgt.AdjustedValue03) AS BudgetStats03,
	SUM(bdgt.AdjustedValue04) AS BudgetStats04,
	SUM(bdgt.AdjustedValue05) AS BudgetStats05,
	SUM(bdgt.AdjustedValue06) AS BudgetStats06,
	SUM(bdgt.AdjustedValue07) AS BudgetStats07,
	SUM(bdgt.AdjustedValue08) AS BudgetStats08,
	SUM(bdgt.AdjustedValue09) AS BudgetStats09,
	SUM(bdgt.AdjustedValue10) AS BudgetStats10,
	SUM(bdgt.AdjustedValue11) AS BudgetStats11,
	SUM(bdgt.AdjustedValue12) AS BudgetStats12,
	SUM(proj.AdjustedValue01) AS ProjectionStats01,
	SUM(proj.AdjustedValue02) AS ProjectionStats02,
	SUM(proj.AdjustedValue03) AS ProjectionStats03,
	SUM(proj.AdjustedValue04) AS ProjectionStats04,
	SUM(proj.AdjustedValue05) AS ProjectionStats05,
	SUM(proj.AdjustedValue06) AS ProjectionStats06,
	SUM(proj.AdjustedValue07) AS ProjectionStats07,
	SUM(proj.AdjustedValue08) AS ProjectionStats08,
	SUM(proj.AdjustedValue09) AS ProjectionStats09,
	SUM(proj.AdjustedValue10) AS ProjectionStats10,
	SUM(proj.AdjustedValue11) AS ProjectionStats11,
	SUM(proj.AdjustedValue12) AS ProjectionStats12,
	SUM(tgt.AdjustedValueTotal) AS TargetStatsTotal,
	SUM(bdgt.AdjustedValueTotal) AS BudgetStatsTotal,
	SUM(proj.AdjustedValueTotal) AS ProjectionStatsTotal
FROM [fp].FactStatistics sb WITH(NOLOCK)
	INNER JOIN [fp].[FactStatisticsBudget] tgt ON sb.StatisticsID = tgt.StatisticsID AND tgt.BudgetPhaseID = 2
	INNER JOIN [fp].[FactStatisticsBudget] bdgt ON sb.StatisticsID = bdgt.StatisticsID AND bdgt.BudgetPhaseID = 3
	INNER JOIN [fp].[FactStatisticsProjection] proj ON sb.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = bdgt.BudgetPhaseID
	INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
	INNER JOIN (
			SELECT DISTINCT EntityGroupConfigID, FlexingTypeID, DepartmentID, StatAccountID, GLAccountID 
			FROM [fp].[FlexConfigMapping] WITH(NOLOCK)
			WHERE FlexingTypeID IN (1, 2) -- Non-Staffing (1) and Revenue (2)
		) fcm ON sb.DepartmentID = fcm.DepartmentID 
			AND sb.AccountID = fcm.StatAccountID 
			AND fcm.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
    	AND sb.EntityID = egcm.EntityID
	INNER JOIN fp.GeneralLedger gl ON sb.BudgetConfigID = gl.BudgetConfigID 
		AND sb.EntityGroupConfigID = gl.EntityGroupConfigID
		AND sb.DepartmentID = gl.DepartmentID
		AND fcm.GLAccountID = gl.AccountID
		AND fcm.FlexingTypeID = gl.FlexingTypeID -- Essentially exclude anything that isn't flexing
WHERE 1 = 1
	AND gl.VariabilityID = 2 -- Filter to Variable records to avoid multiple rows
GROUP BY gl.GeneralLedgerID, gl.FlexingTypeID, gl.BudgetConfigID, gl.EntityGroupConfigID
HAVING SUM(tgt.AdjustedValueTotal) > 0 -- Exclude records that are all 0's, we can just assume it's 0 if it's missing from this
	OR SUM(bdgt.AdjustedValueTotal) > 0
	OR SUM(proj.AdjustedValueTotal) > 0
GO


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

-- fp.viewFactStatisticsForAdjustments_Unpivoted
CREATE VIEW [fp].[viewFactStatisticsForAdjustments_Unpivoted]
AS
SELECT 
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.AccountID,
	ov.PatientClassID,
	ov.PayorID,
	ov.FinancialReportingID,
	ov.UnitTypeID,
	2 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID,
	ov.InitialValue as OriginalValue,
	v.Value,
	mgrv.Value as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.*
		FROM fp.FactStatistics cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 2) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.FinancialReportingID = v.FinancialReportingID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for Manager Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 3) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.FinancialReportingID = mgrv.FinancialReportingID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID

UNION

	SELECT 
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.AccountID,
	ov.PatientClassID,
	ov.PayorID,
	ov.FinancialReportingID,
	ov.UnitTypeID,
	12 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID,
	ov.InitialValue as OriginalValue,
	v.Value,
	mgrv.Value as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.*
		FROM fp.FactStatistics cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 2) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.FinancialReportingID = v.FinancialReportingID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for Manager Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 3) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.FinancialReportingID = mgrv.FinancialReportingID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactStatisticsHistory_Unpivoted
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI          Description  
 ** 1   2021-07-20   MD      JAZZ-23237  Adding union all for data transfer table
*************************************************************/  

CREATE VIEW [fp].[viewFactStatisticsHistory_Unpivoted] 
AS 
	SELECT 
		BudgetConfigID, 
		EntityGroupConfigID,
		EntityID,
		DepartmentID,
		AccountID,
		FinancialReportingID,
		PayorID,
		PatientClassID,
		UnitTypeID,
		TimeClassID,
		FiscalYearID,
		FiscalMonthID,
		Value
	FROM fp.FactReportStatisticsHistory

	UNION ALL 

	SELECT 
		BudgetConfigID, 
		0 as EntityGroupConfigID,
		EntityID,
		DepartmentID,
		AccountID,
		FinancialReportingID,
		PayorID,
		PatientClassID,
		UnitTypeID,
		TimeClassID,
		FiscalYearID,
		FiscalMonthID,
		Value
	FROM fp.FactReportStatisticsHistoryDataTransfer
GO


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

-- fp.viewFactStatisticsHistory_Unpivoted_archive
CREATE VIEW fp.viewFactStatisticsHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStatisticsHistory_archive
GO


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

-- fp.viewFactStatisticsHistory_Unpivoted_source
CREATE VIEW [fp].[viewFactStatisticsHistory_Unpivoted_source]
AS
-- Unpivot for PriorYearActual
SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.PayorID, data.PatientClassID, data.ProviderID, data.ProviderTypeID, data.ProviderSpecialtyID, data.ProviderLineItemID, data.SubsectionID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, 
		PatientClassID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT fs.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12
        FROM fp.FactStatistics fs
        INNER JOIN fp.FactStatisticsHistory hist ON fs.StatisticsID = hist.StatisticsID ) fs
        UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f
        LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for ActualYTD
SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.PayorID, data.PatientClassID, data.ProviderID, data.ProviderTypeID, data.ProviderSpecialtyID, data.ProviderLineItemID, data.SubsectionID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, 
		PatientClassID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT fs.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12
        FROM fp.FactStatistics fs
        INNER JOIN fp.FactStatisticsHistory hist ON fs.StatisticsID = hist.StatisticsID ) fs
        UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f
        LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID

UNION ALL

-- Unpivot for CurrentYearBudget
SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.PayorID, data.PatientClassID, data.ProviderID, data.ProviderTypeID, data.ProviderSpecialtyID, data.ProviderLineItemID, data.SubsectionID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value
FROM (
    SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, 
		PatientClassID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value
    FROM (
        SELECT fs.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12
        FROM fp.FactStatistics fs
        INNER JOIN fp.FactStatisticsHistory hist ON fs.StatisticsID = hist.StatisticsID ) fs
        UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f
        LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudget', 'Month')) data
    INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactStatisticsProjection_HistoryViewer
CREATE VIEW [fp].[viewFactStatisticsProjection_HistoryViewer]
AS
SELECT
	ov.StatisticsID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID,
	ov.EntityID, 
	ov.DepartmentID, 
	ov.AccountID, 
	ov.FinancialReportingID, 
	ov.PatientClassID, 
	ov.PayorID,
	ov.ProviderID,
	ov.ProviderTypeID,
	ov.ProviderLineItemID,
	ov.ProviderSpecialtyID,
	ov.SubSectionID,
	ov.UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT gl.*
		FROM fp.FactStatistics gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics gl 
		INNER JOIN fp.FactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 2) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.BudgetConfigID = v.BudgetConfigID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.SubSectionID = v.SubSectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics gl 
		INNER JOIN fp.FactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID 
		WHERE bdgt.BudgetPhaseID = 3) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.ProviderID = mgrv.ProviderID
	AND ov.ProviderTypeID = mgrv.ProviderTypeID
	AND ov.ProviderLineItemID = mgrv.ProviderLineItemID
	AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID
	AND ov.SubSectionID = mgrv.SubSectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactStatisticsProjection_repo
CREATE VIEW fp.viewFactStatisticsProjection_repo
AS
SELECT 
    fsp.RowID,
    stat.StatisticsID,
    stat.BudgetConfigID,
    stat.EntityGroupConfigID,
    fsp.BudgetPhaseID,
    stat.EntityID,
    stat.DepartmentID,
    stat.AccountID,
    stat.FinancialReportingID,
    stat.PayorID,
    stat.PatientClassID,
    stat.UnitTypeID,
    stat.ProviderID,
    stat.ProviderSpecialtyID,
    stat.ProviderTypeID,
    stat.ProviderLineItemID,
    fsp.LockFlag,
    fsp.LockType,
    CAST(12 AS TINYINT) AS TimeClassID,
    fsp.AdjustedValue01, fsp.AdjustedValue02, fsp.AdjustedValue03, fsp.AdjustedValue04, fsp.AdjustedValue05, fsp.AdjustedValue06, fsp.AdjustedValue07, fsp.AdjustedValue08, fsp.AdjustedValue09, fsp.AdjustedValue10, fsp.AdjustedValue11, fsp.AdjustedValue12,
    fsp.RateAdjustedValue01, fsp.RateAdjustedValue02, fsp.RateAdjustedValue03, fsp.RateAdjustedValue04, fsp.RateAdjustedValue05, fsp.RateAdjustedValue06, fsp.RateAdjustedValue07, fsp.RateAdjustedValue08, fsp.RateAdjustedValue09, fsp.RateAdjustedValue10, fsp.RateAdjustedValue11, fsp.RateAdjustedValue12,
    stat.SubsectionID,
	stat.GroupingGuid
FROM fp.FactStatistics stat
    INNER JOIN fp.FactStatisticsProjection fsp ON stat.StatisticsID = fsp.StatisticsID;
GO


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

-- fp.viewFactStatisticsTotals
CREATE VIEW fp.viewFactStatisticsTotals
 AS
    SELECT obj.StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID,
        obj.ProviderID, obj.ProviderSpecialtyID, obj.ProviderTypeID, obj.ProviderLineItemID, 
        SampledBudgetTotal, SampledProjectionTotal, InitialBudgetTotal, InitialProjectionTotal, adminProj.AdjustedValueTotal AS ProjectionAdminTotal, mgrProj.AdjustedValueTotal AS ProjectionManagerTotal, 
        adminBudg.AdjustedValueTotal AS BudgetAdminTotal, mgrBudg.AdjustedValueTotal AS BudgetManagerTotal, hist.ActualYTDValueTotal, hist.PriorYearActualValueTotal, hist.CurrentYearBudgetTotal
    FROM [fp].[FactStatistics] obj
        INNER JOIN [fp].[FactStatisticsProjection] adminProj ON obj.StatisticsID = adminProj.StatisticsID
        INNER JOIN [fp].[FactStatisticsProjection] mgrProj ON obj.StatisticsID = mgrProj.StatisticsID
        INNER JOIN [fp].[FactStatisticsBudget] adminBudg ON obj.StatisticsID = adminBudg.StatisticsID
        INNER JOIN [fp].[FactStatisticsBudget] mgrBudg ON obj.StatisticsID = mgrBudg.StatisticsID
        INNER JOIN [fp].[FactStatisticsHistory] hist ON obj.StatisticsID = hist.StatisticsID
    WHERE 
            adminProj.BudgetPhaseID = 2
        AND mgrProj.BudgetPhaseID = 3
        AND adminBudg.BudgetPhaseID = 2
        AND mgrBudg.BudgetPhaseID = 3
GO


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

-- fp.viewFactStatistics_Pivoted
CREATE VIEW [fp].[viewFactStatistics_Pivoted]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-01-31  AO  	 JAZZ-48807	    Added BudgetSpreadsLockFlag
 ** 2 	 2023-02-01  NH  	 JAZZ-47035	    Added TargetLockType, TargetLockFlag
*************************************************************/

SELECT
	stat.StatisticsID,
	stat.BudgetConfigID,
	stat.EntityGroupConfigID,
	stat.DepartmentID,
	stat.FinancialReportingID,
	stat.PayorID,
	stat.PatientClassID,
	stat.EntityID,
	stat.AccountID,
	bc.FiscalYearID,
	stat.UnitTypeID,
	stat.ProviderID,
	stat.ProviderSpecialtyID,
	stat.ProviderTypeID,
	stat.ProviderLineItemID,
	stat.SubsectionID,
	stat.GroupingGuid,
	fbdgt.LockType as TargetLockType,
	fbdgt.LockFlag as TargetLockFlag,
	dbdgt.LockType as BudgetLockType,
	dbdgt.LockFlag as BudgetLockFlag,
	dproj.LockType as ProjectionLockType,
	dproj.LockFlag as ProjectionLockFlag,
	
	CASE WHEN dbdgt.LockType = 6 THEN 1 ELSE 0 END AS BudgetSpreadsLockFlag,

	CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag,
	CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag,
	CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag,
		   
	fbdgt.AdjustedValueTotal,
	dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal,
	
	fproj.AdjustedValueTotal as AdjustedProjectionValueTotal,
	dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal,
	
	hist.PriorYearActualValueTotal as PriorYearActualValueTotal,
	hist.ActualYTDValueTotal as ActualYTDValueTotal,
	hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal,
	
	stat.InitialBudgetTotal,
	stat.InitialProjectionTotal,
	
	dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12,
	
	fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12,
	fproj.AdjustedValue01 as AdjustedProjectionValue01, fproj.AdjustedValue02 as AdjustedProjectionValue02, fproj.AdjustedValue03 as AdjustedProjectionValue03, fproj.AdjustedValue04 as AdjustedProjectionValue04, fproj.AdjustedValue05 as AdjustedProjectionValue05, fproj.AdjustedValue06 as AdjustedProjectionValue06, fproj.AdjustedValue07 as AdjustedProjectionValue07, fproj.AdjustedValue08 as AdjustedProjectionValue08, fproj.AdjustedValue09 as AdjustedProjectionValue09, fproj.AdjustedValue10 as AdjustedProjectionValue10, fproj.AdjustedValue11 as AdjustedProjectionValue11, fproj.AdjustedValue12 as AdjustedProjectionValue12,
	dproj.AdjustedValue01 as ManagerAdjustedProjectionValue01, dproj.AdjustedValue02 as ManagerAdjustedProjectionValue02, dproj.AdjustedValue03 as ManagerAdjustedProjectionValue03, dproj.AdjustedValue04 as ManagerAdjustedProjectionValue04, dproj.AdjustedValue05 as ManagerAdjustedProjectionValue05, dproj.AdjustedValue06 as ManagerAdjustedProjectionValue06, dproj.AdjustedValue07 as ManagerAdjustedProjectionValue07, dproj.AdjustedValue08 as ManagerAdjustedProjectionValue08, dproj.AdjustedValue09 as ManagerAdjustedProjectionValue09, dproj.AdjustedValue10 as ManagerAdjustedProjectionValue10, dproj.AdjustedValue11 as ManagerAdjustedProjectionValue11, dproj.AdjustedValue12 as ManagerAdjustedProjectionValue12
FROM 
	fp.FactStatistics stat
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON stat.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN fp.FactStatisticsBudget fbdgt with (readuncommitted) ON stat.StatisticsID = fbdgt.StatisticsID and fbdgt.BudgetPhaseID = 2
	INNER JOIN fp.FactStatisticsBudget dbdgt with (readuncommitted) ON stat.StatisticsID = dbdgt.StatisticsID and dbdgt.BudgetPhaseID = 3
	INNER JOIN fp.FactStatisticsProjection fproj with (readuncommitted) ON stat.StatisticsID = fproj.StatisticsID and fproj.BudgetPhaseID = 2
	INNER JOIN fp.FactStatisticsProjection dproj with (readuncommitted) ON stat.StatisticsID = dproj.StatisticsID and dproj.BudgetPhaseID = 3
	INNER JOIN fp.FactStatisticsHistory hist with (readuncommitted) ON stat.StatisticsID = hist.StatisticsID
GO


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

-- fp.viewFactStatistics_Unpivoted
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI          Description  
 ** 1   2021-07-20   MD      JAZZ-23237  Adding union all for data transfer table
*************************************************************/  

CREATE VIEW [fp].[viewFactStatistics_Unpivoted] AS 
SELECT 
	BudgetConfigID, 
	EntityID, 
	DepartmentID,
	AccountID, 
	PatientClassID,
	PayorID,
	FinancialReportingID, 
	UnitTypeID, 
	TimeClassID, 
	FiscalMonthID, 
	FiscalYearID, 
	OriginalValue, 
	Value,
	ManagerValue, 
	ProviderID, 
	ProviderLineItemID, 
	ProviderSpecialtyID, 
	ProviderTypeID
FROM fp.FactReportStatistics

UNION ALL

SELECT 
	BudgetConfigID, 
	EntityID, 
	DepartmentID,
	AccountID, 
	PatientClassID,
	PayorID,
	FinancialReportingID, 
	UnitTypeID, 
	TimeClassID, 
	FiscalMonthID, 
	FiscalYearID, 
	OriginalValue, 
	Value,
	ManagerValue, 
	0 AS ProviderID, 
	0 AS ProviderLineItemID, 
	0 AS ProviderSpecialtyID, 
	0 AS ProviderTypeID
FROM fp.FactReportStatisticsDataTransfer
GO


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

-- fp.viewFactStatistics_Unpivoted_BaselineOnly
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2022-07-18   MY        JAZZ-37944  Initial
*************************************************************/
CREATE   VIEW [fp].[viewFactStatistics_Unpivoted_BaselineOnly]
AS
SELECT 
	ov.StatisticsID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.AccountID,
	ov.PatientClassID,
	ov.PayorID,
	ov.FinancialReportingID,
	ov.ProviderID,
	ov.ProviderTypeID,
	ov.ProviderSpecialtyID,
	ov.ProviderLineItemID,
	ov.SubsectionID,
	ov.UnitTypeID,
	2 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID,
	ov.InitialValue as OriginalValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, 
		FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.*
		FROM fp.FactStatistics cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFactStatistics_Unpivoted_archive
CREATE VIEW fp.viewFactStatistics_Unpivoted_archive AS SELECT * FROM fp.FactReportStatistics_archive
GO


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

-- fp.viewFactStatistics_Unpivoted_source
CREATE VIEW fp.viewFactStatistics_Unpivoted_source
AS
SELECT 
	ov.StatisticsID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.AccountID,
	ov.PatientClassID,
	ov.PayorID,
	ov.FinancialReportingID,
	ov.ProviderID,
	ov.ProviderTypeID,
	ov.ProviderSpecialtyID,
	ov.ProviderLineItemID,
	ov.SubsectionID,
	ov.UnitTypeID,
	2 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID,
	ov.InitialValue as OriginalValue,
	v.Value,
	mgrv.Value as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, 
		FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.*
		FROM fp.FactStatistics cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, 
		FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 2) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.FinancialReportingID = v.FinancialReportingID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for Manager Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, 
		FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 3) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.FinancialReportingID = mgrv.FinancialReportingID
	AND ov.ProviderID = mgrv.ProviderID
	AND ov.ProviderTypeID = mgrv.ProviderTypeID
	AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID
	AND ov.ProviderLineItemID = mgrv.ProviderLineItemID
	AND ov.SubsectionID = mgrv.SubsectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID

UNION ALL

SELECT 
	ov.StatisticsID,
	ov.BudgetConfigID,
	ov.EntityID,
	ov.DepartmentID,
	ov.AccountID,
	ov.PatientClassID,
	ov.PayorID,
	ov.FinancialReportingID,
	ov.ProviderID,
	ov.ProviderTypeID,
	ov.ProviderSpecialtyID,
	ov.ProviderLineItemID,
	ov.SubsectionID,
	ov.UnitTypeID,
	12 as TimeClassID,
	ov.FiscalMonthID,
	bc.FiscalYearID - 1,
	ov.InitialValue as OriginalValue,
	v.Value,
	mgrv.Value as ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, 
		FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT cv.*
		FROM fp.FactStatistics cv ) cv
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, 
		FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 2) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON ov.BudgetConfigID = v.BudgetConfigID
	AND ov.EntityID = v.EntityID
	AND ov.DepartmentID = v.DepartmentID
	AND ov.AccountID = v.AccountID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.PayorID = v.PayorID
	AND ov.FinancialReportingID = v.FinancialReportingID
	AND ov.ProviderID = v.ProviderID
	AND ov.ProviderTypeID = v.ProviderTypeID
	AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID
	AND ov.ProviderLineItemID = v.ProviderLineItemID
	AND ov.SubsectionID = v.SubsectionID
	AND ov.UnitTypeID = v.UnitTypeID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for Manager Value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, 
		FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
		FROM fp.FactStatistics cv
		INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID
		WHERE bdgt.BudgetPhaseID = 3) cv
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.DepartmentID = mgrv.DepartmentID
	AND ov.AccountID = mgrv.AccountID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.PayorID = mgrv.PayorID
	AND ov.FinancialReportingID = mgrv.FinancialReportingID
	AND ov.ProviderID = mgrv.ProviderID
	AND ov.ProviderTypeID = mgrv.ProviderTypeID
	AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID
	AND ov.ProviderLineItemID = mgrv.ProviderLineItemID
	AND ov.SubsectionID = mgrv.SubsectionID
	AND ov.UnitTypeID = mgrv.UnitTypeID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewFlexConfigMapping
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	4-27-2023  MY      JAZZ-54239		Add SourceDepartment to view
*************************************************************/
CREATE   VIEW fp.viewFlexConfigMapping
AS
SELECT bc.BudgetConfigID, fcm.EntityGroupConfigID, fcm.SourceDepartmentID, fcm.DepartmentID, fcm.GLAccountID, fcm.StatAccountID, fcm.FlexingTypeID, fcm.PRJobCodeID, fcm.ChargeCodeID, fcm.PatientClassID, fcm.DependentStatisticAccountID
FROM [fp].[FlexConfigMapping] fcm
	INNER JOIN [fp].[EntityGroupConfig] egc ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
GO


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

-- fp.viewGeneralLedger
CREATE VIEW  fp.viewGeneralLedger
 AS
 SELECT 
	gl.GeneralLedgerID,
	gl.BudgetConfigID,
	gl.EntityGroupConfigID,
	gl.DepartmentID,
	gl.FinancialReportingID,
	gl.VariabilityID,
	gl.EntityID,
	gl.AccountID,
	gl.APEModelSectionID,
	msm.APEModelSectionName,

	TargetLockType,
	TargetLockFlag,
	BudgetLockType,
	BudgetLockFlag,
	ProjectionLockType,
	ProjectionLockFlag,
	
	gl.InitialBudgetTotal,
	gl.InitialProjectionTotal,
	TargetAdjustedTotal,
	BudgetAdjustedTotal,
	ProjectionAdjustedTotal AS AdjustedProjectionValueTotal,
	
	gl.InitialBudget01,
	gl.InitialBudget02,
	gl.InitialBudget03,
	gl.InitialBudget04,
	gl.InitialBudget05,
	gl.InitialBudget06,
	gl.InitialBudget07,
	gl.InitialBudget08,
	gl.InitialBudget09,
	gl.InitialBudget10,
	gl.InitialBudget11,
	gl.InitialBudget12,

	gl.InitialProjection01,
	gl.InitialProjection02,
	gl.InitialProjection03,
	gl.InitialProjection04,
	gl.InitialProjection05,
	gl.InitialProjection06,
	gl.InitialProjection07,
	gl.InitialProjection08,
	gl.InitialProjection09,
	gl.InitialProjection10,
	gl.InitialProjection11,
	gl.InitialProjection12,
	
	TargetAdjusted01,
	TargetAdjusted02,
	TargetAdjusted03,
	TargetAdjusted04,
	TargetAdjusted05,
	TargetAdjusted06,
	TargetAdjusted07,
	TargetAdjusted08,
	TargetAdjusted09,
	TargetAdjusted10,
	TargetAdjusted11,
	TargetAdjusted12,

	BudgetAdjusted01,
	BudgetAdjusted02,
	BudgetAdjusted03,
	BudgetAdjusted04,
	BudgetAdjusted05,
	BudgetAdjusted06,
	BudgetAdjusted07,
	BudgetAdjusted08,
	BudgetAdjusted09,
	BudgetAdjusted10,
	BudgetAdjusted11,
	BudgetAdjusted12,

	ProjectionAdjusted01 AS AdjustedProjectionValue01,
	ProjectionAdjusted02 AS AdjustedProjectionValue02,
	ProjectionAdjusted03 AS AdjustedProjectionValue03,
	ProjectionAdjusted04 AS AdjustedProjectionValue04,
	ProjectionAdjusted05 AS AdjustedProjectionValue05,
	ProjectionAdjusted06 AS AdjustedProjectionValue06,
	ProjectionAdjusted07 AS AdjustedProjectionValue07,
	ProjectionAdjusted08 AS AdjustedProjectionValue08,
	ProjectionAdjusted09 AS AdjustedProjectionValue09,
	ProjectionAdjusted10 AS AdjustedProjectionValue10,
	ProjectionAdjusted11 AS AdjustedProjectionValue11,
	ProjectionAdjusted12 AS AdjustedProjectionValue12

FROM fp.GeneralLedger gl
INNER JOIN (SELECT DISTINCT APEModelSEctionID, APEModelSectionName FROM fp.ModelSectionMap) msm ON gl.APEModelSectionID = msm.APEModelSectionID
GO


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

-- fp.viewGeneralLedgerAdjustment
CREATE VIEW fp.viewGeneralLedgerAdjustment
AS 
SELECT AdjustmentGUID,
      BudgetConfigGUID,
      AdjustmentType,
      Value,
      AdjustmentFilterJSON,
      GroupingHierarchyJSON,
      AdjustedProperty,
      Comment,
      AuthorGUID,
      AuthorFullName,
      LastModifiedDateUtc,
      DateCreatedUtc,
      UnitTypeID,
      GroupingGUID,
      TimeClassID,
      BudgetPhaseID,
      ClassificationGroupID,
      ClassificationCategoryID,
      IsRecordDeleted,
      DimensionMemberJson,
      AdjustmentID,
      IsErrored
FROM [fp].[GeneralLedgerAdjustment]
WHERE IsRecordDeleted = 0;
GO


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

-- fp.viewGeneralLedgerAdjustmentAdjustmentJsonBreakdown
CREATE   VIEW fp.viewGeneralLedgerAdjustmentAdjustmentJsonBreakdown
AS 
SELECT
  BudgetConfigGUID,
  AdjustmentID,
  AdjustmentGUID,
  AdjustmentType,
  GroupingGUID,
  CASE WHEN AdjustmentType IN (12, 13, 14) THEN 1 WHEN AdjustmentType IN (0, 2) AND GroupingGUID != '00000000-0000-0000-0000-000000000000' THEN 1 ELSE 0 END IsRollUp,
  IsRecordDeleted,
  IsErrored,
  DepartmentID, 
  DepartmentName, 
  AccountID,
  AccountName,
  FinancialReportingID,
  FinancialReportingName,
  EntityID,
  EntityName,
  AdjustmentFilterJSON,
  AdjJson.DepartmentJSON, 
  AdjJson.AccountJSON, 
  AdjJson.FinancialReportingJSON, 
  AdjJson.EntityJSON
FROM fp.GeneralLedgerAdjustment
CROSS APPLY OPENJSON(AdjustmentFilterJSON)
WITH (
	DepartmentJSON NVARCHAR(MAX) '$.Department' AS JSON,
	AccountJSON NVARCHAR(MAX) '$.Account' AS JSON,
	FinancialReportingJSON NVARCHAR(MAX) '$.FinancialReporting' AS JSON,
	EntityJSON NVARCHAR(MAX) '$.Entity' AS JSON
) AS AdjJson
OUTER APPLY OPENJSON(DepartmentJSON) WITH (
	DepartmentID VARCHAR(200) '$.ID',
	DepartmentName NVARCHAR(100) '$.Name',
	DepartmentCode NVARCHAR(100) '$.Code',
	DepartmentPathID NVARCHAR(100) '$.PathID'
)
OUTER APPLY OPENJSON(AccountJSON) WITH (
	AccountID VARCHAR(200) '$.ID',
	AccountName NVARCHAR(100) '$.Name',
	AccountCode NVARCHAR(100) '$.Code',
	AccountPathID NVARCHAR(100) '$.PathID'
)
OUTER APPLY OPENJSON(FinancialReportingJSON) WITH (
	FinancialReportingID VARCHAR(200) '$.ID',
	FinancialReportingName NVARCHAR(100) '$.Name',
	FinancialReportingCode NVARCHAR(100) '$.Code',
	FinancialReportingPathID NVARCHAR(100) '$.PathID'
)
OUTER APPLY OPENJSON(EntityJSON) WITH (
	EntityID VARCHAR(200) '$.ID',
	EntityName NVARCHAR(100) '$.Name',
	EntityCode NVARCHAR(100) '$.Code',
	EntityPathID NVARCHAR(100) '$.PathID'
)
GO


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

-- fp.viewGeneralLedgerAdjustmentImport
CREATE   VIEW [fp].[viewGeneralLedgerAdjustmentImport]
AS 
SELECT  [RowID]
      ,[AdjustmentGUID]
      ,[DepartmentID]
      ,[AccountID]
      ,[FinancialReportingID]
      ,[FiscalYearID]
      ,[UnitTypeID]
      ,[FiscalMonthID]
      ,[Value]
      ,[Version]
      ,[VariabilityID]
      ,[EntityID]
      ,[TimeClassID]
      ,[BudgetPhaseID]
      ,[IsRecordDeleted]
      ,[AdjustmentID]
	  ,[OriginalUnitTypeID]
FROM [fp].[GeneralLedgerAdjustmentImport]
WHERE IsRecordDeleted = 0
GO


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

-- fp.viewGeneralLedgerDataForStatsToNonStaffing
CREATE VIEW fp.viewGeneralLedgerDataForStatsToNonStaffing AS

SELECT GeneralLedgerID, EntityGroupConfigID, DepartmentID, AccountID, FlexingTypeID, 
		TargetAdjusted01,
		TargetAdjusted02,
		TargetAdjusted03,
		TargetAdjusted04,
		TargetAdjusted05,
		TargetAdjusted06,
		TargetAdjusted07,
		TargetAdjusted08,
		TargetAdjusted09,
		TargetAdjusted10,
		TargetAdjusted11,
		TargetAdjusted12,
		BudgetAdjusted01,
		BudgetAdjusted02,
		BudgetAdjusted03,
		BudgetAdjusted04,
		BudgetAdjusted05,
		BudgetAdjusted06,
		BudgetAdjusted07,
		BudgetAdjusted08,
		BudgetAdjusted09,
		BudgetAdjusted10,
		BudgetAdjusted11,
		BudgetAdjusted12, 
		ProjectionAdjusted01,
		ProjectionAdjusted02,
		ProjectionAdjusted03,
		ProjectionAdjusted04,
		ProjectionAdjusted05,
		ProjectionAdjusted06,
		ProjectionAdjusted07,
		ProjectionAdjusted08,
		ProjectionAdjusted09,
		ProjectionAdjusted10,
		ProjectionAdjusted11,
		ProjectionAdjusted12,TargetDollarsPerUOSAdjusted01,
		 TargetDollarsPerUOSAdjusted02,
		 TargetDollarsPerUOSAdjusted03,
		 TargetDollarsPerUOSAdjusted04,
		 TargetDollarsPerUOSAdjusted05,
		 TargetDollarsPerUOSAdjusted06,
		 TargetDollarsPerUOSAdjusted07,
		 TargetDollarsPerUOSAdjusted08,
		 TargetDollarsPerUOSAdjusted09,
		 TargetDollarsPerUOSAdjusted10,
		 TargetDollarsPerUOSAdjusted11,
		 TargetDollarsPerUOSAdjusted12,  
		 BudgetDollarsPerUOSAdjusted01,
		 BudgetDollarsPerUOSAdjusted02,
		 BudgetDollarsPerUOSAdjusted03,
		 BudgetDollarsPerUOSAdjusted04,
		 BudgetDollarsPerUOSAdjusted05,
		 BudgetDollarsPerUOSAdjusted06,
		 BudgetDollarsPerUOSAdjusted07,
		 BudgetDollarsPerUOSAdjusted08,
		 BudgetDollarsPerUOSAdjusted09,
		 BudgetDollarsPerUOSAdjusted10,
		 BudgetDollarsPerUOSAdjusted11,
		 BudgetDollarsPerUOSAdjusted12,  
		 ProjectionDollarsPerUOSAdjusted01,
		 ProjectionDollarsPerUOSAdjusted02,
		 ProjectionDollarsPerUOSAdjusted03,
		 ProjectionDollarsPerUOSAdjusted04,
		 ProjectionDollarsPerUOSAdjusted05,
		 ProjectionDollarsPerUOSAdjusted06,
		 ProjectionDollarsPerUOSAdjusted07,
		 ProjectionDollarsPerUOSAdjusted08,
		 ProjectionDollarsPerUOSAdjusted09,
		 ProjectionDollarsPerUOSAdjusted10,
		 ProjectionDollarsPerUOSAdjusted11,
		 ProjectionDollarsPerUOSAdjusted12
	FROM [fp].[GeneralLedger] WHERE VariabilityID = 2
GO


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

-- fp.viewGeneralLedgerFlexConfig
CREATE VIEW fp.viewGeneralLedgerFlexConfig
AS
SELECT EntityGroupConfigGUID, DepartmentID, AccountID, FlexMethodID 
FROM [fp].[viewNonStaffingExpenseFlexingConfig] 

UNION ALL

SELECT EntityGroupConfigGUID, DepartmentID, AccountID, FlexMethodID
FROM [fp].[viewRevenueExpenseFlexingConfig] 
	
UNION ALL 

SELECT EntityGroupConfigGUID, DepartmentID, AccountID, FlexMethodID
FROM [fp].[viewDeductionsFlexingConfig]
GO


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

-- fp.viewGeneralLedgerInitialPlanConfigDetailLogs
CREATE   VIEW fp.viewGeneralLedgerInitialPlanConfigDetailLogs AS

SELECT RowID,
      BudgetConfigGUID,
      BudgetConfigID,
      EntityID,
      DepartmentID,
      AccountID,
      FinancialReportingID,
      VariabilityID,
      APEModelSectionID,
      TimeClassID,
	  ProjectionMethodID,
	  TrailingMonths,
	  VersionID
	FROM [fp].[GeneralLedgerInitialPlanConfigDetailHistory]
	UNION
	SELECT RowID,
      BudgetConfigGUID,
      BudgetConfigID,
      EntityID,
      DepartmentID,
      AccountID,
      FinancialReportingID,
      VariabilityID,
      APEModelSectionID,
      TimeClassID,
	  ProjectionMethodID,
	  TrailingMonths,
	  VersionID
	FROM [fp].[GeneralLedgerInitialPlanConfigDetail]
GO


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

-- fp.viewGeneralLedgerItemizationDetail
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2022-08-05  YR          JAZZ-39315  Added column 'CategoryID'
** 2    2022-08-16  DM			JAZZ-35820  Added LastModified columns
** 3    2024-03-15  AO			JAZZ-65797  Table rename
** 4    2024-06-12  NH			JAZZ-69119  Added IsSetValue field
*************************************************************/
CREATE   VIEW [fp].[viewGeneralLedgerItemizationDetail]
AS
WITH deletedAdjustments(CommentGUID) AS (SELECT OriginalAdjustmentCommentGUID AS CommentGUID
                                                                                            FROM      fp.GeneralLedgerItemizationDetailLink
                                                                                            UNION ALL
                                                                                            SELECT InverseAdjustmentCommentGUID AS CommentGUID
                                                                                            FROM     fp.GeneralLedgerItemizationDetailLink)
    SELECT glid.CommentGUID, glid.AdjustmentID, glid.BudgetConfigID, glid.DepartmentID, glid.FinancialReportingID, glid.AccountID, glid.TimeClassID, glid.DollarsValue, glid.Comment, glid.CategoryID, glid.SortOrder, glid.SpreadID, glid.IsMarkedForDeletion, 
                      glid.AuthorGUID, glid.AuthorFullName, glid.DateCreatedUTC, glid.LastModifiedAuthorFullName, glid.LastModifiedDateUtc, glid.LastModifiedAuthorGUID, glid.SpreadPercentage01, glid.SpreadPercentage02, glid.SpreadPercentage03, glid.SpreadPercentage04, glid.SpreadPercentage05, glid.SpreadPercentage06, 
                      glid.SpreadPercentage07, glid.SpreadPercentage08, glid.SpreadPercentage09, glid.SpreadPercentage10, glid.SpreadPercentage11, glid.SpreadPercentage12, glid.TotalImportedValue, glid.IsSetValue
    FROM     fp.GeneralLedgerFixedDetail AS glid LEFT OUTER JOIN
                      deletedAdjustments AS del ON glid.CommentGUID = del.CommentGUID
    WHERE  (del.CommentGUID IS NULL)
GO


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

-- fp.viewGeneralLedgerManagerComments
CREATE view [fp].[viewGeneralLedgerManagerComments]
as
select
	ROW_NUMBER() OVER(ORDER BY DepartmentID ASC) AS RowID,
	bc.BudgetConfigID,
	glc.DepartmentID,
	glc.AccountID,
	glc.FiscalYearID,
	glc.Comment,
	glc.InitialValue,
	glc.DeltaValue as Adjustment,
	glc.InitialValue + glc.DeltaValue as FinalValue,
	glc.DateCreatedUtc,
	glc.AuthorFullName,
	glc.DateModifiedUtc,
	CAST(glc.DateCreatedUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' as DateTime) as DateCreated,
    CAST(glc.DateModifiedUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' as DateTime) as DateModified,
	dc.CalendarDateTime as DateCreatedDate
from
	fp.GeneralLedgerManagerAdjustmentComment as glc 
	inner join fp.BudgetConfig as bc on bc.BudgetConfigGUID = glc.BudgetConfigGUID
	inner join [fw].[DimDate] as dc on CAST(glc.DateCreatedUtc AS DATE) = dc.CalendarDateTime
GO


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

-- fp.viewGeneralLedgerMyBudgetReportData
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI				Description
** 1    2021-09-03  MY          JAZZ-23920		Filter out deleted itemized adjustments from report
** 2    2022-06-08  DM			JAZZ-37699		Added sub-account detail adjustments for new data type
** 3    2022-06-28  YR			JAZZ-36123		Rename 'Comment' to 'Description' 
** 4    2022-07-07  MV			JAZZ-39283		Add Sub Account Detail CategoryID
** 5    2022-07-20	SD			JAZZ-35821		Add variable adjustments
** 6    2022-08-05	YR			JAZZ-39315		Add CategoryID for viewGeneralLedgerItemizationDetail
** 7	2022-08-17  DM			JAZZ-35820		Added LastModified columns for viewGeneralLedgerItemizationDetail
** 8	2022-08-22	SD			JAZZ-42351		Added grouping stats data by budgetConfig 
** 9	2023-08-25	MY			JAZZ-58152		Update to new structure
** 10  2024-05-03  MZ			JAZZ-69734		Renamed GeneralLedgerAdjustmentItemization to GeneralLedgerMyBudgetAdjustment
** 11  2024-06-12  NH         JAZZ-69119		My Budgets Non-Staffing redesign: Update Itemization Report to show Set Value adjustments
** 12  2024-07-09  NH         JAZZ-73268		Non-Staffing and Other Revenue Non-itemized: update Description to be a Comment
** 13  2024-07-21  NH         JAZZ-73268		Non-Staffing and Other Revenue Non-itemized: updated Description/Comment
*************************************************************/
CREATE   VIEW [fp].[viewGeneralLedgerMyBudgetReportData]
AS

	-- TODO: The formatting of this view is attorciious and needs to be cleaned up the next time someone works on this view for a fix.

WITH distinctVariableDetails AS (
	   SELECT
		f.BudgetConfigID, f.AccountID, f.DepartmentID, f.FinancialReportingID, f.TimeClassID, f.AdjustmentID, f.DollarsValue, a.Comment_All as Comment, a.AuthorFullName_All as AuthorFullName , a.DateCreated,
		ROW_NUMBER() OVER(PARTITION BY f.BudgetConfigID, f.AccountID, f.DepartmentID, f.FinancialReportingID, f.TimeClassID ORDER BY f.DateCreatedUTC DESC) AS row_number
	  FROM [fp].[GeneralLedgerVariableDetail] f
	  INNER JOIN 
		  (
		  select t.BudgetConfigID, t.AccountID, t.DepartmentID, t.FinancialReportingID, t.TimeClassID,
		  STRING_AGG(CAST(t.AuthorFullName AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As AuthorFullName_All,	
		  STRING_AGG(CAST(t.Comment AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As Comment_All,	
		  STRING_AGG(CONVERT(VARCHAR, CAST(t.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) as DateCreated
		  From [fp].[GeneralLedgerVariableDetail]  t		  
		  LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
		  Group By BudgetConfigID, AccountID, DepartmentID, FinancialReportingID, TimeClassID
		  ) a on f.BudgetConfigID = a.BudgetConfigID 
			  and f.AccountID = a.AccountID
			  and f.DepartmentID = a.DepartmentID
			  and f.FinancialReportingID = a.FinancialReportingID
			  and f.TimeClassID = a.TimeClassID 
	),
	 distinctFixedDetails AS (
	   SELECT
		f.BudgetConfigID,
		f.AccountID, 
		f.DepartmentID, 
		f.FinancialReportingID,
		f.TimeClassID,
		f.AdjustmentID, 
		f.DollarsValue, 
		a.Comment_All as Comment,
		a.AuthorFullName_All as AuthorFullName,
		a.DateCreated,
		f.SpreadID,
		f.SpreadPercentage01, 
		f.SpreadPercentage02,
		f.SpreadPercentage03,
		f.SpreadPercentage04,
		f.SpreadPercentage05,
		f.SpreadPercentage06,
		f.SpreadPercentage07,
		f.SpreadPercentage08,
		f.SpreadPercentage09,
		f.SpreadPercentage10,
		f.SpreadPercentage11,
		f.SpreadPercentage12,
		ROW_NUMBER() OVER(PARTITION BY f.BudgetConfigID, f.AccountID, f.DepartmentID, f.FinancialReportingID, f.TimeClassID ORDER BY f.DateCreatedUTC DESC) AS row_number
	  FROM [fp].GeneralLedgerFixedDetail f
	  INNER JOIN 
		  (
		  select t.BudgetConfigID, t.AccountID, t.DepartmentID, t.FinancialReportingID, t.TimeClassID,
		  STRING_AGG(CAST(t.AuthorFullName AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As AuthorFullName_All,	
		  STRING_AGG(CAST(t.Comment AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As Comment_All,	
		  STRING_AGG(CONVERT(VARCHAR, CAST(t.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) as DateCreated
		  From [fp].GeneralLedgerFixedDetail  t		  
		  LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
		  Group By BudgetConfigID, AccountID, DepartmentID, FinancialReportingID, TimeClassID
		  ) a on f.BudgetConfigID = a.BudgetConfigID 
			  and f.AccountID = a.AccountID
			  and f.DepartmentID = a.DepartmentID
			  and f.FinancialReportingID = a.FinancialReportingID
			  and f.TimeClassID = a.TimeClassID
		   WHERE IsSetValue = 1 
		   ),

	distinctGLAdjItemized AS (select DISTINCT AccountID, DepartmentID, BudgetConfigID, EntityID, FinancialReportingID, TimeClassID, VariabilityID from
		fp.GeneralLedgerMyBudgetAdjustment),

	projectionGLData AS (
			select gl.AccountID, gl.DepartmentID, gl.EntityID, gl.FinancialReportingID, gl.BudgetConfigID, 
			gl.ProjectionAdjusted01 AS AdjustedValue01, gl.ProjectionAdjusted02 AS AdjustedValue02, gl.ProjectionAdjusted03 AS AdjustedValue03, 
			gl.ProjectionAdjusted04 AS AdjustedValue04, gl.ProjectionAdjusted05 AS AdjustedValue05, gl.ProjectionAdjusted06 AS AdjustedValue06, 
			gl.ProjectionAdjusted07 AS AdjustedValue07, gl.ProjectionAdjusted08 AS AdjustedValue08, gl.ProjectionAdjusted09 AS AdjustedValue09, 
			gl.ProjectionAdjusted10 AS AdjustedValue10, gl.ProjectionAdjusted11 AS AdjustedValue11, gl.ProjectionAdjusted12 AS AdjustedValue12, 
			gl.ProjectionAdjustedTotal AS AdjustedValueTotal
		from
		fp.GeneralLedger gl
		INNER JOIN distinctGLAdjItemized gli
		on 
		gli.AccountID = gl.AccountID and 
		gli.DepartmentID = gl.DepartmentID and 
		gli.BudgetConfigID = gl.BudgetConfigID and 
		gli.EntityID = gl.EntityID and 
		gli.FinancialReportingID = gl.FinancialReportingID and
		gl.VariabilityID = gli.VariabilityID and
		gli.TimeClassID = 12 and
		gl.VariabilityID = 2
		),

	projectionGLFixedData AS (
			select gl.AccountID, gl.DepartmentID, gl.EntityID, gl.FinancialReportingID, gl.BudgetConfigID, 
			gl.ProjectionAdjusted01 AS AdjustedValue01, gl.ProjectionAdjusted02 AS AdjustedValue02, gl.ProjectionAdjusted03 AS AdjustedValue03, 
			gl.ProjectionAdjusted04 AS AdjustedValue04, gl.ProjectionAdjusted05 AS AdjustedValue05, gl.ProjectionAdjusted06 AS AdjustedValue06, 
			gl.ProjectionAdjusted07 AS AdjustedValue07, gl.ProjectionAdjusted08 AS AdjustedValue08, gl.ProjectionAdjusted09 AS AdjustedValue09, 
			gl.ProjectionAdjusted10 AS AdjustedValue10, gl.ProjectionAdjusted11 AS AdjustedValue11, gl.ProjectionAdjusted12 AS AdjustedValue12, 
			gl.ProjectionAdjustedTotal AS AdjustedValueTotal
		from
		fp.GeneralLedger gl
		INNER JOIN distinctGLAdjItemized gli
		on 
		gli.AccountID = gl.AccountID and 
		gli.DepartmentID = gl.DepartmentID and 
		gli.BudgetConfigID = gl.BudgetConfigID and 
		gli.EntityID = gl.EntityID and 
		gli.FinancialReportingID = gl.FinancialReportingID and
		gl.VariabilityID = gli.VariabilityID and
		gli.TimeClassID = 12 and
		gl.VariabilityID = 1
		),
		
	statsData AS (SELECT 
	                glai.AccountID,
					glai.DepartmentID,
					s.BudgetConfigID,
				    ISNULL(SUM(s.ManagerAdjustedValue01),0) AS ManagerAdjustedValue01,
					ISNULL(SUM(s.ManagerAdjustedValue02),0) AS ManagerAdjustedValue02,
					ISNULL(SUM(s.ManagerAdjustedValue03),0) AS ManagerAdjustedValue03,
					ISNULL(SUM(s.ManagerAdjustedValue04),0) AS ManagerAdjustedValue04,
					ISNULL(SUM(s.ManagerAdjustedValue05),0) AS ManagerAdjustedValue05,
					ISNULL(SUM(s.ManagerAdjustedValue06),0) AS ManagerAdjustedValue06,
					ISNULL(SUM(s.ManagerAdjustedValue07),0) AS ManagerAdjustedValue07,
					ISNULL(SUM(s.ManagerAdjustedValue08),0) AS ManagerAdjustedValue08,
					ISNULL(SUM(s.ManagerAdjustedValue09),0) AS ManagerAdjustedValue09,
					ISNULL(SUM(s.ManagerAdjustedValue10),0) AS ManagerAdjustedValue10,
					ISNULL(SUM(s.ManagerAdjustedValue11),0) AS ManagerAdjustedValue11,
					ISNULL(SUM(s.ManagerAdjustedValue12),0) AS ManagerAdjustedValue12,					
					ISNULL(SUM(s.ManagerAdjustedValueTotal),0) AS ManagerAdjustedValueTotal,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue01),0) AS ManagerAdjustedProjectionValue01,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue02),0) AS ManagerAdjustedProjectionValue02,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue03),0) AS ManagerAdjustedProjectionValue03,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue04),0) AS ManagerAdjustedProjectionValue04,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue05),0) AS ManagerAdjustedProjectionValue05,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue06),0) AS ManagerAdjustedProjectionValue06,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue07),0) AS ManagerAdjustedProjectionValue07,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue08),0) AS ManagerAdjustedProjectionValue08,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue09),0) AS ManagerAdjustedProjectionValue09,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue10),0) AS ManagerAdjustedProjectionValue10,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue11),0) AS ManagerAdjustedProjectionValue11,
					ISNULL(SUM(s.ManagerAdjustedProjectionValue12),0) AS ManagerAdjustedProjectionValue12,					
					ISNULL(SUM(s.ManagerAdjustedProjectionValueTotal),0) AS ManagerAdjustedProjectionValueTotal,
					glai.TimeClassID
            From [fp].[viewFactStatistics_Pivoted] s 
				INNER JOIN distinctGLAdjItemized as glai 
					on glai.DepartmentID = s.DepartmentID
					AND glai.BudgetConfigID = s.BudgetConfigID 
					AND glai.VariabilityID = 2
				INNER JOIN fp.BudgetConfig bc on bc.BudgetConfigID = glai.BudgetConfigID
				INNER JOIN fp.EntityGroupConfig egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID
				INNER JOIN ( 
	                SELECT DISTINCT DepartmentID, GLAccountID, StatAccountID, EntityGroupConfigID 
	                FROM [fp].[FlexConfigMapping]
                ) As fcm 
	                ON glai.DepartmentID = fcm.DepartmentID 
	                AND glai.AccountID = fcm.GLAccountID 
	                AND egc.EntityGroupConfigID = fcm.EntityGroupConfigID
					AND s.AccountID = fcm.StatAccountID
				Group By glai.AccountID, glai.DepartmentID, glai.TimeClassID, s.BudgetConfigID)

SELECT a.BudgetConfigID, 
		a.EntityID,
		a.DepartmentID,
		a.AccountID,
		a.TimeClassID,
		a.DateCreated,
		a.AuthorFullName,
		a.Comment AS 'Description/Comment',
		a.CategoryID,
		a.ItemizationDataTypeID,
		a.Month01,
		a.Month02,
		a.Month03,
		a.Month04,
		a.Month05,
		a.Month06,
		a.Month07,
		a.Month08,
		a.Month09,
		a.Month10,
		a.Month11,
		a.Month12,
		a.TotalValue, ROW_NUMBER() OVER(ORDER BY BUDGETCONFIGID) AS RowID
FROM (
	SELECT 
		rd.BudgetConfigID, 
		rd.EntityID,
		rd.DepartmentID,
		rd.AccountID,
		rd.TimeClassID,
		''  AS DateCreated,
		'' AS AuthorFullName,
		'' AS Comment,
		0 AS CategoryID,
		rd.ItemizationDataTypeID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		TotalValue
	FROM fp.GeneralLedgerItemizationReportData rd

	UNION ALL

	-- select variable admin projection adj
Select 
		m.BudgetConfigID,
		m.EntityID, 
		m.DepartmentID,
		m.AccountID, 
		m.TimeClassID,
		m.DateCreated,
		m.AuthorFullName,
		m.Comment,
		m.CategoryID,
		m.ItemizationDataTypeID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		m.AdjustedValueTotal - (m.ManagerAdjMonth01 + m.ManagerAdjMonth02 + m.ManagerAdjMonth03 + m.ManagerAdjMonth04 + m.ManagerAdjMonth05 + m.ManagerAdjMonth06 + m.ManagerAdjMonth07 + m.ManagerAdjMonth08 + m.ManagerAdjMonth09 + m.ManagerAdjMonth10 + m.ManagerAdjMonth11 + m.ManagerAdjMonth12) AS TotalValue
		from (
		   SELECT 
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,
		'' AS  DateCreated,
		'' AS AuthorFullName,
		'' AS Comment,
		0 AS CategoryID,
		6 AS ItemizationDataTypeID,
		CASE WHEN bc.MonthsLoaded >= 1  THEN 0 ELSE phd.AdjustedValue01 - gli.Value01 * sd.ManagerAdjustedProjectionValue01 END AS Month01,
		CASE WHEN bc.MonthsLoaded >= 2  THEN 0 ELSE phd.AdjustedValue02 - gli.Value02 * sd.ManagerAdjustedProjectionValue02 END AS Month02,
		CASE WHEN bc.MonthsLoaded >= 3  THEN 0 ELSE phd.AdjustedValue03 - gli.Value03 * sd.ManagerAdjustedProjectionValue03 END AS Month03,
		CASE WHEN bc.MonthsLoaded >= 4  THEN 0 ELSE phd.AdjustedValue04 - gli.Value04 * sd.ManagerAdjustedProjectionValue04 END AS Month04,
		CASE WHEN bc.MonthsLoaded >= 5  THEN 0 ELSE phd.AdjustedValue05 - gli.Value05 * sd.ManagerAdjustedProjectionValue05 END AS Month05,
		CASE WHEN bc.MonthsLoaded >= 6  THEN 0 ELSE phd.AdjustedValue06 - gli.Value06 * sd.ManagerAdjustedProjectionValue06 END AS Month06,
		CASE WHEN bc.MonthsLoaded >= 7  THEN 0 ELSE phd.AdjustedValue07 - gli.Value07 * sd.ManagerAdjustedProjectionValue07 END AS Month07,
		CASE WHEN bc.MonthsLoaded >= 8  THEN 0 ELSE phd.AdjustedValue08 - gli.Value08 * sd.ManagerAdjustedProjectionValue08 END AS Month08,
		CASE WHEN bc.MonthsLoaded >= 9  THEN 0 ELSE phd.AdjustedValue09 - gli.Value09 * sd.ManagerAdjustedProjectionValue09 END AS Month09,
		CASE WHEN bc.MonthsLoaded >= 10 THEN 0 ELSE phd.AdjustedValue10 - gli.Value10 * sd.ManagerAdjustedProjectionValue10 END AS Month10,
		CASE WHEN bc.MonthsLoaded >= 11 THEN 0 ELSE phd.AdjustedValue11 - gli.Value11 * sd.ManagerAdjustedProjectionValue11 END AS Month11,
		CASE WHEN bc.MonthsLoaded >= 12 THEN 0 ELSE phd.AdjustedValue12 - gli.Value12 * sd.ManagerAdjustedProjectionValue12 END AS Month12,
			
		CASE WHEN bc.MonthsLoaded >= 1  THEN phd.AdjustedValue01 ELSE  gli.Value01 * sd.ManagerAdjustedProjectionValue01 END AS ManagerAdjMonth01,
		CASE WHEN bc.MonthsLoaded >= 2  THEN phd.AdjustedValue02 ELSE  gli.Value02 * sd.ManagerAdjustedProjectionValue02 END AS ManagerAdjMonth02,
		CASE WHEN bc.MonthsLoaded >= 3  THEN phd.AdjustedValue03 ELSE  gli.Value03 * sd.ManagerAdjustedProjectionValue03 END AS ManagerAdjMonth03,
		CASE WHEN bc.MonthsLoaded >= 4  THEN phd.AdjustedValue04 ELSE  gli.Value04 * sd.ManagerAdjustedProjectionValue04 END AS ManagerAdjMonth04,
		CASE WHEN bc.MonthsLoaded >= 5  THEN phd.AdjustedValue05 ELSE  gli.Value05 * sd.ManagerAdjustedProjectionValue05 END AS ManagerAdjMonth05,
		CASE WHEN bc.MonthsLoaded >= 6  THEN phd.AdjustedValue06 ELSE  gli.Value06 * sd.ManagerAdjustedProjectionValue06 END AS ManagerAdjMonth06,
		CASE WHEN bc.MonthsLoaded >= 7  THEN phd.AdjustedValue07 ELSE  gli.Value07 * sd.ManagerAdjustedProjectionValue07 END AS ManagerAdjMonth07,
		CASE WHEN bc.MonthsLoaded >= 8  THEN phd.AdjustedValue08 ELSE  gli.Value08 * sd.ManagerAdjustedProjectionValue08 END AS ManagerAdjMonth08,
		CASE WHEN bc.MonthsLoaded >= 9  THEN phd.AdjustedValue09 ELSE  gli.Value09 * sd.ManagerAdjustedProjectionValue09 END AS ManagerAdjMonth09,
		CASE WHEN bc.MonthsLoaded >= 10 THEN phd.AdjustedValue10 ELSE  gli.Value10 * sd.ManagerAdjustedProjectionValue10 END AS ManagerAdjMonth10,
		CASE WHEN bc.MonthsLoaded >= 11 THEN phd.AdjustedValue11 ELSE  gli.Value11 * sd.ManagerAdjustedProjectionValue11 END AS ManagerAdjMonth11,
		CASE WHEN bc.MonthsLoaded >= 12 THEN phd.AdjustedValue12 ELSE  gli.Value12 * sd.ManagerAdjustedProjectionValue12 END AS ManagerAdjMonth12,
		phd.AdjustedValueTotal
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
	INNER JOIN projectionGLData phd on 
			gli.BudgetConfigID = phd.BudgetConfigID
			AND gli.DepartmentID = phd.DepartmentID
			AND gli.FinancialReportingID = phd.FinancialReportingID
			AND gli.AccountID = phd.AccountID
			AND gli.EntityID = phd.EntityID
			AND gli.FinancialReportingID = phd.FinancialReportingID
	INNER JOIN distinctVariableDetails glvd on 
			gli.AdjustmentID = glvd.AdjustmentID
			AND gli.BudgetConfigID = glvd.BudgetConfigID
			AND gli.DepartmentID = glvd.DepartmentID
			AND gli.FinancialReportingID = glvd.FinancialReportingID
			AND gli.AccountID = glvd.AccountID
			AND gli.FinancialReportingID = glvd.FinancialReportingID
			AND gli.TimeClassID = glvd.TimeClassID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'		
		INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = gli.TimeClassID and gli.BudgetConfigID = sd.BudgetConfigID
		WHERE 
		gli.TimeClassID = 12 
		AND gli.VariabilityID = 2
		and glvd.row_number = 1 ) m
		where (
		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 )

	UNION ALL

	-- select variable admin budget adj
	select
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,
		'' AS DateCreated,
		'' AS AuthorFullName,
		'' as Comment,
		0 AS CategoryID,
		6 AS ItemizationDataTypeID,
		gl.BudgetAdjusted01 - gli.Value01 * sd.ManagerAdjustedValue01 AS Month01,
		gl.BudgetAdjusted02 - gli.Value02 * sd.ManagerAdjustedValue02 AS Month02,
		gl.BudgetAdjusted03 - gli.Value03 * sd.ManagerAdjustedValue03 AS Month03,
		gl.BudgetAdjusted04 - gli.Value04 * sd.ManagerAdjustedValue04 AS Month04,
		gl.BudgetAdjusted05 - gli.Value05 * sd.ManagerAdjustedValue05 AS Month05,
		gl.BudgetAdjusted06 - gli.Value06 * sd.ManagerAdjustedValue06 AS Month06,
		gl.BudgetAdjusted07 - gli.Value07 * sd.ManagerAdjustedValue07 AS Month07,
		gl.BudgetAdjusted08 - gli.Value08 * sd.ManagerAdjustedValue08 AS Month08,
		gl.BudgetAdjusted09 - gli.Value09 * sd.ManagerAdjustedValue09 AS Month09,
		gl.BudgetAdjusted10 - gli.Value10 * sd.ManagerAdjustedValue10 AS Month10,
		gl.BudgetAdjusted11 - gli.Value11 * sd.ManagerAdjustedValue11 AS Month11,
		gl.BudgetAdjusted12 - gli.Value12 * sd.ManagerAdjustedValue12 AS Month12,
		gl.BudgetAdjustedTotal - glvd.DollarsValue * sd.ManagerAdjustedValueTotal AS TotalValue
		from fp.GeneralLedger gl
		Inner join fp.GeneralLedgerMyBudgetAdjustment gli on 
					 gli.BudgetConfigID = gl.BudgetConfigID
					AND gli.DepartmentID = gl.DepartmentID
					AND gli.FinancialReportingID = gl.FinancialReportingID
					AND gli.AccountID = gl.AccountID
					AND gli.TimeClassID = 2
			INNER JOIN distinctVariableDetails glvd on gli.AdjustmentID = glvd.AdjustmentID
					AND gli.BudgetConfigID = glvd.BudgetConfigID
					AND gli.DepartmentID = glvd.DepartmentID
					AND gli.FinancialReportingID = glvd.FinancialReportingID
					AND gli.AccountID = glvd.AccountID
					AND gli.TimeClassID = glvd.TimeClassID
				JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
				LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
				INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = 2 and gli.BudgetConfigID = sd.BudgetConfigID
				Where 
				gl.VariabilityID  = 2 and 
				glvd.row_number = 1 and
				(   gl.BudgetAdjusted01 - gli.Value01 * sd.ManagerAdjustedValue01 <> 0 OR
					gl.BudgetAdjusted02 - gli.Value02 * sd.ManagerAdjustedValue02 <> 0 OR
					gl.BudgetAdjusted03 - gli.Value03 * sd.ManagerAdjustedValue03 <> 0 OR
					gl.BudgetAdjusted04 - gli.Value04 * sd.ManagerAdjustedValue04 <> 0 OR
					gl.BudgetAdjusted05 - gli.Value05 * sd.ManagerAdjustedValue05 <> 0 OR
					gl.BudgetAdjusted06 - gli.Value06 * sd.ManagerAdjustedValue06 <> 0 OR
					gl.BudgetAdjusted07 - gli.Value07 * sd.ManagerAdjustedValue07 <> 0 OR
					gl.BudgetAdjusted08 - gli.Value08 * sd.ManagerAdjustedValue08 <> 0 OR
					gl.BudgetAdjusted09 - gli.Value09 * sd.ManagerAdjustedValue09 <> 0 OR
					gl.BudgetAdjusted10 - gli.Value10 * sd.ManagerAdjustedValue10 <> 0 OR
					gl.BudgetAdjusted11 - gli.Value11 * sd.ManagerAdjustedValue11 <> 0 OR
					gl.BudgetAdjusted12 - gli.Value12 * sd.ManagerAdjustedValue12 <> 0 )


	UNION ALL

	SELECT 
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,	
		CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN CONVERT(varchar, CAST(glid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime))
			ELSE CONCAT(CONVERT(varchar, CAST(glid.DateCreatedUtc  AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME)), ', ',
			CONVERT(varchar, CAST(glid.LastModifiedDateUtc  AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME))) END AS DateCreated,
		CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN glid.AuthorFullName ELSE glid.AuthorFullName + ', ' + glid.LastModifiedAuthorFullName END AS AuthorFullName,
		glid.Comment,
		glid.CategoryID,
		3 AS ItemizationDataTypeID,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage01 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage01 as decimal(19,8))
		END AS Month01,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage02 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage02 as decimal(19,8))
		END AS Month02,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage03 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage03 as decimal(19,8))
		END AS Month03,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage04 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage04 as decimal(19,8))
		END AS Month04,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage05 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage05 as decimal(19,8))
		END AS Month05,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage06 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage06 as decimal(19,8))
		END AS Month06,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage07 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage07 as decimal(19,8))
		END AS Month07,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage08 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage08 as decimal(19,8))
		END AS Month08,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage09 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage09 as decimal(19,8))
		END AS Month09,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage10 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage10 as decimal(19,8))
		END AS Month10,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage11 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage11 as decimal(19,8))
		END AS Month11,
		CASE WHEN glid.SpreadID = 0
			 THEN glid.DollarsValue / 12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage12 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage12 as decimal(19,8))
		END AS Month12,
		glid.DollarsValue as TotalValue
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
		JOIN fp.viewGeneralLedgerItemizationDetail glid	ON gli.AdjustmentID = glid.AdjustmentID
			AND gli.BudgetConfigID = glid.BudgetConfigID
			AND gli.DepartmentID = glid.DepartmentID
			AND gli.FinancialReportingID = glid.FinancialReportingID
			AND gli.AccountID = glid.AccountID
			AND gli.TimeClassID = glid.TimeClassID
		JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
	WHERE 
		glid.TimeClassID = 2 
		AND gli.VariabilityID = 1
		AND glid.IsSetValue = 0

	UNION ALL

	SELECT 
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,	
		CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN CONVERT(varchar, CAST(glid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime))
			ELSE CONCAT(CONVERT(varchar, CAST(glid.DateCreatedUtc  AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME)), ', ',
			CONVERT(varchar, CAST(glid.LastModifiedDateUtc  AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME))) END AS DateCreated,
		CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN glid.AuthorFullName ELSE glid.AuthorFullName + ', ' + glid.LastModifiedAuthorFullName END AS AuthorFullName,
		glid.Comment,
		glid.CategoryID,
		3 AS ItemizationDataTypeID,	
		CASE WHEN bc.MonthsLoaded < 1  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month01,
		CASE WHEN bc.MonthsLoaded < 2  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month02,
		CASE WHEN bc.MonthsLoaded < 3  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month03,
		CASE WHEN bc.MonthsLoaded < 4  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month04,
		CASE WHEN bc.MonthsLoaded < 5  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month05,
		CASE WHEN bc.MonthsLoaded < 6  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month06,
		CASE WHEN bc.MonthsLoaded < 7  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month07,
		CASE WHEN bc.MonthsLoaded < 8  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month08,
		CASE WHEN bc.MonthsLoaded < 9  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month09,
		CASE WHEN bc.MonthsLoaded < 10 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month10,
		CASE WHEN bc.MonthsLoaded < 11 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month11,
		CASE WHEN bc.MonthsLoaded < 12  THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month12,
		glid.DollarsValue as TotalValue
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
		JOIN fp.viewGeneralLedgerItemizationDetail glid	ON gli.AdjustmentID = glid.AdjustmentID
			AND gli.BudgetConfigID = glid.BudgetConfigID
			AND gli.DepartmentID = glid.DepartmentID
			AND gli.FinancialReportingID = glid.FinancialReportingID
			AND gli.AccountID = glid.AccountID
			AND gli.TimeClassID = glid.TimeClassID
		JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
	WHERE 
		glid.TimeClassID = 12 
		and gli.VariabilityID = 1
		AND glid.IsSetValue = 0
		
UNION ALL

SELECT
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,	
		glvd.DateCreated, 		
		glvd.AuthorFullName AS AuthorFullName,
		glvd.Comment,
		0 AS CategoryID,
		3 AS ItemizationDataTypeID,	
		CASE WHEN bc.MonthsLoaded < 1  THEN gli.Value01 ELSE 0 END AS Month01,
		CASE WHEN bc.MonthsLoaded < 2  THEN gli.Value02 ELSE 0 END AS Month02,
		CASE WHEN bc.MonthsLoaded < 3  THEN gli.Value03 ELSE 0 END AS Month03,
		CASE WHEN bc.MonthsLoaded < 4  THEN gli.Value04 ELSE 0 END AS Month04,
		CASE WHEN bc.MonthsLoaded < 5  THEN gli.Value05 ELSE 0 END AS Month05,
		CASE WHEN bc.MonthsLoaded < 6  THEN gli.Value06 ELSE 0 END AS Month06,
		CASE WHEN bc.MonthsLoaded < 7  THEN gli.Value07 ELSE 0 END AS Month07,
		CASE WHEN bc.MonthsLoaded < 8  THEN gli.Value08 ELSE 0 END AS Month08,
		CASE WHEN bc.MonthsLoaded < 9  THEN gli.Value09 ELSE 0 END AS Month09,
		CASE WHEN bc.MonthsLoaded < 10 THEN gli.Value10 ELSE 0 END AS Month10,
		CASE WHEN bc.MonthsLoaded < 11 THEN gli.Value11 ELSE 0 END AS Month11,
		CASE WHEN bc.MonthsLoaded < 12 THEN gli.Value12 ELSE 0 END AS Month12,
		glvd.DollarsValue as TotalValue
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
		JOIN distinctFixedDetails glvd	ON gli.AdjustmentID = glvd.AdjustmentID
			AND gli.BudgetConfigID = glvd.BudgetConfigID
			AND gli.DepartmentID = glvd.DepartmentID
			AND gli.FinancialReportingID = glvd.FinancialReportingID
			AND gli.AccountID = glvd.AccountID
			AND gli.TimeClassID = glvd.TimeClassID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
	WHERE 
		glvd.TimeClassID = 12 
		AND gli.VariabilityID = 1
		AND glvd.row_number = 1 

	UNION ALL

	Select 
		m.BudgetConfigID,
		m.EntityID, 
		m.DepartmentID,
		m.AccountID, 
		m.TimeClassID,
		m.DateCreated,
		m.AuthorFullName,
		m.Comment,
		m.CategoryID,
		m.ItemizationDataTypeID,
		Month01,
		Month02,
		Month03,
		Month04,
		Month05,
		Month06,
		Month07,
		Month08,
		Month09,
		Month10,
		Month11,
		Month12,
		m.AdjustedValueTotal - (m.ManagerAdjMonth01 + m.ManagerAdjMonth02 + m.ManagerAdjMonth03 + m.ManagerAdjMonth04 + m.ManagerAdjMonth05 + m.ManagerAdjMonth06 + m.ManagerAdjMonth07 + m.ManagerAdjMonth08 + m.ManagerAdjMonth09 + m.ManagerAdjMonth10 + m.ManagerAdjMonth11 + m.ManagerAdjMonth12) AS TotalValue
		from (SELECT
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,	
		'' AS  DateCreated,
		'' AS AuthorFullName,
		'' AS Comment,
		0 AS CategoryID,
		2 AS ItemizationDataTypeID,	
		CASE WHEN bc.MonthsLoaded < 1  THEN phd.AdjustedValue01 - gli.Value01 ELSE 0 END AS Month01,
		CASE WHEN bc.MonthsLoaded < 2  THEN phd.AdjustedValue02 - gli.Value02 ELSE 0 END AS Month02,
		CASE WHEN bc.MonthsLoaded < 3  THEN phd.AdjustedValue03 - gli.Value03 ELSE 0 END AS Month03,
		CASE WHEN bc.MonthsLoaded < 4  THEN phd.AdjustedValue04 - gli.Value04 ELSE 0 END AS Month04,
		CASE WHEN bc.MonthsLoaded < 5  THEN phd.AdjustedValue05 - gli.Value05 ELSE 0 END AS Month05,
		CASE WHEN bc.MonthsLoaded < 6  THEN phd.AdjustedValue06 - gli.Value06 ELSE 0 END AS Month06,
		CASE WHEN bc.MonthsLoaded < 7  THEN phd.AdjustedValue07 - gli.Value07 ELSE 0 END AS Month07,
		CASE WHEN bc.MonthsLoaded < 8  THEN phd.AdjustedValue08 - gli.Value08 ELSE 0 END AS Month08,
		CASE WHEN bc.MonthsLoaded < 9  THEN phd.AdjustedValue09 - gli.Value09 ELSE 0 END AS Month09,
		CASE WHEN bc.MonthsLoaded < 10 THEN phd.AdjustedValue10 - gli.Value10 ELSE 0 END AS Month10,
		CASE WHEN bc.MonthsLoaded < 11 THEN phd.AdjustedValue11 - gli.Value11 ELSE 0 END AS Month11,
		CASE WHEN bc.MonthsLoaded < 12 THEN phd.AdjustedValue12 - gli.Value12 ELSE 0 END AS Month12,
	    CASE WHEN bc.MonthsLoaded < 1  THEN gli.Value01 ELSE 0 END AS ManagerAdjMonth01,
		CASE WHEN bc.MonthsLoaded < 2  THEN gli.Value02 ELSE 0 END AS ManagerAdjMonth02,
		CASE WHEN bc.MonthsLoaded < 3  THEN gli.Value03 ELSE 0 END AS ManagerAdjMonth03,
		CASE WHEN bc.MonthsLoaded < 4  THEN gli.Value04 ELSE 0 END AS ManagerAdjMonth04,
		CASE WHEN bc.MonthsLoaded < 5  THEN gli.Value05 ELSE 0 END AS ManagerAdjMonth05,
		CASE WHEN bc.MonthsLoaded < 6  THEN gli.Value06 ELSE 0 END AS ManagerAdjMonth06,
		CASE WHEN bc.MonthsLoaded < 7  THEN gli.Value07 ELSE 0 END AS ManagerAdjMonth07,
		CASE WHEN bc.MonthsLoaded < 8  THEN gli.Value08 ELSE 0 END AS ManagerAdjMonth08,
		CASE WHEN bc.MonthsLoaded < 9  THEN gli.Value09 ELSE 0 END AS ManagerAdjMonth09,
		CASE WHEN bc.MonthsLoaded < 10 THEN gli.Value10 ELSE 0 END AS ManagerAdjMonth10,
		CASE WHEN bc.MonthsLoaded < 11 THEN gli.Value11 ELSE 0 END AS ManagerAdjMonth11,
		CASE WHEN bc.MonthsLoaded < 12 THEN gli.Value12 ELSE 0 END AS ManagerAdjMonth12,
        phd.AdjustedValueTotal,
		glvd.DollarsValue as TotalValue
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
	INNER JOIN projectionGLFixedData phd on 
			gli.BudgetConfigID = phd.BudgetConfigID
			AND gli.DepartmentID = phd.DepartmentID
			AND gli.FinancialReportingID = phd.FinancialReportingID
			AND gli.AccountID = phd.AccountID
			AND gli.EntityID = phd.EntityID
			AND gli.FinancialReportingID = phd.FinancialReportingID
		JOIN distinctFixedDetails glvd	ON gli.AdjustmentID = glvd.AdjustmentID
			AND gli.BudgetConfigID = glvd.BudgetConfigID
			AND gli.DepartmentID = glvd.DepartmentID
			AND gli.FinancialReportingID = glvd.FinancialReportingID
			AND gli.AccountID = glvd.AccountID
			AND gli.TimeClassID = glvd.TimeClassID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
	WHERE 
		glvd.TimeClassID = 12 
		and gli.VariabilityID = 1
		AND glvd.row_number = 1 ) m
	where (
		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 )

		UNION ALL

		SELECT
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,	
		glid.DateCreated,
		glid.AuthorFullName,
		glid.Comment,
		0 as CategoryID,
		3 AS ItemizationDataTypeID,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value01
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage01 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage01 as decimal(19,8))
		END AS Month01,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value02
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage02 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage02 as decimal(19,8))
		END AS Month02,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value03
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage03 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage03 as decimal(19,8))
		END AS Month03,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value04
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage04 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage04 as decimal(19,8))
		END AS Month04,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value05
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage05 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage05 as decimal(19,8))
		END AS Month05,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value06
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage06 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage06 as decimal(19,8))
		END AS Month06,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value07
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage07 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage07 as decimal(19,8))
		END AS Month07,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value08
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage08 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage08 as decimal(19,8))
		END AS Month08,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value09
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage09 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage09 as decimal(19,8))
		END AS Month09,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value10
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage10 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage10 as decimal(19,8))
		END AS Month10,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value11
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage11 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage11 as decimal(19,8))
		END AS Month11,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage12 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage12 as decimal(19,8))
		END AS Month12,
		glid.DollarsValue as TotalValue
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
		JOIN distinctFixedDetails glid	ON gli.AdjustmentID = glid.AdjustmentID
			AND gli.BudgetConfigID = glid.BudgetConfigID
			AND gli.DepartmentID = glid.DepartmentID
			AND gli.FinancialReportingID = glid.FinancialReportingID
			AND gli.AccountID = glid.AccountID
			AND gli.TimeClassID = glid.TimeClassID
		JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
	WHERE 
		glid.TimeClassID = 2 
		AND gli.VariabilityID = 1
		AND glid.row_number = 1
	
	UNION ALL


	Select 
		m.BudgetConfigID,
		m.EntityID, 
		m.DepartmentID,
		m.AccountID, 
		m.TimeClassID,
		m.DateCreated,
		m.AuthorFullName,
		m.Comment,
		m.CategoryID,
		m.ItemizationDataTypeID,
		glMonth01 - ManagerAdjustmentMonth01 AS Month01,
		glMonth02 - ManagerAdjustmentMonth02 AS Month02,
		glMonth03 - ManagerAdjustmentMonth03 AS Month03,
		glMonth04 - ManagerAdjustmentMonth04 AS Month04,
		glMonth05 - ManagerAdjustmentMonth05 AS Month05,
		glMonth06 - ManagerAdjustmentMonth06 AS Month06,
		glMonth07 - ManagerAdjustmentMonth07 AS Month07,
		glMonth08 - ManagerAdjustmentMonth08 AS Month08,
		glMonth09 - ManagerAdjustmentMonth09 AS Month09,
		glMonth10 - ManagerAdjustmentMonth10 AS Month10,
		glMonth11 - ManagerAdjustmentMonth11 AS Month11,
		glMonth12 - ManagerAdjustmentMonth12 AS Month12,
		glTotal - m.TotalValue AS TotalValue
		from (
	SELECT 
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,	
		'' AS DateCreated,
		'' AS AuthorFullName,
		'' AS Comment,
		0 as CategoryID,
		2 AS ItemizationDataTypeID,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value01
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage01 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage01 as decimal(19,8))
		END AS ManagerAdjustmentMonth01,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value02
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage02 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage02 as decimal(19,8))
		END AS ManagerAdjustmentMonth02,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value03
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage03 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage03 as decimal(19,8))
		END AS ManagerAdjustmentMonth03,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value04
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage04 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage04 as decimal(19,8))
		END AS ManagerAdjustmentMonth04,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value05
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage05 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage05 as decimal(19,8))
		END AS ManagerAdjustmentMonth05,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value06
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage06 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage06 as decimal(19,8))
		END AS ManagerAdjustmentMonth06,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value07
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage07 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage07 as decimal(19,8))
		END AS ManagerAdjustmentMonth07,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value08
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage08 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage08 as decimal(19,8))
		END AS ManagerAdjustmentMonth08,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value09
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage09 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage09 as decimal(19,8))
		END AS ManagerAdjustmentMonth09,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value10
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage10 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage10 as decimal(19,8))
		END AS ManagerAdjustmentMonth10,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value11
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage11 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage11 as decimal(19,8))
		END AS ManagerAdjustmentMonth11,
		CASE WHEN glid.SpreadID = 0
			 THEN gli.Value12
			 WHEN glid.SpreadID = 1
			 THEN cast(glid.DollarsValue * glid.SpreadPercentage12 as decimal(19,8))
			 ELSE cast(glid.DollarsValue * gs.SpreadPercentage12 as decimal(19,8))
		END AS ManagerAdjustmentMonth12,
		gl.BudgetAdjusted01 as glMonth01,
		gl.BudgetAdjusted02 as glMonth02,
		gl.BudgetAdjusted03 as glMonth03,
		gl.BudgetAdjusted04 as glMonth04,
		gl.BudgetAdjusted05 as glMonth05,
		gl.BudgetAdjusted06 as glMonth06,
		gl.BudgetAdjusted07 as glMonth07,
		gl.BudgetAdjusted08 as glMonth08,
		gl.BudgetAdjusted09 as glMonth09,
		gl.BudgetAdjusted10 as glMonth10,
		gl.BudgetAdjusted11 as glMonth11,
		gl.BudgetAdjusted12 as glMonth12,
		gl.BudgetAdjustedTotal as glTotal,
		glid.DollarsValue as TotalValue
		FROM fp.GeneralLedger gl
		INNER JOIN fp.GeneralLedgerMyBudgetAdjustment gli ON 
					 gli.BudgetConfigID = gl.BudgetConfigID
					AND gli.DepartmentID = gl.DepartmentID
					AND gli.FinancialReportingID = gl.FinancialReportingID
					AND gli.AccountID = gl.AccountID
					AND gli.TimeClassID = 2
					AND gli.VariabilityID = gl.VariabilityID
		JOIN distinctFixedDetails glid	ON gli.AdjustmentID = glid.AdjustmentID
			AND gli.BudgetConfigID = glid.BudgetConfigID
			AND gli.DepartmentID = glid.DepartmentID
			AND gli.FinancialReportingID = glid.FinancialReportingID
			AND gli.AccountID = glid.AccountID
			AND gli.TimeClassID = glid.TimeClassID
		JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
	WHERE 
		glid.TimeClassID = 2 
		AND gli.VariabilityID = 1
		AND glid.row_number = 1 ) m
       where (
		ABS(glMonth01 - ManagerAdjustmentMonth01) > 0.001 OR
		ABS(glMonth02 - ManagerAdjustmentMonth02) > 0.001 OR
		ABS(glMonth03 - ManagerAdjustmentMonth03) > 0.001  OR
		ABS(glMonth04 - ManagerAdjustmentMonth04) > 0.001 OR
		ABS(glMonth05 - ManagerAdjustmentMonth05) > 0.001 OR
		ABS(glMonth06 - ManagerAdjustmentMonth06) > 0.001 OR
		ABS(glMonth07 - ManagerAdjustmentMonth07) > 0.001 OR
		ABS(glMonth08 - ManagerAdjustmentMonth08) > 0.001 OR
		ABS(glMonth09 - ManagerAdjustmentMonth09) > 0.001 OR
		ABS(glMonth10 - ManagerAdjustmentMonth10) > 0.001 OR
		ABS(glMonth11 - ManagerAdjustmentMonth11) > 0.001 OR
		ABS(glMonth12 - ManagerAdjustmentMonth12) > 0.001 )

		UNION ALL

		--  for manager variable projection
		Select *,
		m.Month01 + m.Month02 + m.Month03 + m.Month04 + m.Month05 + m.Month05 + m.Month07 + m.Month08 + m.Month09 + m.Month10 + m.Month11 + m.Month12 AS TotalValue
		from (
		   SELECT 
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,
		glvd.DateCreated,
		glvd.AuthorFullName,
		glvd.Comment,
		0 AS CategoryID,
		5 AS ItemizationDataTypeID,
		CASE WHEN bc.MonthsLoaded >= 1  THEN phd.AdjustedValue01 ELSE  gli.Value01 * sd.ManagerAdjustedProjectionValue01 END AS Month01,
		CASE WHEN bc.MonthsLoaded >= 2  THEN phd.AdjustedValue02 ELSE  gli.Value02 * sd.ManagerAdjustedProjectionValue02 END AS Month02,
		CASE WHEN bc.MonthsLoaded >= 3  THEN phd.AdjustedValue03 ELSE  gli.Value03 * sd.ManagerAdjustedProjectionValue03 END AS Month03,
		CASE WHEN bc.MonthsLoaded >= 4  THEN phd.AdjustedValue04 ELSE  gli.Value04 * sd.ManagerAdjustedProjectionValue04 END AS Month04,
		CASE WHEN bc.MonthsLoaded >= 5  THEN phd.AdjustedValue05 ELSE  gli.Value05 * sd.ManagerAdjustedProjectionValue05 END AS Month05,
		CASE WHEN bc.MonthsLoaded >= 6  THEN phd.AdjustedValue06 ELSE  gli.Value06 * sd.ManagerAdjustedProjectionValue06 END AS Month06,
		CASE WHEN bc.MonthsLoaded >= 7  THEN phd.AdjustedValue07 ELSE  gli.Value07 * sd.ManagerAdjustedProjectionValue07 END AS Month07,
		CASE WHEN bc.MonthsLoaded >= 8  THEN phd.AdjustedValue08 ELSE  gli.Value08 * sd.ManagerAdjustedProjectionValue08 END AS Month08,
		CASE WHEN bc.MonthsLoaded >= 9  THEN phd.AdjustedValue09 ELSE  gli.Value09 * sd.ManagerAdjustedProjectionValue09 END AS Month09,
		CASE WHEN bc.MonthsLoaded >= 10 THEN phd.AdjustedValue10 ELSE  gli.Value10 * sd.ManagerAdjustedProjectionValue10 END AS Month10,
		CASE WHEN bc.MonthsLoaded >= 11 THEN phd.AdjustedValue11 ELSE  gli.Value11 * sd.ManagerAdjustedProjectionValue11 END AS Month11,
		CASE WHEN bc.MonthsLoaded >= 12 THEN phd.AdjustedValue12 ELSE  gli.Value12 * sd.ManagerAdjustedProjectionValue12 END AS Month12
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
	INNER JOIN projectionGLData phd on 
			gli.BudgetConfigID = phd.BudgetConfigID
			AND gli.DepartmentID = phd.DepartmentID
			AND gli.FinancialReportingID = phd.FinancialReportingID
			AND gli.AccountID = phd.AccountID
			AND gli.EntityID = phd.EntityID
			AND gli.FinancialReportingID = phd.FinancialReportingID
	INNER JOIN distinctVariableDetails glvd on 
			gli.AdjustmentID = glvd.AdjustmentID
			AND gli.BudgetConfigID = glvd.BudgetConfigID
			AND gli.DepartmentID = glvd.DepartmentID
			AND gli.FinancialReportingID = glvd.FinancialReportingID
			AND gli.AccountID = glvd.AccountID
			AND gli.FinancialReportingID = glvd.FinancialReportingID
			AND gli.TimeClassID = glvd.TimeClassID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'		
		INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = gli.TimeClassID and gli.BudgetConfigID = sd.BudgetConfigID
		WHERE 
		gli.TimeClassID = 12 
		AND gli.VariabilityID = 2
		and glvd.row_number = 1 ) m

		UNION ALL

	
   SELECT 
		gli.BudgetConfigID,
		gli.EntityID, 
		gli.DepartmentID,
		gli.AccountID, 
		gli.TimeClassID,
		glvd.DateCreated,
		glvd.AuthorFullName,
		glvd.Comment,
		0 AS CategoryID,
		5 AS ItemizationDataTypeID,
		gli.Value01 * sd.ManagerAdjustedValue01 AS Month01,
		gli.Value02 * sd.ManagerAdjustedValue02 AS Month02,
		gli.Value03 * sd.ManagerAdjustedValue03 AS Month03,
		gli.Value04 * sd.ManagerAdjustedValue04 AS Month04,
		gli.Value05 * sd.ManagerAdjustedValue05 AS Month05,
		gli.Value06 * sd.ManagerAdjustedValue06 AS Month06,
		gli.Value07 * sd.ManagerAdjustedValue07 AS Month07,
		gli.Value08 * sd.ManagerAdjustedValue08 AS Month08,
		gli.Value09 * sd.ManagerAdjustedValue09 AS Month09,
		gli.Value10 * sd.ManagerAdjustedValue10 AS Month10,
		gli.Value11 * sd.ManagerAdjustedValue11 AS Month11,
		gli.Value12 * sd.ManagerAdjustedValue12 AS Month12,
		glvd.DollarsValue * sd.ManagerAdjustedValueTotal AS TotalValue
	FROM fp.GeneralLedgerMyBudgetAdjustment gli
	INNER JOIN distinctVariableDetails glvd on gli.AdjustmentID = glvd.AdjustmentID
			AND gli.BudgetConfigID = glvd.BudgetConfigID
			AND gli.DepartmentID = glvd.DepartmentID
			AND gli.FinancialReportingID = glvd.FinancialReportingID
			AND gli.AccountID = glvd.AccountID
			AND gli.TimeClassID = glvd.TimeClassID
		JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
		INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = gli.TimeClassID and gli.BudgetConfigID = sd.BudgetConfigID
		WHERE 
		gli.TimeClassID = 2 
		AND gli.VariabilityID = 2
		and glvd.row_number = 1

		UNION ALL

	SELECT 
	DISTINCT
		glsai.BudgetConfigID,
		dep.EntityID, 
		glsai.DepartmentID,
		glsai.AccountID, 
		CASE WHEN glsai.TimeClassID = 12 THEN glsai.TimeClassID ELSE CASE WHEN glsaid.BudgetPhaseID = 2 THEN 20 ELSE 2 END END AS TimeClassID ,
		CASE WHEN glsaid.LastModifiedAuthorFullName = '' THEN CONVERT(varchar, CAST(glsaid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime))
			ELSE CONCAT(CONVERT(varchar, CAST(glsaid.DateCreatedUtc  AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME), 121), ', ',
			CONVERT(varchar, CAST(glsaid.LastModifiedDateUtc  AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME), 121)) END AS DateCreated,
		CASE WHEN glsaid.LastModifiedAuthorFullName = '' THEN glsaid.CreatedAuthorFullName ELSE glsaid.CreatedAuthorFullName + ', ' + glsaid.LastModifiedAuthorFullName END AS AuthorFullName,
		glsaid.Description AS Comment,
		glsaid.CategoryID,
		4 AS ItemizationDataTypeID,	
		glsaid.Value01 AS Month01,
		glsaid.Value02 AS Month02,
		glsaid.Value03 AS Month03,
		glsaid.Value04 AS Month04,
		glsaid.Value05 AS Month05,
		glsaid.Value06 AS Month06,
		glsaid.Value07 AS Month07,
		glsaid.Value08 AS Month08,
		glsaid.Value09 AS Month09,
		glsaid.Value10 AS Month10,
		glsaid.Value11 AS Month11,
		glsaid.Value12 AS Month12,
		glsaid.Value01 + glsaid.Value02 + glsaid.Value03 + glsaid.Value04 + glsaid.Value05 + glsaid.Value06 + glsaid.Value07 + glsaid.Value08 + glsaid.Value09 + glsaid.Value10 + glsaid.Value11 + glsaid.Value12 as TotalValue
	FROM fp.GeneralLedgerSubAccountItemizedAdjustment glsai
		JOIN fp.GeneralLedgerSubAccountItemizedDetail glsaid ON glsai.BudgetConfigID = glsaid.BudgetConfigID
			AND glsai.DepartmentID = glsaid.DepartmentID
			AND glsai.AccountID = glsaid.AccountID
			AND glsai.TimeClassID = glsaid.TimeClassID
			AND glsai.BudgetPhaseID = glsaid.BudgetPhaseID
		JOIN fp.BudgetConfig bc ON glsai.BudgetConfigID = bc.BudgetConfigID
		JOIN fw.DimDepartment dep ON dep.DepartmentId = glsai.DepartmentId
		LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone'
	WHERE glsai.Itemized = 1
	) a;
GO


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

-- fp.viewGeneralLedgerSpreadUnlockData
CREATE VIEW fp.viewGeneralLedgerSpreadUnlockData
AS 

SELECT [RowID]
      ,[BudgetConfigID]
      ,[AdjustmentGUID]
      ,[EntityID]
      ,[DepartmentID]
      ,[AccountID]
      ,[FinancialReportingID]
      ,[Version]
      ,[Value01]
      ,[Value02]
      ,[Value03]
      ,[Value04]
      ,[Value05]
      ,[Value06]
      ,[Value07]
      ,[Value08]
      ,[Value09]
      ,[Value10]
      ,[Value11]
      ,[Value12]
      ,[IsRecordDeleted]
  FROM [fp].[GeneralLedgerSpreadUnlockData]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewGeneralLedgerSpreads
CREATE VIEW fp.viewGeneralLedgerSpreads
AS
	SELECT [BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID]
	FROM [fp].[GeneralLedgerSpreads] gls with (readuncommitted)
	WHERE GlobalSpreadID = 1

	UNION ALL

	SELECT gls.[BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, gls.[GlobalSpreadID]
	FROM [fp].[GeneralLedgerSpreads] gls with (readuncommitted)
		 INNER JOIN [fp].[GlobalSpread] gs
		 	ON gls.GlobalSpreadID = gs.GlobalSpreadID
	WHERE gls.GlobalSpreadID > 1
GO


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

-- fp.viewGeneralLedgerUOSData
CREATE   VIEW [fp].[viewGeneralLedgerUOSData]
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2023-03-06  NT      JAZZ-49040		Cross Department Flexing change
** 2	2024-02-05  MY      JAZZ-67147		Adjustments made to variable GL accounts for Depts using source depts as primary stats driver wipes out budgeted data
*************************************************************/
AS
SELECT 
	sb.BudgetConfigID, fcm.EntityGroupConfigID, dept.EntityID, fcm.DepartmentID, fcm.GLAccountID AS AccountID, acct.OBDollarsFinancialReportingID AS FinancialReportingID, sb.UnitTypeID, sb.BudgetPhaseID,
	SUM(AdjustedValue01) AS AdjustedValue01, SUM(AdjustedValue02) AS AdjustedValue02, SUM(AdjustedValue03) AS AdjustedValue03, SUM(AdjustedValue04) AS AdjustedValue04, SUM(AdjustedValue05) AS AdjustedValue05, SUM(AdjustedValue06) AS AdjustedValue06, SUM(AdjustedValue07) AS AdjustedValue07, SUM(AdjustedValue08) AS AdjustedValue08, SUM(AdjustedValue09) AS AdjustedValue09, SUM(AdjustedValue10) AS AdjustedValue10, SUM(AdjustedValue11) AS AdjustedValue11, SUM(AdjustedValue12) AS AdjustedValue12, SUM(AdjustedValueTotal) AS AdjustedValueTotal,
	SUM(AdjustedProjectionValue01) AS AdjustedProjectionValue01, SUM(AdjustedProjectionValue02) AS AdjustedProjectionValue02, SUM(AdjustedProjectionValue03) AS AdjustedProjectionValue03, SUM(AdjustedProjectionValue04) AS AdjustedProjectionValue04, SUM(AdjustedProjectionValue05) AS AdjustedProjectionValue05, SUM(AdjustedProjectionValue06) AS AdjustedProjectionValue06, SUM(AdjustedProjectionValue07) AS AdjustedProjectionValue07, SUM(AdjustedProjectionValue08) AS AdjustedProjectionValue08, SUM(AdjustedProjectionValue09) AS AdjustedProjectionValue09, SUM(AdjustedProjectionValue10) AS AdjustedProjectionValue10, SUM(AdjustedProjectionValue11) AS AdjustedProjectionValue11, SUM(AdjustedProjectionValue12) AS AdjustedProjectionValue12, SUM(AdjustedProjectionValueTotal) AS AdjustedProjectionValueTotal
FROM [fp].[viewFactStatistics] sb
	INNER JOIN (
		SELECT DISTINCT bc.BudgetConfigID, fcm.EntityGroupConfigID, DepartmentID, StatAccountID, GLAccountID, SourceDepartmentID
		FROM [fp].[FlexConfigMapping] fcm
			INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigID = fcm.EntityGroupConfigID
			INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE FlexingTypeID IN (1, 2)
	) fcm 
		ON sb.DepartmentID = fcm.SourceDepartmentID
		AND sb.AccountID = fcm.StatAccountID 
		AND sb.BudgetConfigID = fcm.BudgetConfigID
	INNER JOIN [fw].[DimAccount] acct ON fcm.GLAccountID = acct.AccountID
	INNER JOIN fw.DimDepartment dept ON fcm.DepartmentID = dept.DepartmentID
GROUP BY
	sb.BudgetConfigID, fcm.EntityGroupConfigID, dept.EntityID, fcm.DepartmentID, fcm.GLAccountID, acct.OBDollarsFinancialReportingID, sb.UnitTypeID, sb.BudgetPhaseID
GO


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

-- fp.viewGeneralLedgerUOSData_Unpivoted
CREATE VIEW fp.viewGeneralLedgerUOSData_Unpivoted
AS
SELECT 
	v.BudgetConfigID,
	v.EntityID,
	v.DepartmentID,
	v.AccountID,
	v.FinancialReportingID,
	2 as TimeClassID,
	v.FiscalMonthID,
	v.Value,
	mgrv.ManagerValue
FROM (
	-- Unpivot for value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12
		FROM [fp].[FactStatistics] fs
		INNER JOIN [fp].[FactStatisticsBudget] sb ON fs.StatisticsID = sb.StatisticsID
		WHERE sb.BudgetPhaseID = 2) sb
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	-- Unpivot for ManagerValue
INNER JOIN (
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.ManagerValue
	FROM (
		SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12
		FROM [fp].[FactStatistics] fs
		INNER JOIN [fp].[FactStatisticsBudget] sb ON fs.StatisticsID = sb.StatisticsID
		WHERE sb.BudgetPhaseID = 3) sb
		UNPIVOT ( ManagerValue FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON v.BudgetConfigID = mgrv.BudgetConfigID
	AND v.DepartmentID = mgrv.DepartmentID
	AND v.AccountID = mgrv.AccountID
	AND v.UnitTypeID = mgrv.UnitTypeID
	AND v.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN (
		SELECT DISTINCT EntityGroupConfigID, DepartmentID, StatAccountID, GLAccountID 
		FROM [fp].[FlexConfigMapping] 
		WHERE FlexingTypeID IN (1, 2)
	) fcm ON v.DepartmentID = fcm.DepartmentID AND v.AccountID = fcm.StatAccountID AND v.EntityGroupConfigID = fcm.EntityGroupConfigID

UNION ALL

SELECT 
	v.BudgetConfigID,
	v.EntityID,
	v.DepartmentID,
	v.AccountID,
	v.FinancialReportingID,
	12 as TimeClassID,
	v.FiscalMonthID,
	v.Value,
	mgrv.ManagerValue
FROM (
	-- Unpivot for value
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value
	FROM (
		SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12
		FROM [fp].[FactStatistics] fs
		INNER JOIN [fp].[FactStatisticsProjection] sb ON fs.StatisticsID = sb.StatisticsID
		WHERE sb.BudgetPhaseID = 2) sb
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	-- Unpivot for ManagerValue
INNER JOIN (
	SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.ManagerValue
	FROM (
		SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12
		FROM [fp].[FactStatistics] fs
		INNER JOIN [fp].[FactStatisticsProjection] sb ON fs.StatisticsID = sb.StatisticsID
		WHERE sb.BudgetPhaseID = 3) sb
		UNPIVOT ( ManagerValue FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON v.BudgetConfigID = mgrv.BudgetConfigID
	AND v.DepartmentID = mgrv.DepartmentID
	AND v.AccountID = mgrv.AccountID
	AND v.UnitTypeID = mgrv.UnitTypeID
	AND v.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN (
		SELECT DISTINCT EntityGroupConfigID, DepartmentID, StatAccountID, GLAccountID 
		FROM [fp].[FlexConfigMapping] 
		WHERE FlexingTypeID IN (1, 2)
	) fcm ON v.DepartmentID = fcm.DepartmentID AND v.AccountID = fcm.StatAccountID AND v.EntityGroupConfigID = fcm.EntityGroupConfigID
GO


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

-- fp.viewGeneralLedgerUOSHistoricalData
CREATE VIEW fp.viewGeneralLedgerUOSHistoricalData
 AS
SELECT   
    base.BudgetConfigID, base.EntityID, base.DepartmentID, fcm.GLAccountID As AccountID, acct.OBDollarsFinancialReportingID As FinancialReportingID, 1 As TimeClassID, bc.FiscalYearID - 2 As FiscalYearID,
    SUM(ISNULL(basis.PriorYearActualValueTotal, 0)) As Value
FROM [fp].[FactStatistics] As base 
	INNER JOIN [fp].[BudgetConfig] As bc ON base.BudgetConfigID = bc.BudgetConfigID 
	INNER JOIN [fp].[FactStatisticsHistory] As basis ON base.StatisticsID = basis.StatisticsID 
	INNER JOIN [fp].[FlexConfigMapping] As fcm ON base.DepartmentID = fcm.DepartmentID AND base.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = base.EntityGroupConfigID 
	INNER JOIN [fw].[DimAccount] As acct ON fcm.GLAccountID = acct.AccountID
WHERE FlexingTypeID In (1, 2)
GROUP BY FiscalYearID,base.BudgetConfigID,
         base.EntityID,
         base.DepartmentID,
         fcm.GLAccountID,
         acct.OBDollarsFinancialReportingID
UNION ALL
SELECT  
	base.BudgetConfigID, base.EntityID, base.DepartmentID, fcm.GLAccountID As AccountID, acct.OBDollarsFinancialReportingID As FinancialReportingID, 1 As TimeClassID, bc.FiscalYearID - 1 As FiscalYearID,
    SUM(ISNULL(basis.ActualYTDValueTotal, 0)) As Value
FROM [fp].[FactStatistics] As base 
	INNER JOIN [fp].[BudgetConfig] As bc ON base.BudgetConfigID = bc.BudgetConfigID 
	INNER JOIN [fp].[FactStatisticsHistory] As basis ON base.StatisticsID = basis.StatisticsID 
	INNER JOIN [fp].[FlexConfigMapping] As fcm ON base.DepartmentID = fcm.DepartmentID AND base.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = base.EntityGroupConfigID 
	INNER JOIN [fw].[DimAccount] As acct ON fcm.GLAccountID = acct.AccountID
WHERE FlexingTypeID In (1, 2)
GROUP BY FiscalYearID,base.BudgetConfigID,
         base.EntityID,
         base.DepartmentID,
         fcm.GLAccountID,
         acct.OBDollarsFinancialReportingID
UNION ALL
SELECT   
	base.BudgetConfigID, base.EntityID, base.DepartmentID, fcm.GLAccountID As AccountID, acct.OBDollarsFinancialReportingID As FinancialReportingID, 2 As TimeClassID, bc.FiscalYearID - 1 As FiscalYearID,
    SUM(ISNULL(basis.CurrentYearBudgetTotal, 0)) As Value
FROM [fp].[FactStatistics] As base 
	INNER JOIN [fp].[BudgetConfig] As bc ON base.BudgetConfigID = bc.BudgetConfigID 
	INNER JOIN [fp].[FactStatisticsHistory] As basis ON base.StatisticsID = basis.StatisticsID 
	INNER JOIN [fp].[FlexConfigMapping] As fcm ON base.DepartmentID = fcm.DepartmentID AND base.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = base.EntityGroupConfigID 
	INNER JOIN [fw].[DimAccount] As acct ON fcm.GLAccountID = acct.AccountID
WHERE FlexingTypeID In (1, 2)
GROUP BY FiscalYearID,base.BudgetConfigID,
         base.EntityID,
         base.DepartmentID,
         fcm.GLAccountID,
         acct.OBDollarsFinancialReportingID;
GO


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

-- fp.viewGeneralLedgerVariability
CREATE VIEW [fp].[viewGeneralLedgerVariability]
AS	
SELECT 
    bc.BudgetConfigID,
	av.EntityGroupConfigGUID,
	dd.EntityID,
	av.DepartmentID,
    av.AccountID,
    av.FixedPercentage
FROM [fp].[FactAccountVariability] av
INNER JOIN [fp].[EntityGroupConfig] egc
ON av.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
INNER JOIN [fp].[BudgetConfig] bc
ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
INNER JOIN [fw].[DimDepartment] dd
ON dd.DepartmentID = av.DepartmentID
GO


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

-- fp.viewGeneralLedger_DepartmentManager
CREATE VIEW  fp.viewGeneralLedger_DepartmentManager
 AS
WITH targetDollarsPerUOS AS (
SELECT 	
	GeneralLedgerID,
	BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	DepartmentID,
	AccountID,
	FinancialReportingID,
	APEModelSectionID,
	VariabilityID,
	TargetLockFlag,
	TargetLockType,
	m.FiscalMonthID,
	33 As UnitTypeID,
	f.Value As TargetValue
FROM
	fp.GeneralLedger gl
UNPIVOT (Value For FiscalMonth IN (TargetDollarsPerUOSAdjusted01, TargetDollarsPerUOSAdjusted02, TargetDollarsPerUOSAdjusted03, TargetDollarsPerUOSAdjusted04, TargetDollarsPerUOSAdjusted05, TargetDollarsPerUOSAdjusted06, TargetDollarsPerUOSAdjusted07, TargetDollarsPerUOSAdjusted08, TargetDollarsPerUOSAdjusted09, TargetDollarsPerUOSAdjusted10, TargetDollarsPerUOSAdjusted11, TargetDollarsPerUOSAdjusted12)) f
LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetDollarsPerUOSAdjusted', 'Month')
),
budgetDollarsPerUOS AS
(SELECT 
	GeneralLedgerID,
	BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	DepartmentID,
	AccountID,
	FinancialReportingID,
	APEModelSectionID,
	VariabilityID,
	BudgetLockFlag,
	BudgetLockType,
	m.FiscalMonthID,
	33 As UnitTypeID,
	f.Value As BudgetValue
FROM
	fp.GeneralLedger gl
UNPIVOT (Value For FiscalMonth IN (BudgetDollarsPerUOSAdjusted01, BudgetDollarsPerUOSAdjusted02, BudgetDollarsPerUOSAdjusted03, BudgetDollarsPerUOSAdjusted04, BudgetDollarsPerUOSAdjusted05, BudgetDollarsPerUOSAdjusted06, BudgetDollarsPerUOSAdjusted07, BudgetDollarsPerUOSAdjusted08, BudgetDollarsPerUOSAdjusted09, BudgetDollarsPerUOSAdjusted10, BudgetDollarsPerUOSAdjusted11, BudgetDollarsPerUOSAdjusted12)) f
LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetDollarsPerUOSAdjusted', 'Month')
)
SELECT b.GeneralLedgerID,
	 b.BudgetConfigID,
	 b.EntityGroupConfigID,
	 b.EntityID,
	 b.DepartmentID,
	 b.AccountID,
	 b.FinancialReportingID,
	 b.APEModelSectionID,
	 b.VariabilityID,
     CAST(33 AS TINYINT) AS UnitTypeID,
     2 AS TimeClassID,
	 bc.FiscalYearID,
	 t.FiscalMonthID,
	 CASE WHEN b.BudgetLockFlag = 1 AND b.BudgetLockType = 6 THEN 0 ELSE b.BudgetLockFlag END As HasFinalValueAdjustment,
	 TargetValue AS Value,
	 BudgetValue AS ManagerValue	
FROM targetDollarsPerUOS t INNER JOIN budgetDollarsPerUOS b ON t.GeneralLedgerID = b.GeneralLedgerID AND t.FiscalMonthID = b.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON t.BudgetConfigID = bc.BudgetConfigID
UNION 
SELECT b.GeneralLedgerID,
	 b.BudgetConfigID,
	 b.EntityGroupConfigID,
	 b.EntityID,
	 b.DepartmentID,
	 b.AccountID,
	 b.FinancialReportingID,
	 b.APEModelSectionID,
	 b.VariabilityID,
	 CAST(34 AS TINYINT) AS UnitTypeID,
	 2 AS TimeClassID,
	 bc.FiscalYearID,
	 t.FiscalMonthID,
	 CASE WHEN b.BudgetLockFlag = 1 AND b.BudgetLockType = 6 THEN 0 ELSE b.BudgetLockFlag END As HasFinalValueAdjustment,
	 TargetValue AS Value,
	 BudgetValue AS ManagerValue
FROM (SELECT  	
			GeneralLedgerID,
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID,
			DepartmentID,
			AccountID,
			FinancialReportingID,
			APEModelSectionID,
			VariabilityID,
			TargetLockFlag,
			TargetLockType,
			m.FiscalMonthID,
			f.Value As TargetValue
		FROM
			fp.GeneralLedger gl
		UNPIVOT (Value For FiscalMonth IN (TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06, TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12)) f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetAdjusted', 'Month')
		) t
INNER JOIN 
		(SELECT 
			GeneralLedgerID,
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID,
			DepartmentID,
			AccountID,
			FinancialReportingID,
			APEModelSectionID,
			VariabilityID,
			BudgetLockFlag,
			BudgetLockType,
			m.FiscalMonthID,
			f.Value As BudgetValue
		FROM
			fp.GeneralLedger gl
		UNPIVOT (Value For FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month')
		) b
	ON t.GeneralLedgerID = b.GeneralLedgerID
   AND t.FiscalMonthID = b.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON t.BudgetConfigID = bc.BudgetConfigID
UNION 
SELECT 
	GeneralLedgerID,
	bc.BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	DepartmentID,
	AccountID,
	FinancialReportingID,
	APEModelSectionID,
	VariabilityID,
	CAST(34 AS TINYINT) As UnitTypeID,
	12 as TimeClassID,
	bc.FiscalYearID - 1 as FiscalYearID,
	m.FiscalMonthID,
	CASE WHEN ProjectionLockFlag = 1 AND ProjectionLockType = 6 THEN 0 ELSE ProjectionLockFlag END As HasFinalValueAdjustment,
	0 as Value,
	f.Value As ManagerValue
FROM
	fp.GeneralLedger gl
UNPIVOT (Value For FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, 
								   ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) f
LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month')
INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = f.BudgetConfigID
UNION
SELECT 
	GeneralLedgerID,
	bc.BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	DepartmentID,
	AccountID,
	FinancialReportingID,
	APEModelSectionID,
	VariabilityID,
	12 as TimeClassID,
	bc.FiscalYearID - 1 as FiscalYearID,
	m.FiscalMonthID,
	CAST(33 AS TINYINT) As UnitTypeID,
	0 as Value,
	f.Value As ManagerValue,
	CASE WHEN ProjectionLockFlag = 1 AND ProjectionLockType = 6 THEN 0 ELSE ProjectionLockFlag END As HasFinalValueAdjustment
FROM
	fp.GeneralLedger gl
UNPIVOT (Value For FiscalMonth IN (ProjectionDollarsPerUOSAdjusted01, ProjectionDollarsPerUOSAdjusted02, ProjectionDollarsPerUOSAdjusted03, ProjectionDollarsPerUOSAdjusted04, ProjectionDollarsPerUOSAdjusted05, ProjectionDollarsPerUOSAdjusted06, ProjectionDollarsPerUOSAdjusted07, 
								   ProjectionDollarsPerUOSAdjusted08, ProjectionDollarsPerUOSAdjusted09, ProjectionDollarsPerUOSAdjusted10, ProjectionDollarsPerUOSAdjusted11, ProjectionDollarsPerUOSAdjusted12)) f
LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionDollarsPerUOSAdjusted', 'Month')
INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = f.BudgetConfigID
GO


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

-- fp.viewGeneralLedger_Pivoted
CREATE     VIEW [fp].[viewGeneralLedger_Pivoted]
  AS
    SELECT
           gl.GeneralLedgerID,
           gl.BudgetConfigID,
           gl.EntityGroupConfigID,
           gl.DepartmentID,
           gl.FinancialReportingID,
           gl.VariabilityID,
           gl.EntityID,
           gl.AccountID,
           bc.FiscalYearID,
           34 AS UnitTypeID,
           gl.APEModelSectionID,
		   
		   gl.TargetLockType,
		   gl.TargetLockFlag,
		   gl.BudgetLockType,
		   gl.BudgetLockFlag,
		   gl.ProjectionLockType,
		   gl.ProjectionLockFlag,
		   
		   CASE WHEN gl.BudgetLockType = 6 THEN 1 ELSE 0 END AS BudgetSpreadsLockFlag,		   
		   CASE WHEN gl.BudgetLockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag,
		   CASE WHEN gl.TargetLockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag,
		   CASE WHEN gl.ProjectionLockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag,

           gl.TargetAdjustedTotal,
           gl.BudgetAdjustedTotal,
		   gl.ProjectionAdjustedTotal,

           hist.PriorYearActualValueTotal as PriorYearActualValueTotal,
           hist.ActualYTDValueTotal as ActualYTDValueTotal,
           hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal,

           gl.InitialBudgetTotal,
           gl.InitialProjectionTotal,

           ISNULL(fgli.InitiativeForecastTotal, 0) as InitiativeForecastTotal,
           ISNULL(fgli.InitiativeForecastTotal + gl.BudgetAdjustedTotal, 0) as IntiativeBudgetTotal,

		   gl.TargetAdjusted01, gl.TargetAdjusted02, gl.TargetAdjusted03, gl.TargetAdjusted04, 
		   gl.TargetAdjusted05, gl.TargetAdjusted06, gl.TargetAdjusted07, gl.TargetAdjusted08, 
		   gl.TargetAdjusted09, gl.TargetAdjusted10, gl.TargetAdjusted11, gl.TargetAdjusted12,

		   gl.BudgetAdjusted01, gl.BudgetAdjusted02, gl.BudgetAdjusted03, gl.BudgetAdjusted04, 
		   gl.BudgetAdjusted05, gl.BudgetAdjusted06, gl.BudgetAdjusted07, gl.BudgetAdjusted08, 
		   gl.BudgetAdjusted09, gl.BudgetAdjusted10, gl.BudgetAdjusted11, gl.BudgetAdjusted12,

		   gl.ProjectionAdjusted01, gl.ProjectionAdjusted02, gl.ProjectionAdjusted03, gl.ProjectionAdjusted04, 
		   gl.ProjectionAdjusted05, gl.ProjectionAdjusted06, gl.ProjectionAdjusted07, gl.ProjectionAdjusted08, 
		   gl.ProjectionAdjusted09, gl.ProjectionAdjusted10, gl.ProjectionAdjusted11, gl.ProjectionAdjusted12,   


		   gl.TargetDollarsPerUOSAdjusted01, gl.TargetDollarsPerUOSAdjusted02, gl.TargetDollarsPerUOSAdjusted03, gl.TargetDollarsPerUOSAdjusted04, 
		   gl.TargetDollarsPerUOSAdjusted05, gl.TargetDollarsPerUOSAdjusted06, gl.TargetDollarsPerUOSAdjusted07, gl.TargetDollarsPerUOSAdjusted08, 
		   gl.TargetDollarsPerUOSAdjusted09, gl.TargetDollarsPerUOSAdjusted10, gl.TargetDollarsPerUOSAdjusted11, gl.TargetDollarsPerUOSAdjusted12,

		   gl.BudgetDollarsPerUOSAdjusted01, gl.BudgetDollarsPerUOSAdjusted02, gl.BudgetDollarsPerUOSAdjusted03, gl.BudgetDollarsPerUOSAdjusted04, 
		   gl.BudgetDollarsPerUOSAdjusted05, gl.BudgetDollarsPerUOSAdjusted06, gl.BudgetDollarsPerUOSAdjusted07, gl.BudgetDollarsPerUOSAdjusted08, 
		   gl.BudgetDollarsPerUOSAdjusted09, gl.BudgetDollarsPerUOSAdjusted10, gl.BudgetDollarsPerUOSAdjusted11, gl.BudgetDollarsPerUOSAdjusted12,

		   gl.ProjectionDollarsPerUOSAdjusted01, gl.ProjectionDollarsPerUOSAdjusted02, gl.ProjectionDollarsPerUOSAdjusted03, gl.ProjectionDollarsPerUOSAdjusted04, 
		   gl.ProjectionDollarsPerUOSAdjusted05, gl.ProjectionDollarsPerUOSAdjusted06, gl.ProjectionDollarsPerUOSAdjusted07, gl.ProjectionDollarsPerUOSAdjusted08, 
		   gl.ProjectionDollarsPerUOSAdjusted09, gl.ProjectionDollarsPerUOSAdjusted10, gl.ProjectionDollarsPerUOSAdjusted11, gl.ProjectionDollarsPerUOSAdjusted12,

		   ISNULL(fgli.InitiativeForecast01, 0) as InitiativeForecast01, ISNULL(fgli.InitiativeForecast02, 0) as InitiativeForecast02, 
		   ISNULL(fgli.InitiativeForecast03, 0) as InitiativeForecast03, ISNULL(fgli.InitiativeForecast04, 0) as InitiativeForecast04, 
		   ISNULL(fgli.InitiativeForecast05, 0) as InitiativeForecast05, ISNULL(fgli.InitiativeForecast06, 0) as InitiativeForecast06, 
		   ISNULL(fgli.InitiativeForecast07, 0) as InitiativeForecast07, ISNULL(fgli.InitiativeForecast08, 0) as InitiativeForecast08, 
		   ISNULL(fgli.InitiativeForecast09, 0) as InitiativeForecast09, ISNULL(fgli.InitiativeForecast10, 0) as InitiativeForecast10, 
		   ISNULL(fgli.InitiativeForecast11, 0) as InitiativeForecast11, ISNULL(fgli.InitiativeForecast12, 0) as InitiativeForecast12
    FROM
         fp.GeneralLedger gl with (readuncommitted)
           INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON gl.BudgetConfigID = bc.BudgetConfigID
           INNER JOIN fp.GeneralLedgerHistory hist with (readuncommitted) ON gl.GeneralLedgerID = hist.GeneralLedgerID
           LEFT JOIN fp.FactGeneralLedgerInitiative fgli with (readuncommitted) ON gl.GeneralLedgerID = fgli.GeneralLedgerID
GO


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

-- fp.viewGeneralLedger_Totals
CREATE VIEW  fp.viewGeneralLedger_Totals
AS
SELECT 
	gl.GeneralLedgerID,
	gl.BudgetConfigID,
	gl.EntityGroupConfigID,
	gl.DepartmentID,
	gl.FinancialReportingID,
	gl.VariabilityID,
	gl.EntityID,
	gl.AccountID,
	gl.APEModelSectionID,
	
	TargetLockType,
	TargetLockFlag,
	BudgetLockType,
	BudgetLockFlag,
	ProjectionLockType,
	ProjectionLockFlag,

	gl.InitialBudgetTotal,
	gl.InitialProjectionTotal,
	TargetAdjustedTotal,
	BudgetAdjustedTotal AS ManagerAdjustedTotal,
	ProjectionAdjustedTotal As ManagerAdjustedProjectionTotal,
	
	hist.PriorYearActualValueTotal,
	hist.ActualYTDValueTotal,
	hist.CurrentYearBudgetTotal
FROM fp.GeneralLedger gl
INNER JOIN fp.GeneralLedgerHistory hist ON gl.GeneralLedgerID = hist.GeneralLedgerID
GO


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

-- fp.viewHistoryViewerAccountFlexAssignments
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	2018-09-05	GF			B-20335		Created - this view needs refactoring, it hardcodes assumptions about default hierarchies
*************************************************************/
CREATE VIEW fp.viewHistoryViewerAccountFlexAssignments
AS
	with AccFlexConfigAssign as (
		SELECT distinct
			JobCodeGroupID = LTRIM(RTRIM(REPLACE(LEFT(JobCodes, LEN(JobCodes) - charindex('|', JobCodes)), '|', ''))),
			JobCodeID = CASE 
				WHEN charindex('|', JobCodes) > 0
					THEN RIGHT(JobCodes, LEN(JobCodes) - charindex('|', JobCodes))
				ELSE NULL
				END,
			PayCodeGroupID,
			ProductiveClassID,
			AccountID
			,EntityGroupConfigID
		FROM (
		SELECT EntityGroupConfigID,
			 REPLACE(REPLACE(JobCodeAssignment, 'JOBCODE|JC|', ''),'All','') AS JobCodes
			,CASE 
				WHEN CHARINDEX('PCG|OBPCG|',PayCodeGroupAssignment) >= 1
					THEN REPLACE(PayCodeGroupAssignment, 'PCG|OBPCG|', '')
				ELSE NULL
				END AS ProductiveClassID
			,CASE 
				WHEN CHARINDEX('PCG|OBPCG|',PayCodeGroupAssignment) = 0
					THEN REPLACE(PayCodeGroupAssignment,'All','')
				ELSE NULL
				END AS PayCodeGroupID
			,AccountID
			,PayCodeGroupAssignment
			,JobCodeAssignment
		FROM fp.AccountFlexConfigAssignment afca
		inner join fp.AccountFlexConfig afc on afc.FlexConfigGUID = afca.FlexConfigGUID
		INNER JOIN [fp].[EntityGroupConfig] EGC on EGC.EntityGroupConfigGUID = afc.EntityGroupConfigGUID
			) SEL1
	)
	SELECT jc.JobCodeID, pcg.PayCodeGroupID,AFCA.EntityGroupConfigID,AFCA.AccountID
	FROM AccFlexConfigAssign AFCA
		INNER JOIN [fw].[DimJobCode] jc 
				ON (
				(jc.JobCodeID = AFCA.JobCodeID or AFCA.JobCodeID is null) 
				and 
				(jc.JobCodeGroupID = AFCA.JobCodeGroupID or AFCA.JobCodeGroupID is null)
				)

		INNER JOIN fw.DimPayCodeGroup pcg on (
					(pcg.PayCodeGroupID = AFCA.PayCodeGroupID or AFCA.PayCodeGroupID is null) 
					and 
					(pcg.ProductiveClassID = AFCA.ProductiveClassID or AFCA.ProductiveClassID is null)
				)
GO


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

-- fp.viewInitialPlanRuleLogs
CREATE VIEW fp.viewInitialPlanRuleLogs AS

SELECT RowID,
      BudgetConfigGUID,
      BudgetConfigID,
      PlanSectionID,
      TimeClassID,
      SubSectionID,
      DimensionalityJSON,
      ProjectionMethodID,
      TrailingMonths,
      RulePriority,
	  VersionID
	FROM [fp].[InitialPlanRuleHistory]
	UNION
	SELECT RowID,
      BudgetConfigGUID,
      BudgetConfigID,
      PlanSectionID,
      TimeClassID,
      SubSectionID,
      DimensionalityJSON,
      ProjectionMethodID,
      TrailingMonths,
      RulePriority,
	  VersionID
	FROM [fp].[InitialPlanRule]
GO


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

-- fp.viewNonStaffingExpenseAccounts
CREATE VIEW [fp].[viewNonStaffingExpenseAccounts]
AS
	SELECT acc.*
	FROM [fw].[DimAccount] acc
	INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID
	WHERE aph.Name = 'Expenses - Non-Staffing'
GO


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

-- fp.viewNonStaffingExpenseFlexingConfig
CREATE VIEW [fp].[viewNonStaffingExpenseFlexingConfig]
AS

SELECT 
	b.EntityGroupConfigGUID,
	b.DepartmentID,
	b.AccountID,
	CASE WHEN b.FlexMethodID = 6 THEN 6
		ELSE COALESCE(ovr.FlexMethodID, b.FlexMethodID) END AS FlexMethodID
FROM (
	SELECT 
		fc.EntityGroupConfigGUID,
		fc.DepartmentID,
		acct.AccountID,
		fc.FlexMethodID
	FROM [fp].[NonStaffingExpenseFlexingConfig] fc
	CROSS APPLY (SELECT AccountID FROM [fp].[viewNonStaffingExpenseAccounts]) acct
) b
LEFT JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] ovr
		ON b.DepartmentID = ovr.DepartmentID
		AND b.AccountID = ovr.AccountID
		AND b.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
GO


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

-- fp.viewPayrollUOSData
CREATE VIEW fp.viewPayrollUOSData
 AS
 SELECT 
 	sb.BudgetConfigID, 
 	sb.EntityID, sb.DepartmentID, 
 	fcm.PRJobCodeID AS JobCodeID, 
 	ISNULL(CAST(TimeClassID AS TINYINT), 0) AS TimeClassID, 
 	ISNULL(FiscalMonthID, 0) AS FiscalMonthID, 
 	ISNULL(SUM(Value), 0) AS Value, 
 	ISNULL(SUM(ManagerValue), 0) AS ManagerValue
FROM [fp].[viewFactStatistics_Unpivoted] sb WITH(NOLOCK)
	INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
	INNER JOIN (
			SELECT DISTINCT EntityGroupConfigID, DepartmentID, StatAccountID, PRJobCodeID 
			FROM [fp].[FlexConfigMapping] WITH(NOLOCK)
			WHERE FlexingTypeID IN (3)
		) fcm ON sb.DepartmentID = fcm.DepartmentID AND sb.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
    	AND sb.EntityID = egcm.EntityID
GROUP BY sb.BudgetConfigID, sb.EntityID, sb.DepartmentID, fcm.PRJobCodeID, TimeClassID, FiscalMonthID
GO


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

-- fp.viewPayrollUOSDataForAdjustments
CREATE   VIEW fp.viewPayrollUOSDataForAdjustments AS
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI                Description
** 1    3-06-2023  NT      JAZZ-49040        Cross Department Flexing change
** 2    1-18-2024  YR      JAZZ-64847        Variable FTE import to Projection wipes out Projected Months
** 3    2-18-2024  NH      JAZZ-58389        Provider Compensation: support new contextual adjustment window 
*************************************************************/
SELECT sb.BudgetConfigID, fcm.EntityID, fcm.DepartmentID, fcm.PRJobCodeID AS JobCodeID, fcm.ProviderLineItemID, sb.ProviderID, fcm.FlexingTypeID, sb.BudgetPhaseID, ISNULL(SUM(sb.AdjustedValue01), 0) AS AdjustedValue01, ISNULL(SUM(sb.AdjustedValue02), 0) 
                  AS AdjustedValue02, ISNULL(SUM(sb.AdjustedValue03), 0) AS AdjustedValue03, ISNULL(SUM(sb.AdjustedValue04), 0) AS AdjustedValue04, ISNULL(SUM(sb.AdjustedValue05), 0) AS AdjustedValue05, ISNULL(SUM(sb.AdjustedValue06), 0) 
                  AS AdjustedValue06, ISNULL(SUM(sb.AdjustedValue07), 0) AS AdjustedValue07, ISNULL(SUM(sb.AdjustedValue08), 0) AS AdjustedValue08, ISNULL(SUM(sb.AdjustedValue09), 0) AS AdjustedValue09, ISNULL(SUM(sb.AdjustedValue10), 0) 
                  AS AdjustedValue10, ISNULL(SUM(sb.AdjustedValue11), 0) AS AdjustedValue11, ISNULL(SUM(sb.AdjustedValue12), 0) AS AdjustedValue12, ISNULL(SUM(sb.AdjustedValueTotal), 0) AS AdjustedValueTotal, 
                  ISNULL(SUM(sb.AdjustedProjectionValue01), 0) AS AdjustedProjectionValue01, ISNULL(SUM(sb.AdjustedProjectionValue02), 0) AS AdjustedProjectionValue02, ISNULL(SUM(sb.AdjustedProjectionValue03), 0) AS AdjustedProjectionValue03, 
                  ISNULL(SUM(sb.AdjustedProjectionValue04), 0) AS AdjustedProjectionValue04, ISNULL(SUM(sb.AdjustedProjectionValue05), 0) AS AdjustedProjectionValue05, ISNULL(SUM(sb.AdjustedProjectionValue06), 0) AS AdjustedProjectionValue06, 
                  ISNULL(SUM(sb.AdjustedProjectionValue07), 0) AS AdjustedProjectionValue07, ISNULL(SUM(sb.AdjustedProjectionValue08), 0) AS AdjustedProjectionValue08, ISNULL(SUM(sb.AdjustedProjectionValue09), 0) AS AdjustedProjectionValue09, 
                  ISNULL(SUM(sb.AdjustedProjectionValue10), 0) AS AdjustedProjectionValue10, ISNULL(SUM(sb.AdjustedProjectionValue11), 0) AS AdjustedProjectionValue11, ISNULL(SUM(sb.AdjustedProjectionValue12), 0) AS AdjustedProjectionValue12, 
                  ISNULL(SUM(sb.AdjustedProjectionValueTotal), 0) AS AdjustedProjectionValueTotal
FROM     fp.viewFactStatistics AS sb WITH (NOLOCK) INNER JOIN
                  fp.BudgetConfig AS bc ON sb.BudgetConfigID = bc.BudgetConfigID INNER JOIN
                  fp.EntityGroupConfig AS egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID INNER JOIN
                      (SELECT DISTINCT fcm.EntityGroupConfigID, d.EntityID, fcm.DepartmentID, fcm.StatAccountID, fcm.PRJobCodeID, ProviderLineItemID, fcm.FlexingTypeID, fcm.SourceDepartmentID
                       FROM      fp.FlexConfigMapping AS fcm WITH (NOLOCK) INNER JOIN fw.DimDepartment d ON d.DepartmentID = fcm.DepartmentID
                       WHERE   (FlexingTypeID IN (3, 9))) AS fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID AND sb.AccountID = fcm.StatAccountID AND sb.DepartmentID = fcm.SourceDepartmentID INNER JOIN
                  fp.EntityGroupConfigMapping AS egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID AND sb.EntityID = egcm.EntityID
GROUP BY sb.BudgetConfigID, fcm.EntityID, fcm.DepartmentID, fcm.PRJobCodeID, sb.ProviderID, fcm.ProviderLineItemID, fcm.FlexingTypeID, sb.BudgetPhaseID
GO


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

-- fp.viewPayrollVariabilityConfig
CREATE VIEW [fp].[viewPayrollVariabilityConfig]
AS
SELECT 
                    OBJ.*, jg.Name as JCGName, jc.Name as JCName 
                FROM
                    
      [fp].[PayrollVariabilityConfig] OBJ
      LEFT JOIN [fw].[DimJobCodeGroup] jg ON OBJ.JobCodeGroupID = jg.JobCodeGroupID
      LEFT JOIN [fw].[DimJobCode] jc ON OBJ.JobCodeID = jc.JobCodeID
GO


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

-- fp.viewPlanSection
CREATE VIEW [fp].[viewPlanSection]
AS

	SELECT
		PlanSectionID,
		PlanSectionGUID as MemberGUID,
		Description,
		SortOrder,
		0 AS TransactionID,				
		'00000000-0000-0000-0000-000000000000' AS HistoryItemGUID
	FROM [fp].[PlanSection]
GO


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

-- fp.viewPlanSection_auto
--Last Modified 11/16/2020 3:28 PM
CREATE VIEW [fp].[viewPlanSection_auto]
AS
SELECT
   grpA26FDA3A669C47BCA67539B1DA857199.[PlanSectionID]
   ,grpA26FDA3A669C47BCA67539B1DA857199.[Description]
   ,grpA26FDA3A669C47BCA67539B1DA857199.[TransactionID]
   ,grpA26FDA3A669C47BCA67539B1DA857199.[SortOrder]
   ,grpA26FDA3A669C47BCA67539B1DA857199.[MemberGUID]
   ,grpA26FDA3A669C47BCA67539B1DA857199.[HistoryItemGUID]
FROM [fp].[viewPlanSection] grpA26FDA3A669C47BCA67539B1DA857199
GO


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

-- fp.viewProviderCompensationSpreads
CREATE     VIEW [fp].[viewProviderCompensationSpreads]
AS
	SELECT [BudgetConfigID], [ProviderID], [ProviderLineItemID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID], [UnitTypeID]
	FROM [fp].[ProviderCompensationSpreads] gls with (readuncommitted)
	WHERE GlobalSpreadID = 1

	UNION ALL

	SELECT gls.[BudgetConfigID], [ProviderID], [ProviderLineItemID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, gls.[GlobalSpreadID], [UnitTypeID]
	FROM [fp].[ProviderCompensationSpreads] gls with (readuncommitted)
		 INNER JOIN [fp].[GlobalSpread] gs
		 	ON gls.GlobalSpreadID = gs.GlobalSpreadID
	WHERE gls.GlobalSpreadID > 1
GO


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

-- fp.viewProviderCompensationVariability
CREATE   VIEW [fp].[viewProviderCompensationVariability] AS
/**************************************************************
** Change History
**************************************************************
** CID  Date	       Author	    WI	          Description
** 1    2024-02-18   NH	       JAZZ-65991 	Provider Compensation: support new contextual adjustment window
*************************************************************/
SELECT DISTINCT
	bc.BudgetConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.DepartmentID, 
	pv.ProviderLineItemID,
	ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage
FROM [fp].[Staffing] pv
	INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
	INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID
		WHERE  SubsectionID = 4
       AND pv.VariabilityID = 2
   GROUP BY bc.BudgetConfigID, 
	pv.EntityGroupConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.DepartmentID, 
	pv.ProviderLineItemID
GO


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

-- fp.viewProviderLineItem
CREATE VIEW [fp].[viewProviderLineItem]
AS

	SELECT
		pli.ProviderLineItemID,
		pli.ProviderLineItemGUID as MemberGUID,
		pli.Description,
		pli.PlanSectionID,
		pli.SortOrder,
		pli.HistoryItemGUID,
		pli.TransactionID
	FROM [fp].[ProviderLineItem] pli
GO


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

-- fp.viewProviderLineItem_auto
--Last Modified 11/15/2023 3:56 PM
CREATE VIEW [fp].[viewProviderLineItem_auto]
AS
SELECT
   grpC441C263E43548A5AE8DFE1AC0E8958C.[ProviderLineItemID]
   ,grpC441C263E43548A5AE8DFE1AC0E8958C.[Description]
   ,grpC441C263E43548A5AE8DFE1AC0E8958C.[PlanSectionID]
   ,grpC441C263E43548A5AE8DFE1AC0E8958C.[PayCodeGroupID]
   ,grpC441C263E43548A5AE8DFE1AC0E8958C.[SortOrder]
   ,grpC441C263E43548A5AE8DFE1AC0E8958C.[TransactionID]
   ,grpC441C263E43548A5AE8DFE1AC0E8958C.[MemberGUID]
   ,grpC441C263E43548A5AE8DFE1AC0E8958C.[HistoryItemGUID]
   ,ISNULL([PLANSECTION].[Description], 'Not Specified') as [PlanSectionName]
   ,ISNULL([PCG].[Name], 'Not Specified') as [PayCodeGroupName]
FROM [fp].[ProviderLineItem] grpC441C263E43548A5AE8DFE1AC0E8958C (readuncommitted)
   LEFT JOIN [fp].[viewPlanSection_auto] [PLANSECTION]  on [PLANSECTION].[PlanSectionID] = [grpC441C263E43548A5AE8DFE1AC0E8958C].[PlanSectionID]
   LEFT JOIN [fw].[viewDimPayCodeGroup] [PCG]  on [PCG].[PayCodeGroupID] = [grpC441C263E43548A5AE8DFE1AC0E8958C].[PayCodeGroupID]
GO


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

-- fp.viewReimbursementAdjustment
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-16-50  MY      JAZZ-32944		Initial
** 1	2023-09-04  MD      JAZZ-59398		Add BudgetPhaseID
*************************************************************/
CREATE   VIEW [fp].[viewReimbursementAdjustment]
AS
	SELECT [AdjustmentGUID]
		  ,[BudgetConfigGUID]
		  ,[AdjustmentType]
		  ,[Value]
		  ,[AdjustmentFilterJSON]
		  ,[GroupingHierarchyJSON]
		  ,[AdjustedProperty]
		  ,[Comment]
		  ,[AuthorGUID]
		  ,[AuthorFullName]
		  ,[GroupingGUID]
		  ,[TimeClassID]
		  ,[ClassificationGroupID]
		  ,[ClassificationCategoryID]
		  ,[IsRecordDeleted]
		  ,[DateCreatedUtc]
		  ,[LastModifiedDateUtc]
		  ,[DimensionMemberJson]
		  ,[AffectedDataCount]
		  ,[UnitTypeID]
		  ,[IsCarryForward]
		  ,[AdjustmentID]
		  ,[BudgetPhaseID]
	  FROM [fp].[ReimbursementAdjustment]
	WHERE IsRecordDeleted = 0
GO


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

-- fp.viewReimbursementAdjustmentImport
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1    2023-09-13  MD      JAZZ-59398		Add BudgetPhaseID column
*******************************************************/

CREATE   VIEW [fp].[viewReimbursementAdjustmentImport]
AS
SELECT 
	 [AdjustmentID]
	,[EntityID]
	,[PatientClassID]
	,[PayorID]
	,[PayorGroupID]
	,[ServiceLineID]
	,[ServiceLineRollupID]
	,[MedicalSurgicalID]
	,[MSDRGID]
	,[PrimaryCPTID] AS CPTID
	,[UBRevCodeID]
	,[UnitTypeID]
	,[TimeClassID]
	,[BudgetPhaseID]
	,[Value01]
	,[Value02]
	,[Value03]
	,[Value04]
	,[Value05]
	,[Value06]
	,[Value07]
	,[Value08]
	,[Value09]
	,[Value10]
	,[Value11]
	,[Value12]
	,6 AS SubsectionID -- Charges
FROM fp.ReimbursementAdjustmentChargeImport
UNION ALL
SELECT 
	 [AdjustmentID]
	,[EntityID]
	,[PatientClassID]
	,[PayorID]
	,[PayorGroupID]
	,[ServiceLineID]
	,[ServiceLineRollupID]
	,[MedicalSurgicalID]
	,[MSDRGID]
	,[CPTID]
	,0 AS [UBRevCodeID]
	,[UnitTypeID]
	,[TimeClassID]
	,[BudgetPhaseID]
	,[Value01]
	,[Value02]
	,[Value03]
	,[Value04]
	,[Value05]
	,[Value06]
	,[Value07]
	,[Value08]
	,[Value09]
	,[Value10]
	,[Value11]
	,[Value12]
	,5 AS SubsectionID -- Encounters
FROM fp.ReimbursementAdjustmentEncounterImport
GO


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

-- fp.viewReimbursementDeductionsAccounts
CREATE VIEW [fp].[viewReimbursementDeductionsAccounts]
AS
	SELECT acc.*
	FROM [fw].[DimAccount] acc
	INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID
	WHERE aph.Name = 'Deductions - Reimbursement'
GO


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

-- fp.viewReimbursementGeneralLedgerAdjustment
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	06-19-2023  MZ      JAZZ-56218		Initial
** 2	10-05-2023  NH      JAZZ-61719		Added UnitTypeID
*************************************************************/
CREATE   VIEW fp.viewReimbursementGeneralLedgerAdjustment
AS
	SELECT [AdjustmentGUID]
		  ,[BudgetConfigGUID]
		  ,[AdjustmentType]
		  ,[Value]
		  ,[AdjustmentFilterJSON]
		  ,[GroupingHierarchyJSON]
		  ,[AdjustedProperty]
		  ,[Comment]
		  ,[AuthorGUID]
		  ,[AuthorFullName]
		  ,[GroupingGUID]
		  ,[TimeClassID]
		  ,[BudgetPhaseID]
		  ,[UnitTypeID]
		  ,[ClassificationGroupID]
		  ,[ClassificationCategoryID]
		  ,[IsRecordDeleted]
		  ,[DateCreatedUtc]
		  ,[LastModifiedDateUtc]
		  ,[DimensionMemberJson]
		  ,[AffectedDataCount]
		  ,[IsCarryForward]
		  ,[AdjustmentID]
		  ,[IsErrored]
	  FROM [fp].[ReimbursementGeneralLedgerAdjustment]
	WHERE IsRecordDeleted = 0
GO


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

-- fp.viewReimbursementGeneralLedgerBudget_HistoryViewer
CREATE VIEW [fp].[viewReimbursementGeneralLedgerBudget_HistoryViewer]
AS
SELECT
	ov.ReimbursementGeneralLedgerID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.PayorGroupID,
	ov.PatientClassID,
	34 AS UnitTypeID, 
	2 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	v.Value, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12
		FROM fp.ReimbursementGeneralLedger gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudgetNetReimbursement', 'Month')) ov
INNER JOIN (
	-- Unpivot for Value
	SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.Value, LockType
	FROM (
		SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID,  PayorGroupID, PatientClassID,
		TargetLockType AS LockType, 
		TargetAdjustedNetReimbursement01 AS AdjustedValue01, 
		TargetAdjustedNetReimbursement02 AS AdjustedValue02, 
		TargetAdjustedNetReimbursement03 AS AdjustedValue03, 
		TargetAdjustedNetReimbursement04 AS AdjustedValue04, 
		TargetAdjustedNetReimbursement05 AS AdjustedValue05, 
		TargetAdjustedNetReimbursement06 AS AdjustedValue06, 
		TargetAdjustedNetReimbursement07 AS AdjustedValue07, 
		TargetAdjustedNetReimbursement08 AS AdjustedValue08, 
		TargetAdjustedNetReimbursement09 AS AdjustedValue09, 
		TargetAdjustedNetReimbursement10 AS AdjustedValue10, 
		TargetAdjustedNetReimbursement11 AS AdjustedValue11, 
		TargetAdjustedNetReimbursement12 AS AdjustedValue12
		FROM fp.ReimbursementGeneralLedger gl) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v
	ON 
	 ov.BudgetConfigID = v.BudgetConfigID
	 AND ov.EntityID = v.EntityID
	AND ov.PayorGroupID = v.PayorGroupID
	AND ov.PatientClassID = v.PatientClassID
	AND ov.FiscalMonthID = v.FiscalMonthID
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.Value AS ManagerValue
	FROM (
		SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		BudgetLockType AS LockType, 
		BudgetAdjustedNetReimbursement01 AS AdjustedValue01, 
		BudgetAdjustedNetReimbursement02 AS AdjustedValue02, 
		BudgetAdjustedNetReimbursement03 AS AdjustedValue03, 
		BudgetAdjustedNetReimbursement04 AS AdjustedValue04, 
		BudgetAdjustedNetReimbursement05 AS AdjustedValue05, 
		BudgetAdjustedNetReimbursement06 AS AdjustedValue06, 
		BudgetAdjustedNetReimbursement07 AS AdjustedValue07, 
		BudgetAdjustedNetReimbursement08 AS AdjustedValue08, 
		BudgetAdjustedNetReimbursement09 AS AdjustedValue09, 
		BudgetAdjustedNetReimbursement10 AS AdjustedValue10, 
		BudgetAdjustedNetReimbursement11 AS AdjustedValue11, 
		BudgetAdjustedNetReimbursement12 AS AdjustedValue12
		FROM fp.ReimbursementGeneralLedger gl) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON
	 v.BudgetConfigID = mgrv.BudgetConfigID
	  AND v.EntityID = mgrv.EntityID
	AND v.PayorGroupID = mgrv.PayorGroupID
	AND v.PatientClassID = mgrv.PatientClassID
	AND v.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewReimbursementGeneralLedgerProjection_HistoryViewer
CREATE VIEW [fp].[viewReimbursementGeneralLedgerProjection_HistoryViewer]
AS
SELECT
	ov.ReimbursementGeneralLedgerID, 
	ov.BudgetConfigID, 
	ov.EntityGroupConfigID, 
	ov.EntityID, 
	ov.PayorGroupID,
	ov.PatientClassID,
	34 AS UnitTypeID, 
	12 as TimeClassID,
	bc.FiscalYearID, 
	ov.FiscalMonthID,
	LockType,
	ov.InitialValue AS OriginalValue, 
	mgrv.ManagerValue
FROM (
	-- Unpivot for OriginalValue
	SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.InitialValue
	FROM (
		SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		InitialProjectionNetReimbursement01, InitialProjectionNetReimbursement02, InitialProjectionNetReimbursement03, InitialProjectionNetReimbursement04, InitialProjectionNetReimbursement05, InitialProjectionNetReimbursement06, InitialProjectionNetReimbursement07, InitialProjectionNetReimbursement08, InitialProjectionNetReimbursement09, InitialProjectionNetReimbursement10, InitialProjectionNetReimbursement11, InitialProjectionNetReimbursement12
		FROM fp.ReimbursementGeneralLedger gl ) gl
		UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjectionNetReimbursement01, InitialProjectionNetReimbursement02, InitialProjectionNetReimbursement03, InitialProjectionNetReimbursement04, InitialProjectionNetReimbursement05, InitialProjectionNetReimbursement06, InitialProjectionNetReimbursement07, InitialProjectionNetReimbursement08, InitialProjectionNetReimbursement09, InitialProjectionNetReimbursement10, InitialProjectionNetReimbursement11, InitialProjectionNetReimbursement12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjectionNetReimbursement', 'Month')) ov
INNER JOIN (
	-- Unpivot for ManagerValue
	SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.Value AS ManagerValue, LockType
	FROM (
		SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		ProjectionLockType AS LockType, 
		ProjectionAdjustedNetReimbursement01 AS AdjustedValue01, 
		ProjectionAdjustedNetReimbursement02 AS AdjustedValue02, 
		ProjectionAdjustedNetReimbursement03 AS AdjustedValue03, 
		ProjectionAdjustedNetReimbursement04 AS AdjustedValue04, 
		ProjectionAdjustedNetReimbursement05 AS AdjustedValue05, 
		ProjectionAdjustedNetReimbursement06 AS AdjustedValue06, 
		ProjectionAdjustedNetReimbursement07 AS AdjustedValue07, 
		ProjectionAdjustedNetReimbursement08 AS AdjustedValue08, 
		ProjectionAdjustedNetReimbursement09 AS AdjustedValue09, 
		ProjectionAdjustedNetReimbursement10 AS AdjustedValue10, 
		ProjectionAdjustedNetReimbursement11 AS AdjustedValue11, 
		ProjectionAdjustedNetReimbursement12 AS AdjustedValue12
		FROM fp.ReimbursementGeneralLedger gl) gl
		UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv
	ON
	 ov.BudgetConfigID = mgrv.BudgetConfigID
	AND ov.EntityID = mgrv.EntityID
	AND ov.PayorGroupID = mgrv.PayorGroupID
	AND ov.PatientClassID = mgrv.PatientClassID
	AND ov.FiscalMonthID = mgrv.FiscalMonthID
INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewReimbursementGeneralLedger_Pivoted
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			  Description
 ** 1 	 2023-06-22  AO  	 JAZZ-56124	  Inital
*************************************************************/	 


CREATE VIEW [fp].[viewReimbursementGeneralLedger_Pivoted]
AS
	SELECT
		rgl.ReimbursementGeneralLedgerID,
		rgl.BudgetConfigID,
		rgl.EntityGroupConfigID,
		rgl.EntityID,
		rgl.PatientClassID,
		rgl.PayorGroupID,

		rgl.TargetLockType,
		rgl.BudgetLockType,
		rgl.ProjectionLockType,

		rgl.TargetLockFlag,
		rgl.BudgetLockFlag,
		rgl.ProjectionLockFlag,
		
		CASE WHEN rgl.TargetLockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag,
		CASE WHEN rgl.BudgetLockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag,
		CASE WHEN rgl.ProjectionLockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag,
		
		rgl.TargetAdjustedTotal,
		rgl.BudgetAdjustedTotal,
		rgl.ProjectionAdjustedTotal,

		hist.PriorYearActualValueTotal,

		rgl.InitialBudgetTotal,
		rgl.InitialProjectionTotal,

		rgl.TargetAdjusted01,
		rgl.TargetAdjusted02,
		rgl.TargetAdjusted03,
		rgl.TargetAdjusted04,
		rgl.TargetAdjusted05,
		rgl.TargetAdjusted06,
		rgl.TargetAdjusted07,
		rgl.TargetAdjusted08,
		rgl.TargetAdjusted09,
		rgl.TargetAdjusted10,
		rgl.TargetAdjusted11,
		rgl.TargetAdjusted12,

		rgl.BudgetAdjusted01,
		rgl.BudgetAdjusted02,
		rgl.BudgetAdjusted03,
		rgl.BudgetAdjusted04,
		rgl.BudgetAdjusted05,
		rgl.BudgetAdjusted06,
		rgl.BudgetAdjusted07,
		rgl.BudgetAdjusted08,
		rgl.BudgetAdjusted09,
		rgl.BudgetAdjusted10,
		rgl.BudgetAdjusted11,
		rgl.BudgetAdjusted12,

		rgl.ProjectionAdjusted01,
		rgl.ProjectionAdjusted02,
		rgl.ProjectionAdjusted03,
		rgl.ProjectionAdjusted04,
		rgl.ProjectionAdjusted05,
		rgl.ProjectionAdjusted06,
		rgl.ProjectionAdjusted07,
		rgl.ProjectionAdjusted08,
		rgl.ProjectionAdjusted09,
		rgl.ProjectionAdjusted10,
		rgl.ProjectionAdjusted11,
		rgl.ProjectionAdjusted12,

		hist.PriorYearActualValue01,
		hist.PriorYearActualValue02,
		hist.PriorYearActualValue03,
		hist.PriorYearActualValue04,
		hist.PriorYearActualValue05,
		hist.PriorYearActualValue06,
		hist.PriorYearActualValue07,
		hist.PriorYearActualValue08,
		hist.PriorYearActualValue09,
		hist.PriorYearActualValue10,
		hist.PriorYearActualValue11,
		hist.PriorYearActualValue12,

		rgl.TargetAdjustedNetReimbursement01,
		rgl.TargetAdjustedNetReimbursement02,
		rgl.TargetAdjustedNetReimbursement03,
		rgl.TargetAdjustedNetReimbursement04,
		rgl.TargetAdjustedNetReimbursement05,
		rgl.TargetAdjustedNetReimbursement06,
		rgl.TargetAdjustedNetReimbursement07,
		rgl.TargetAdjustedNetReimbursement08,
		rgl.TargetAdjustedNetReimbursement09,
		rgl.TargetAdjustedNetReimbursement10,
		rgl.TargetAdjustedNetReimbursement11,
		rgl.TargetAdjustedNetReimbursement12,

		rgl.BudgetAdjustedNetReimbursement01,
		rgl.BudgetAdjustedNetReimbursement02,
		rgl.BudgetAdjustedNetReimbursement03,
		rgl.BudgetAdjustedNetReimbursement04,
		rgl.BudgetAdjustedNetReimbursement05,
		rgl.BudgetAdjustedNetReimbursement06,
		rgl.BudgetAdjustedNetReimbursement07,
		rgl.BudgetAdjustedNetReimbursement08,
		rgl.BudgetAdjustedNetReimbursement09,
		rgl.BudgetAdjustedNetReimbursement10,
		rgl.BudgetAdjustedNetReimbursement11,
		rgl.BudgetAdjustedNetReimbursement12,

		rgl.ProjectionAdjustedNetReimbursement01,
		rgl.ProjectionAdjustedNetReimbursement02,
		rgl.ProjectionAdjustedNetReimbursement03,
		rgl.ProjectionAdjustedNetReimbursement04,
		rgl.ProjectionAdjustedNetReimbursement05,
		rgl.ProjectionAdjustedNetReimbursement06,
		rgl.ProjectionAdjustedNetReimbursement07,
		rgl.ProjectionAdjustedNetReimbursement08,
		rgl.ProjectionAdjustedNetReimbursement09,
		rgl.ProjectionAdjustedNetReimbursement10,
		rgl.ProjectionAdjustedNetReimbursement11,
		rgl.ProjectionAdjustedNetReimbursement12,

		hist.PriorYearActualValueNetReimbursement01,
		hist.PriorYearActualValueNetReimbursement02,
		hist.PriorYearActualValueNetReimbursement03,
		hist.PriorYearActualValueNetReimbursement04,
		hist.PriorYearActualValueNetReimbursement05,
		hist.PriorYearActualValueNetReimbursement06,
		hist.PriorYearActualValueNetReimbursement07,
		hist.PriorYearActualValueNetReimbursement08,
		hist.PriorYearActualValueNetReimbursement09,
		hist.PriorYearActualValueNetReimbursement10,
		hist.PriorYearActualValueNetReimbursement11,
		hist.PriorYearActualValueNetReimbursement12,

		rgl.TargetAdjustedNetAsPercentOfCharge01,
		rgl.TargetAdjustedNetAsPercentOfCharge02,
		rgl.TargetAdjustedNetAsPercentOfCharge03,
		rgl.TargetAdjustedNetAsPercentOfCharge04,
		rgl.TargetAdjustedNetAsPercentOfCharge05,
		rgl.TargetAdjustedNetAsPercentOfCharge06,
		rgl.TargetAdjustedNetAsPercentOfCharge07,
		rgl.TargetAdjustedNetAsPercentOfCharge08,
		rgl.TargetAdjustedNetAsPercentOfCharge09,
		rgl.TargetAdjustedNetAsPercentOfCharge10,
		rgl.TargetAdjustedNetAsPercentOfCharge11,
		rgl.TargetAdjustedNetAsPercentOfCharge12,

		rgl.BudgetAdjustedNetAsPercentOfCharge01,
		rgl.BudgetAdjustedNetAsPercentOfCharge02,
		rgl.BudgetAdjustedNetAsPercentOfCharge03,
		rgl.BudgetAdjustedNetAsPercentOfCharge04,
		rgl.BudgetAdjustedNetAsPercentOfCharge05,
		rgl.BudgetAdjustedNetAsPercentOfCharge06,
		rgl.BudgetAdjustedNetAsPercentOfCharge07,
		rgl.BudgetAdjustedNetAsPercentOfCharge08,
		rgl.BudgetAdjustedNetAsPercentOfCharge09,
		rgl.BudgetAdjustedNetAsPercentOfCharge10,
		rgl.BudgetAdjustedNetAsPercentOfCharge11,
		rgl.BudgetAdjustedNetAsPercentOfCharge12,

		rgl.ProjectionAdjustedNetAsPercentOfCharge01,
		rgl.ProjectionAdjustedNetAsPercentOfCharge02,
		rgl.ProjectionAdjustedNetAsPercentOfCharge03,
		rgl.ProjectionAdjustedNetAsPercentOfCharge04,
		rgl.ProjectionAdjustedNetAsPercentOfCharge05,
		rgl.ProjectionAdjustedNetAsPercentOfCharge06,
		rgl.ProjectionAdjustedNetAsPercentOfCharge07,
		rgl.ProjectionAdjustedNetAsPercentOfCharge08,
		rgl.ProjectionAdjustedNetAsPercentOfCharge09,
		rgl.ProjectionAdjustedNetAsPercentOfCharge10,
		rgl.ProjectionAdjustedNetAsPercentOfCharge11,
		rgl.ProjectionAdjustedNetAsPercentOfCharge12,

		hist.PriorYearActualValueNetAsPercentOfCharge01,
		hist.PriorYearActualValueNetAsPercentOfCharge02,
		hist.PriorYearActualValueNetAsPercentOfCharge03,
		hist.PriorYearActualValueNetAsPercentOfCharge04,
		hist.PriorYearActualValueNetAsPercentOfCharge05,
		hist.PriorYearActualValueNetAsPercentOfCharge06,
		hist.PriorYearActualValueNetAsPercentOfCharge07,
		hist.PriorYearActualValueNetAsPercentOfCharge08,
		hist.PriorYearActualValueNetAsPercentOfCharge09,
		hist.PriorYearActualValueNetAsPercentOfCharge10,
		hist.PriorYearActualValueNetAsPercentOfCharge11,
		hist.PriorYearActualValueNetAsPercentOfCharge12

	FROM 
		[fp].[ReimbursementGeneralLedger] rgl
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON rgl.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [fp].[ReimbursementGeneralLedgerHistory] hist with (readuncommitted) ON rgl.ReimbursementGeneralLedgerID = hist.ReimbursementGeneralLedgerID
GO


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

-- fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues
CREATE VIEW fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues
AS
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 2    2022-11-01  JB          JAZZ-45621      Remove PayorID
*********************************************************************/
	WITH ChargeToStat AS (
		select BudgetConfigID,
			EntityID,
			DepartmentID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			PatientClassID,
			UnitTypeID,
			TimeClassID,
			FiscalYearID,
			FiscalMonthID,
			AccountID,
			RVUWeight,
			OriginalValue,
			Value,
			ManagerValue
		from [fp].[FactReportChargeToStatisticsCrosswalk]
		union all
		select BudgetConfigID,
			EntityID,
			DepartmentID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			PatientClassID,
			UnitTypeID,
			TimeClassID,
			FiscalYearID,
			FiscalMonthID,
			AccountID,
			RVUWeight,
			OriginalValue,
			Value,
			ManagerValue
		from [fp].[FactReportChargeToStatisticsCrosswalk_archive]
	),
	ChargeToStatHistory AS (
		select ChargeVolumeID,
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID,
			DepartmentID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			PatientClassID,
			UnitTypeID,
			TimeClassID,
			FiscalYearID,
			FiscalMonthID,
			AccountID,
			RVUWeight,
			Value
		from [fp].[FactReportChargeToStatisticsCrosswalkHistory]
		union all
		select ChargeVolumeID,
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID,
			DepartmentID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			PatientClassID,
			UnitTypeID,
			TimeClassID,
			FiscalYearID,
			FiscalMonthID,
			AccountID,
			RVUWeight,
			Value
		from [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive]
	)
	
		-- Manager Projection
		SELECT
			bc.BudgetConfigID,
			st.EntityID,
			st.DepartmentID,
			st.AccountID,
			bc.FiscalYearID-1 as FiscalYearID,
			TimeClassID,
			ManagerValue as Value,			
			UnitTypeID,		
			st.PatientClassID,
			st.ChargeCodeID,
			st.ServiceLineID,
			st.AgeCohortID,
			st.MedicalSurgicalID,
			st.RVUWeight,
			FiscalMonthID
		from ChargeToStat st
		INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID
		WHERE TimeClassID=12

		union all

		-- Initial Budget
		SELECT
			BudgetConfigID,
			st.EntityID,
			st.DepartmentID,
			st.AccountID,
			FiscalYearID,
			21 as TimeClassID,
			OriginalValue as Value,
			UnitTypeID,
			st.PatientClassID,
			st.ChargeCodeID,
			st.ServiceLineID,
			st.AgeCohortID,
			st.MedicalSurgicalID,
			st.RVUWeight,
			FiscalMonthID
		from ChargeToStat st
		WHERE TimeClassID=2

		union all

		-- Manager Budget
		select
			BudgetConfigID,
			st.EntityID,
			st.DepartmentID,
			st.AccountID,
			FiscalYearID,
			TimeClassID,
			ManagerValue as Value,
			UnitTypeID,
			st.PatientClassID,
			st.ChargeCodeID,
			st.ServiceLineID,
			st.AgeCohortID,
			st.MedicalSurgicalID,
			st.RVUWeight,
			FiscalMonthID
		from ChargeToStat st
		WHERE TimeClassID=2

		union all

		-- Baseline Budget
		select
			BudgetConfigID,
			st.EntityID,
			st.DepartmentID,
			st.AccountID,
			FiscalYearID,
			22 as TimeClassID,
			Value,
			UnitTypeID,
			st.PatientClassID,
			st.ChargeCodeID,
			st.ServiceLineID,
			st.AgeCohortID,
			st.MedicalSurgicalID,
			st.RVUWeight,
			FiscalMonthID
		from ChargeToStat st
		WHERE TimeClassID=2

		union all

		-- Prior Year Actual and Current Year Budget
		select
			bc.BudgetConfigID,
			st.EntityID,
			st.DepartmentID,
			st.AccountID,
			st.FiscalYearID,
			TimeClassID,
			Value,
			UnitTypeID,
			st.PatientClassID,
			st.ChargeCodeID,
			st.ServiceLineID,
			st.AgeCohortID,
			st.MedicalSurgicalID,
			st.RVUWeight,
			FiscalMonthID
		from ChargeToStatHistory st
		INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID
		WHERE TimeClassID in(1, 2)
GO


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

-- fp.viewReportChargeToStatisticsCrosswalk_Unpivoted
CREATE VIEW fp.viewReportChargeToStatisticsCrosswalk_Unpivoted
AS 
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 2    2022-11-01  JB          JAZZ-45621      Remove PayorID
*********************************************************************/
	-- Making sure final projection has all months included
	SELECT  cvToStat.[BudgetConfigID], 
			cvToStat.[EntityID],
			cvToStat.[DepartmentID], 
			cvToStat.[AccountID],
			cvToStat.[PatientClassID], 
			cvToStat.[UnitTypeID], 
			cvToStat.[TimeClassID],
			cvToStat.[FiscalMonthID], 
			cvToStat.[FiscalYearID],
			cvToStat.ChargeCodeID, 
			cvToStat.ServiceLineID, 
			cvToStat.AgeCohortID, 
			cvToStat.MedicalSurgicalID, 
			--cvToStat.RVUWeight, -- Disabling this for now because the value is wrong
			COALESCE(frs.Value, cvToStat.Value) as Value
	FROM (
		SELECT DISTINCT [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [PatientClassID],
			[ChargeCodeID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [UnitTypeID], [TimeClassID],
			ca.[FiscalMonthID], [FiscalYearID], [RVUWeight], 0 as Value, 0 as OriginalValue, 0 as ManagerValue
		FROM fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues
		CROSS APPLY (
			select FiscalMonthID
			from [fw].[DimFiscalMonth]
			WHERE FiscalMonthID != 0
			) ca
		WHERE TimeClassID IN (1, 2, 12, 21, 22)
	) cvToStat 

	LEFT JOIN (select * from fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues) frs
	ON cvToStat.BudgetConfigID = frs.BudgetConfigID
		and cvToStat.DepartmentID = frs.DepartmentID
		and cvToStat.AccountID = frs.AccountID
		and cvToStat.FiscalYearID = frs.FiscalYearID
		and cvToStat.TimeClassID = frs.TimeClassID
		and cvToStat.FiscalMonthID = frs.FiscalMonthID
		and cvToStat.PatientClassID = frs.PatientClassID
		and cvToStat.UnitTypeID = frs.UnitTypeID
		and cvToStat.ChargeCodeID = frs.ChargeCodeID
		and cvToStat.AgeCohortID = frs.AgeCohortID
		and cvToStat.ServiceLineID = frs.ServiceLineID
		and cvToStat.MedicalSurgicalID = frs.MedicalSurgicalID
GO


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

-- fp.viewReportEncounter_MonthsWithValues
CREATE VIEW [fp].[viewReportEncounter_MonthsWithValues]  AS
	WITH Enc AS (
		select BudgetConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, DepartmentID, PayorID, PayorGroupID,
		MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue
		from [fp].[FactReportEncounter]
		union all
		select BudgetConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, DepartmentID, PayorID, PayorGroupID,
		MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue
		from [fp].[FactReportEncounter_archive]
	),
	EncHistory AS (
		select ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		DepartmentID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, Value  
		from [fp].[FactReportEncounterHistory]
		union all
		select ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, 
		DepartmentID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, Value 
		from [fp].[FactReportEncounterHistory_archive]
	)
	
		-- Manager Projection
		SELECT
			bc.BudgetConfigID,
			ec.EntityID,
			ec.DepartmentID,
			bc.FiscalYearID-1 as FiscalYearID,
			TimeClassID,
			Value as Value,
			UnitTypeID,
			ec.ServiceLineID,
			ec.ServiceLineRollupID,
			ec.PatientClassID,
			ec.AgeCohortID,
			ec.MedicalSurgicalID,
			ec.PayorID,
			ec.PayorGroupID,
			ec.MSDRGID,
			ec.CPTID,
			ec.ProviderID,
			ec.PhysicianSpecialtyID,
			ec.FiscalMonthID
		from Enc ec
		INNER JOIN fp.BudgetConfig bc on ec.BudgetConfigID = bc.BudgetConfigID
		WHERE TimeClassID=12

		union all

		-- Initial Budget
		SELECT
			BudgetConfigID,
			ec.EntityID,
			ec.DepartmentID,
			ec.FiscalYearID,
			21 as TimeClassID,
			OriginalValue as Value,
			UnitTypeID,
			ec.ServiceLineID,
			ec.ServiceLineRollupID,
			ec.PatientClassID,
			ec.AgeCohortID,
			ec.MedicalSurgicalID,
			ec.PayorID,
			ec.PayorGroupID,
			ec.MSDRGID,
			ec.CPTID,
			ec.ProviderID,
			ec.PhysicianSpecialtyID,
			ec.FiscalMonthID
		from Enc ec
		WHERE TimeClassID=2

		union all

		-- Manager Budget
		select
			BudgetConfigID,
			ec.EntityID,
			ec.DepartmentID,
			ec.FiscalYearID,
			TimeClassID,
			ManagerValue as Value,
			UnitTypeID,
			ec.ServiceLineID,
			ec.ServiceLineRollupID,
			ec.PatientClassID,
			ec.AgeCohortID,
			ec.MedicalSurgicalID,
			ec.PayorID,
			ec.PayorGroupID,
			ec.MSDRGID,
			ec.CPTID,
			ec.ProviderID,
			ec.PhysicianSpecialtyID,
			ec.FiscalMonthID
		from Enc ec
		WHERE TimeClassID=2

		union all

		-- Baseline Budget
		select
			BudgetConfigID,
			ec.EntityID,
			ec.DepartmentID,
			ec.FiscalYearID,
			22 as TimeClassID,
			Value,
			UnitTypeID,
			ec.ServiceLineID,
			ec.ServiceLineRollupID,
			ec.PatientClassID,
			ec.AgeCohortID,
			ec.MedicalSurgicalID,
			ec.PayorID,
			ec.PayorGroupID,
			ec.MSDRGID,
			ec.CPTID,
			ec.ProviderID,
			ec.PhysicianSpecialtyID,
			ec.FiscalMonthID
		from Enc ec
		WHERE TimeClassID=2

		union all

		-- Prior Year Actual and Current Year Budget
		select
			bc.BudgetConfigID,
			ec.EntityID,
			ec.DepartmentID,
			ec.FiscalYearID,
			TimeClassID,
			Value,
			UnitTypeID,
			ec.ServiceLineID,
			ec.ServiceLineRollupID,
			ec.PatientClassID,
			ec.AgeCohortID,
			ec.MedicalSurgicalID,
			ec.PayorID,
			ec.PayorGroupID,
			ec.MSDRGID,
			ec.CPTID,
			ec.ProviderID,
			ec.PhysicianSpecialtyID,
			ec.FiscalMonthID
		from EncHistory ec
		INNER JOIN fp.BudgetConfig bc on ec.BudgetConfigID = bc.BudgetConfigID
		WHERE TimeClassID in(1, 2)
GO


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

-- fp.viewReportEncounter_Unpivoted
CREATE VIEW [fp].[viewReportEncounter_Unpivoted]
AS 
	-- Making sure final projection has all months included
	SELECT fre_allmths.[BudgetConfigID], fre_allmths.[EntityID],
		fre_allmths.[DepartmentID], fre_allmths.[ServiceLineID],
		fre_allmths.[ServiceLineRollupID], fre_allmths.[PatientClassID],
		fre_allmths.[AgeCohortID], fre_allmths.[MedicalSurgicalID],
		fre_allmths.[PayorID], fre_allmths.[PayorGroupID],
		fre_allmths.[MSDRGID], fre_allmths.[CPTID],
		fre_allmths.[ProviderID], fre_allmths.[PhysicianSpecialtyID],
		fre_allmths.[UnitTypeID], fre_allmths.[TimeClassID], 
		fre_allmths.[FiscalMonthID], fre_allmths.[FiscalYearID],
			COALESCE(fre.Value, fre_allmths.Value) as Value
	FROM (
		SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [ServiceLineRollupID], [PatientClassID], [AgeCohortID],
			[MedicalSurgicalID],[PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID],
			[UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID], 0 as Value, 0 as OriginalValue, 0 as ManagerValue
		FROM fp.viewReportEncounter_MonthsWithValues
		CROSS APPLY (
			select FiscalMonthID
			from [fw].[DimFiscalMonth]
			WHERE FiscalMonthID != 0
			) ca
		WHERE TimeClassID IN (1, 2, 12, 21, 22)
	) fre_allmths 

	LEFT JOIN (select * from fp.viewReportEncounter_MonthsWithValues) fre
	ON fre_allmths.BudgetConfigID = fre.BudgetConfigID
		and fre_allmths.DepartmentID = fre.DepartmentID
		and fre_allmths.FiscalYearID = fre.FiscalYearID
		and fre_allmths.TimeClassID = fre.TimeClassID
		and fre_allmths.FiscalMonthID = fre.FiscalMonthID
		and fre_allmths.ServiceLineID = fre.ServiceLineID
		and fre_allmths.ServiceLineRollupID = fre.ServiceLineRollupID
		and fre_allmths.PatientClassID = fre.PatientClassID
		and fre_allmths.AgeCohortID = fre.AgeCohortID
		and fre_allmths.MedicalSurgicalID = fre.MedicalSurgicalID
		and fre_allmths.PayorID = fre.PayorID
		and fre_allmths.PayorGroupID = fre.PayorGroupID
		and fre_allmths.MSDRGID = fre.MSDRGID
		and fre_allmths.CPTID = fre.CPTID
		and fre_allmths.ProviderID = fre.ProviderID
		and fre_allmths.PhysicianSpecialtyID = fre.PhysicianSpecialtyID
		and fre_allmths.UnitTypeID = fre.UnitTypeID
		and fre_allmths.EntityID = fre.EntityID
GO


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

-- fp.viewReportFinancialStatements
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2019-04-16  IP      B-22841		AP Income Statement Issues - Statistics
** 2    2020-05-04  LR      D-09648		Data in wrong FinancialStatement ID
** 3    2023-06-26  MD      JAZZ-54581	Simulate annualized time class
** 4	2024-07-18	DM		JAZZ-72142	Included IsUsedForReportComparison budget config data
** 5	2024-10-17	MY		JAZZ-78043	Annualized 2024 Time Class is not Calculating Correctly in IS
 *************************************************************/
CREATE   VIEW [fp].[viewReportFinancialStatements] 
as
	-- GL Dollars, Projection
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.ManagerValue as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.ManagerValue else 0 end as YTD,
		data.ManagerValue as Yearly,
		data.ManagerValue as Total
	from
		fp.viewFactGeneralLedger_UnPivoted data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.TimeClassID = 12
		and data.UnitTypeID = 34
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)
		
	union all

	-- GL Dollars, Target/Budget
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		tc.TimeClassID,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total
	from
		fp.viewFactGeneralLedger_UnPivoted data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		cross join fw.DimTimeClass tc with (readuncommitted)
	where
		data.TimeClassID = 2
		and data.UnitTypeID = 34
		and tc.TimeClassID in(2, 20)
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)
	
	union all
	
	-- GL Dollars, Actual
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		[fp].[viewFactGeneralLedgerHistory_Unpivoted] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.UnitTypeID = 34
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)

	union all
	
	-- GL Dollars, Annualized
	-- --------------------JAZZ-54581---------------------------------------------------
	-- We are adding in the annualized time class as a valid time class for AP Income Statement
	-- All data that is not generated by procReportFactStatisticsISBackup is pulled from the source tables in this view.
	-- Timeclass 19 (annualized) is the annualized version of current year actuals. The below case statements are annualizing 
	-- current year actual data, taking into account leap year. The leap year logic has been pulled 
	-- directly from procReportFactStatisticsISBackup
	-- BTB
	-- --------------------JAZZ-54581---------------------------------------------------
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		19 TimeClassID,
		(CASE WHEN 
			((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0)
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Amount,
		CASE WHEN fm.SortOrder <= bc.MonthsLoaded 
			THEN (CASE WHEN ((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0)
					THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
					ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END)
			ELSE 0 END as YTD,
		(CASE WHEN ((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0)
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Yearly,
		(CASE WHEN ((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0)
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Total
	from
		[fp].[viewFactGeneralLedgerHistory_Unpivoted] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		inner join fw.DimFiscalMonth fm2 on bc.MonthsLoaded = fm2.SortOrder --To get YTD days in month
		inner join fw.DimFiscalMonth fm3 on fm3.SortOrder = 12 --To get YTD days in full year
	where
		data.UnitTypeID = 34
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)
		and data.TimeClassID = 1
		and data.FiscalYearID = bc.FiscalYearID - 1
	
	union all

	-- Statistics, Projection
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.ManagerValue as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.ManagerValue else 0 end as YTD,
		data.ManagerValue as Yearly,
		data.ManagerValue as Total
	from
		fp.viewFactStatistics_UnPivoted data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.TimeClassID = 12
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)
		
	union all
	
	-- Statistics, Target/Budget
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		tc.TimeClassID,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total
	from
		fp.viewFactStatistics_UnPivoted data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		cross join fw.DimTimeClass tc with (readuncommitted)
	where
		data.TimeClassID = 2
		and tc.TimeClassID in(2, 20)
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)

	union all
	
	-- Statistics, Actual
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		[fp].[viewFactStatisticsHistory_Unpivoted] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	WHERE bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1

	union all
	
	-- Statistics, Annualized
	-- --------------------JAZZ-54581---------------------------------------------------
	-- We are adding in the annualized time class as a valid time class for AP Income Statement
	-- All data that is not generated by procReportFactStatisticsISBackup is pulled from the source tables in this view.
	-- Timeclass 19 (annualized) is the annualized version of current year actuals. The below case statements are annualizing 
	-- current year actual data, taking into account leap year. The leap year logic has been pulled 
	-- directly from procReportFactStatisticsISBackup
	-- BTB
	-- --------------------JAZZ-54581---------------------------------------------------
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		19 as TimeClassID,
		(CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Amount,
		CASE WHEN fm.SortOrder <= bc.MonthsLoaded 
			THEN (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
					THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
					ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END)
			ELSE 0 END as YTD,
		(CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Yearly,
		(CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Total
	from
		[fp].[viewFactStatisticsHistory_Unpivoted] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		inner join fw.DimFiscalMonth fm2 on bc.MonthsLoaded = fm2.SortOrder --To get YTD days in month
		inner join fw.DimFiscalMonth fm3 on fm3.SortOrder = 12 --To get YTD days in full year
	WHERE (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)
	and data.TimeClassID = 1
	and data.FiscalYearID = bc.FiscalYearID - 1
	
	union all
	
	-- Staffing Hours, Projection
	select
		data.BudgetConfigID,
		data.DepartmentID,
		0 as AccountID,
		CASE 
			WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 
			WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 
            ELSE 0 
		END AS FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.ManagerValue as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.ManagerValue else 0 end as YTD,
		data.ManagerValue as Yearly,
		data.ManagerValue as Total
	from
		fp.viewFactStaffing_UnPivoted data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.UnitTypeID = 51
		and data.TimeClassID = 12
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)
		
	union all
	
	-- Staffing Hours, Target/Budget
	select
		data.BudgetConfigID,
		data.DepartmentID,
		0 as AccountID,
		CASE 
			WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 
			WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 
            ELSE 0 
		END AS FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		tc.TimeClassID,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total
	from
		fp.viewFactStaffing_UnPivoted data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		cross join fw.DimTimeClass tc with (readuncommitted)
	where
		data.UnitTypeID = 51
		and data.TimeClassID = 2 
		and tc.TimeClassID in(2, 20) 
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)

	union all

	-- Staffing, Actual
	select
		data.BudgetConfigID,
		data.DepartmentID,
		0 as AccountID,
		CASE 
			WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 
			WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 
            ELSE 0 
		END AS FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		[fp].[viewFactStaffingHistory_Unpivoted] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.UnitTypeID = 51
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)

		union all

	-- Staffing, Annualized
	-- --------------------JAZZ-54581---------------------------------------------------
	-- We are adding in the annualized time class as a valid time class for AP Income Statement
	-- All data that is not generated by procReportFactStatisticsISBackup is pulled from the source tables in this view.
	-- Timeclass 19 (annualized) is the annualized version of current year actuals. The below case statements are annualizing 
	-- current year actual data, taking into account leap year. The leap year logic has been pulled 
	-- directly from procReportFactStatisticsISBackup
	-- BTB
	-- --------------------JAZZ-54581---------------------------------------------------
	select
		data.BudgetConfigID,
		data.DepartmentID,
		0 as AccountID,
		CASE 
			WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 
			WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 
            ELSE 0 
		END AS FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		19 as TimeClassID,
		(CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Amount,
		CASE WHEN fm.SortOrder <= bc.MonthsLoaded 
			THEN (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
					THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
					ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END)
			ELSE 0 END as YTD,
		(CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Yearly,
		(CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 
			THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) 
			ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Total
	from
		[fp].[viewFactStaffingHistory_Unpivoted] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		inner join fw.DimFiscalMonth fm2 on bc.MonthsLoaded = fm2.SortOrder --To get YTD days in month
		inner join fw.DimFiscalMonth fm3 on fm3.SortOrder = 12 --To get YTD days in full year
	where
		data.UnitTypeID = 51
		and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1)
		and data.TimeClassID = 1
		and data.FiscalYearID = bc.FiscalYearID - 1

	union all

	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,	--Stats - Other - Working Hours
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Amount,
		data.YTD,
		data.Yearly,
		data.Total
	FROM fp.FactISReportStatistics data
	INNER JOIN fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
	WHERE  bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1
GO


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

-- fp.viewReportFinancialStatements_archive
CREATE view [fp].[viewReportFinancialStatements_archive] 
as
	-- GL Dollars, Projection
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		fp.viewFactGeneralLedger_UnPivoted_archive data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.TimeClassID = 12
		and data.UnitTypeID = 34
		
	union all

	-- GL Dollars, Target/Budget
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		tc.TimeClassID,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total
	from
		fp.viewFactGeneralLedger_UnPivoted_archive data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		cross join fw.DimTimeClass tc with (readuncommitted)
	where
		data.TimeClassID = 2
		and data.UnitTypeID = 34
		and tc.TimeClassID in(2, 20)
	
	union all
	
	-- GL Dollars, Actual
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		[fp].[viewFactGeneralLedgerHistory_Unpivoted_archive] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.UnitTypeID = 34
	
	union all

	-- Statistics, Projection
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		fp.viewFactStatistics_UnPivoted_archive data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.TimeClassID = 12
		
	union all
	
	-- Statistics, Target/Budget
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		tc.TimeClassID,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total
	from
		fp.viewFactStatistics_UnPivoted_archive data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		cross join fw.DimTimeClass tc with (readuncommitted)
	where
		data.TimeClassID = 2
		and tc.TimeClassID in(2, 20)

	union all
	
	-- Statistics, Actual
	select 
		data.BudgetConfigID,
		data.DepartmentID,
		data.AccountID,
		data.FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		[fp].[viewFactStatisticsHistory_Unpivoted_archive] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	
	union all
	
	-- Staffing Hours, Projection
	select
		data.BudgetConfigID,
		data.DepartmentID,
		0 as AccountID,
		CASE 
			WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 
			WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 
			WHEN data.ProductiveClassID = 0 AND data.UnitTypeID = 51 THEN 4029
            ELSE 0 
		END AS FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		fp.viewFactStaffing_UnPivoted_archive data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.UnitTypeID = 51
		and data.TimeClassID = 12
		
	union all
	
	-- Staffing Hours, Target/Budget
	select
		data.BudgetConfigID,
		data.DepartmentID,
		0 as AccountID,
		CASE 
			WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 
			WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 
			WHEN data.ProductiveClassID = 0 AND data.UnitTypeID = 51 THEN 4029
            ELSE 0 
		END AS FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		tc.TimeClassID,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly,
		case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total
	from
		fp.viewFactStaffing_UnPivoted_archive data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
		cross join fw.DimTimeClass tc with (readuncommitted)
	where
		data.UnitTypeID = 51
		and data.TimeClassID = 2 
		and tc.TimeClassID in(2, 20) 

	union all

	-- Staffing, Actual
	select
		data.BudgetConfigID,
		data.DepartmentID,
		0 as AccountID,
		CASE 
			WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 
			WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 
			WHEN data.ProductiveClassID = 0 AND data.UnitTypeID = 51 THEN 4029
            ELSE 0 
		END AS FinancialReportingID,
		data.FiscalYearID,
		data.FiscalMonthID,
		data.TimeClassID,
		data.Value as Amount,
		case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD,
		data.Value as Yearly,
		data.Value as Total
	from
		[fp].[viewFactStaffingHistory_Unpivoted_archive] data with (readuncommitted)
		inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID
		inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID
	where
		data.UnitTypeID = 51

	union all

	-- Working Hours - Monthly
	select 
		bc.BudgetConfigID,
		d.DepartmentID,
		0 as AccountID,
		1015 as FinancialReportingID,	--Stats - Other - Working Hours
		WH.FiscalYearID,
		WH.FiscalMonthID,
		tc.TimeClassID,
		WH.Hours as Amount,
		WH.YTDHours as AmountYTD,
		WH.Hours as Yearly,
		WH.Hours as Total
	FROM 
		[fw].[DimDepartment] d with (readuncommitted)
		INNER JOIN [fw].[DimWorkWeek] ww WITH (READUNCOMMITTED) ON ww.WorkWeekID = d.WorkWeekID
		INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH ON ww.WorkWeekID = WH.WorkWeekID
		INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID
		CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted)
	WHERE 
		tc.TimeClassID in(1, 2, 12, 20)
		and bc.IsActive = 0

	union all

	-- Working Hours - Annual
	select 
		bc.BudgetConfigID,
		d.DepartmentID,
		0 as AccountID,
		1015 as FinancialReportingID,	--Stats - Other - Working Hours
		WH.FiscalYearID,
		0 as FiscalMonthID,
		tc.TimeClassID,
		SUM(WH.Hours) as Amount,
		SUM(WH.Hours) as AmountYTD,
		SUM(WH.Hours) as Yearly,
		SUM(WH.Hours) as Total
	FROM 
		[fw].[DimDepartment] d with (readuncommitted)
		INNER JOIN [fw].[DimWorkWeek] ww WITH (READUNCOMMITTED) ON ww.WorkWeekID = d.WorkWeekID
		INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH ON ww.WorkWeekID = WH.WorkWeekID
		INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID
		CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted)
	WHERE 
		tc.TimeClassID in(1, 2, 12, 20)
		and bc.IsActive = 0
	GROUP BY
		bc.BudgetConfigID,
		d.DepartmentID,
		WH.FiscalYearID,
		tc.TimeClassID
GO


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

-- fp.viewReportGeneralLedger
CREATE VIEW [fp].[viewReportGeneralLedger]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI   Description
 ** 1 	 2020-04-22  LR  	 D-09178	Including months with value zero on projection, so that reports wont have null values.
 ** 2 	 2020-04-23  LR  	 D-09151	Breaking down results by TimeCLassID, so that labels are displayed correctly in report.
 *************************************************************/
SELECT
		factReportGL_AllMonths.[BudgetConfigID],
		factReportGL_AllMonths.[DepartmentID],
		factReportGL_AllMonths.[EntityID],
		factReportGL_AllMonths.[AccountID],
		factReportGL_AllMonths.[FiscalYearID],
		factReportGL_AllMonths.[FiscalMonthID],
		factReportGL_AllMonths.[TimeClassID],
		factReportGL_AllMonths.VariabilityID,
		acc.PatientClassID,
     	COALESCE(vrgl.Value, factReportGL_AllMonths.Value) as Value
FROM (
	SELECT distinct budgetconfigID, DepartmentID, EntityID, AccountID, FiscalYearID, TimeClassID, VariabilityID, ca.FiscalMonthID, 0 as value
	FROM fp.viewReportGeneralLedger_MonthsWithValues
	CROSS APPLY (
		select FiscalMonthID
		from [fw].[DimFiscalMonth]
		WHERE FiscalMonthID != 0
		) ca
	) factReportGL_AllMonths 

LEFT JOIN (select * from fp.viewReportGeneralLedger_MonthsWithValues) vrgl
		ON factReportGL_AllMonths.BudgetConfigID = vrgl.BudgetConfigID
        and factReportGL_AllMonths.DepartmentID = vrgl.DepartmentID
        and factReportGL_AllMonths.AccountID = vrgl.AccountID
        and factReportGL_AllMonths.FiscalYearID = vrgl.FiscalYearID
        and factReportGL_AllMonths.TimeClassID = vrgl.TimeClassID
        and factReportGL_AllMonths.VariabilityID = vrgl.VariabilityID
        and factReportGL_AllMonths.FiscalMonthID = vrgl.FiscalMonthID
		
INNER JOIN [fw].[DimAccount] acc (READUNCOMMITTED) ON acc.AccountID = factReportGL_AllMonths.AccountID
INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON bc.BudgetConfigID = factReportGL_AllMonths.BudgetConfigID
GO


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

-- fp.viewReportGeneralLedgerInitiatives
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	8-17-2023  MY      JAZZ-58792		Update to new structure
*************************************************************/
CREATE   VIEW fp.viewReportGeneralLedgerInitiatives
AS
SELECT
	gl.BudgetConfigID,
	gl.DepartmentID,
	gl.EntityID,
	gl.AccountID,
	bc.FiscalYearID,
	acc.PatientClassID,
	gli.FiscalMonthID,
	gli.InitiativeForecast
FROM fp.GeneralLedger gl 
JOIN fw.DimAccount acc (READUNCOMMITTED) ON acc.AccountID = gl.AccountID
JOIN fp.BudgetConfig bc (READUNCOMMITTED) ON bc.BudgetConfigID = gl.BudgetConfigID
JOIN (
	SELECT
		GeneralLedgerID,
		InitiativeForecast,
		CASE
			WHEN FiscalMonthID = 'InitiativeForecast01' THEN 1
			WHEN FiscalMonthID = 'InitiativeForecast02' THEN 2
			WHEN FiscalMonthID = 'InitiativeForecast03' THEN 3
			WHEN FiscalMonthID = 'InitiativeForecast04' THEN 4
			WHEN FiscalMonthID = 'InitiativeForecast05' THEN 5
			WHEN FiscalMonthID = 'InitiativeForecast06' THEN 6
			WHEN FiscalMonthID = 'InitiativeForecast07' THEN 7
			WHEN FiscalMonthID = 'InitiativeForecast08' THEN 8
			WHEN FiscalMonthID = 'InitiativeForecast09' THEN 9
			WHEN FiscalMonthID = 'InitiativeForecast10' THEN 10
			WHEN FiscalMonthID = 'InitiativeForecast11' THEN 11
			WHEN FiscalMonthID = 'InitiativeForecast12' THEN 12
		END AS FiscalMonthID
	FROM fp.FactGeneralLedgerInitiative
	UNPIVOT (InitiativeForecast FOR FiscalMonthID IN (
		InitiativeForecast01,
		InitiativeForecast02,
		InitiativeForecast03,
		InitiativeForecast04,
		InitiativeForecast05,
		InitiativeForecast06,
		InitiativeForecast07,
		InitiativeForecast08,
		InitiativeForecast09,
		InitiativeForecast10,
		InitiativeForecast11,
		InitiativeForecast12
	)) unpivoted
) gli on gl.GeneralLedgerID = gli.GeneralLedgerID
GO


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

-- fp.viewReportGeneralLedgerSnapshot
CREATE   VIEW [fp].[viewReportGeneralLedgerSnapshot]
AS
/*************************************************************
** Change History
**************************************************************
** CID    Date        Author      WI			Description
** 1      2024-11-04  MY          JAZZ-77737	Initial
***************************************************************/
 
------------------------------------
-- This is a copy of fp.viewReportGeneralLedger essentially except cleaned up and adopted for Snapshots.
------------------------------------

WITH GL AS (  
	SELECT * FROM [fp].[viewFactGeneralLedgerSnapshot_UnPivoted]  
),
viewReportGeneralLedger_MonthsWithValues AS (
  -- Manager Projection  
  SELECT  
	SnapshotID,  
	bc.BudgetConfigID,  
	st.EntityID,  
	st.DepartmentID,  
	st.AccountID,  
	bc.FiscalYearID - 1 as FiscalYearID,  
	12 as TimeClassID,  
	ManagerValue as Value,  
	IsStat,  
	UnitTypeID,  
	st.FinancialReportingID,  
	acc.PatientClassID,  
	VariabilityID,  
	FiscalMonthID  
  FROM GL st  
	INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID  
	INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID = 12  
  
  UNION ALL  
  
  -- Initial Budget  
  SELECT  
	SnapshotID,  
	BudgetConfigID,  
	st.EntityID,  
	st.DepartmentID,  
	st.AccountID,  
	FiscalYearID,  
	21 as TimeClassID,  
	OriginalValue as Value,  
	IsStat,  
	UnitTypeID,  
	st.FinancialReportingID,  
	acc.PatientClassID,  
	VariabilityID,  
	FiscalMonthID  
  FROM GL st  
	INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID = 2  
  
  UNION ALL  
  
  -- Manager Budget  
  SELECT  
	SnapshotID,  
	BudgetConfigID,  
	st.EntityID,  
	st.DepartmentID,  
	st.AccountID,  
	FiscalYearID,  
	2 as TimeClassID,  
	ManagerValue as Value,  
	IsStat,  
	UnitTypeID,  
	st.FinancialReportingID,  
	acc.PatientClassID,  
	VariabilityID,  
	FiscalMonthID  
  FROM GL st  
	INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID = 2  
  
  UNION ALL  
  
  -- Baseline Budget  
  SELECT  
   SnapshotID,  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   FiscalYearID,  
   22 as TimeClassID,  
   Value,  
   IsStat,  
   UnitTypeID,  
   st.FinancialReportingID,  
   acc.PatientClassID,  
   VariabilityID,  
   FiscalMonthID  
  FROM GL st  
	INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID = 2  
 
)
SELECT
		factReportGL_AllMonths.[SnapshotID],
		factReportGL_AllMonths.[BudgetConfigID],
		factReportGL_AllMonths.[DepartmentID],
		factReportGL_AllMonths.[EntityID],
		factReportGL_AllMonths.[AccountID],
		factReportGL_AllMonths.[FiscalYearID],
		factReportGL_AllMonths.[FiscalMonthID],
		factReportGL_AllMonths.[TimeClassID],
		factReportGL_AllMonths.VariabilityID,
		acc.PatientClassID,
     	COALESCE(vrgl.Value, factReportGL_AllMonths.Value) AS Value
FROM (
	SELECT DISTINCT SnapshotID, budgetconfigID, DepartmentID, EntityID, AccountID, FiscalYearID, TimeClassID, VariabilityID, ca.FiscalMonthID, 0 as value
	FROM viewReportGeneralLedger_MonthsWithValues
	CROSS APPLY (
		select FiscalMonthID
		from [fw].[DimFiscalMonth]
		WHERE FiscalMonthID != 0
		) ca
	) factReportGL_AllMonths
	-- Not a fan of this, but the original is doing this too and I don't know the reason so I am leaving it.
	LEFT JOIN (
		SELECT * FROM viewReportGeneralLedger_MonthsWithValues
	) vrgl
			ON factReportGL_AllMonths.BudgetConfigID = vrgl.BudgetConfigID
			and factReportGL_AllMonths.SnapshotID = vrgl.SnapshotID
			and factReportGL_AllMonths.DepartmentID = vrgl.DepartmentID
			and factReportGL_AllMonths.AccountID = vrgl.AccountID
			and factReportGL_AllMonths.FiscalYearID = vrgl.FiscalYearID
			and factReportGL_AllMonths.TimeClassID = vrgl.TimeClassID
			and factReportGL_AllMonths.VariabilityID = vrgl.VariabilityID
			and factReportGL_AllMonths.FiscalMonthID = vrgl.FiscalMonthID
	INNER JOIN [fw].[DimAccount] acc (READUNCOMMITTED) ON acc.AccountID = factReportGL_AllMonths.AccountID
	INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON bc.BudgetConfigID = factReportGL_AllMonths.BudgetConfigID
GO


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

-- fp.viewReportGeneralLedger_MonthsWithValues
/*************************************************************
** Change History
**************************************************************
** CID    Date        Author     WI       Description
** 1    2021-07-20   MattD        JAZZ-23237  Added unions in for data transfer tables for CCHS
** 2    2021-11-21   MattD        JAZZ-29894  Removed unions in for data transfer tables for CCHS
***************************************************************/
  
 CREATE VIEW  fp.viewReportGeneralLedger_MonthsWithValues    
 AS  
 WITH GL AS (  
  select * from [fp].[viewFactGeneralLedger_UnPivoted]  
 ),  
 GLHistory AS (  
  select * from [fp].[viewFactGeneralLedgerHistory_UnPivoted]  
 )
   
  -- Manager Projection  
  SELECT  
   bc.BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   bc.FiscalYearID-1 as FiscalYearID,  
   12 as TimeClassID,  
   ManagerValue as Value,  
   IsStat,  
   UnitTypeID,  
   st.FinancialReportingID,  
   acc.PatientClassID,  
   VariabilityID,  
   FiscalMonthID  
  from GL st  
  INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID  
  INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID=12  
  
  union all  
  
  -- Initial Budget  
  SELECT  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   FiscalYearID,  
   21 as TimeClassID,  
   OriginalValue as Value,  
   IsStat,  
   UnitTypeID,  
   st.FinancialReportingID,  
   acc.PatientClassID,  
   VariabilityID,  
   FiscalMonthID  
  from GL st  
  INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID=2  
  
  union all  
  
  -- Manager Budget  
  select  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   FiscalYearID,  
   2 as TimeClassID,  
   ManagerValue as Value,  
   IsStat,  
   UnitTypeID,  
   st.FinancialReportingID,  
   acc.PatientClassID,  
   VariabilityID,  
   FiscalMonthID  
  from GL st  
  INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID=2  
  
  union all  
  
  -- Baseline Budget  
  select  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   FiscalYearID,  
   22 as TimeClassID,  
   Value,  
   IsStat,  
   UnitTypeID,  
   st.FinancialReportingID,  
   acc.PatientClassID,  
   VariabilityID,  
   FiscalMonthID  
  from GL st  
  INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID=2  
  
  union all  
  
  -- Prior Year Actual and Current Year Budget  
  select  
   bc.BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   st.FiscalYearID,  
   TimeClassID,  
   Value,  
   IsStat,  
   UnitTypeID,  
   st.FinancialReportingID,  
   acc.PatientClassID,  
   VariabilityID,  
   FiscalMonthID  
  from GLHistory st  
  INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID  
  INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID  
  WHERE TimeClassID in(1, 2)
GO


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

-- fp.viewReportGeneralLedger_WithFlex
/***** ***********************************************************
****** Author: lcunningham
****** Create Date: 2021-08-19
****** Description: GL reporting view having Flex originating from Demo 3.
****** Last Modified: 2022-03-24
****** GM Release: 2022.22
****** ***********************************************************
****** Change History
****** ***********************************************************
****** CID  Date        Author    WI            Description       
****** xx   2021-08-19  ljc       xxxx-xxxxxxx  Custom report view request
****** 1    2022-03-24  ljc       JAZZ-28731    Pulling in Flex total instead of Flex impact and view name change
****** **********************************************************/
       
CREATE 
     
  VIEW [fp].[viewReportGeneralLedger_WithFlex] 
    AS 
SELECT [BudgetConfigID], 
       [DepartmentID], 
       [EntityID], 
       [AccountID], 
       [FiscalYearID], 
       [TimeClassID], 
       [VariabilityID], 
       [PatientClassID], 
       SUM([Value]) AS [Value] 
       
  FROM [fp].[viewReportGeneralLedger] 
       
 GROUP BY 
       [BudgetConfigID], 
       [DepartmentID], 
       [EntityID], 
       [AccountID], 
       [FiscalYearID], 
       [TimeClassID], 
       [VariabilityID], 
       [PatientClassID] 
       
 UNION ALL 
       
SELECT [gl].[BudgetConfigID], 
       [gl].[DepartmentID], 
       [gl].[EntityID], 
       [gl].[AccountID], 
       [bc].[FiscalYearID], 
       '4' AS [TimeClassID], 
       [gl].[VariabilityID], 
       [acc].[PatientClassID], 
       SUM([glb].[FlexedValueTotal]) AS [Value] 
       
  FROM [fp].[FactGeneralLedger] AS [gl] 
       INNER JOIN [fp].[FactGeneralLedgerBudget] AS [glb] 
       ON [gl].[GeneralLedgerID] = [glb].[GeneralLedgerID] 
          AND [glb].[BudgetPhaseID] = 2  -- Target 
       
       INNER JOIN [fp].[BudgetConfig] AS [bc] 
       ON [bc].[BudgetConfigID] = [gl].[BudgetConfigID] 
       
       INNER JOIN [fw].[DimAccount] AS [acc] 
       ON [acc].[AccountID] = [gl].[AccountID] 
       
 WHERE [bc].[IsActive] = 1 
   AND [gl].[UnitTypeID] = 34 
   AND [glb].[FlexedValueTotal] != 0 
       
 GROUP BY 
       [gl].[BudgetConfigID], 
       [gl].[DepartmentID], 
       [gl].[EntityID], 
       [gl].[AccountID], 
       [bc].[FiscalYearID], 
       [gl].[VariabilityID], 
       [acc].[PatientClassID] 
       
 UNION ALL 
       
SELECT [gl].[BudgetConfigID], 
       [gl].[DepartmentID], 
       [gl].[EntityID], 
       [gl].[AccountID], 
       [bc].[FiscalYearID] - 1 AS [FiscalYearID], 
       '4' AS [TimeClassID], 
       [gl].[VariabilityID], 
       [acc].[PatientClassID], 
       SUM([glb].[FlexedValueTotal]) AS [Value] 
       
  FROM [fp].[FactGeneralLedger] AS [gl] 
       INNER JOIN [fp].[FactGeneralLedgerProjection] AS [glb] 
       ON [gl].[GeneralLedgerID] = [glb].[GeneralLedgerID] 
          AND [glb].[BudgetPhaseID] = 2  -- Target 
       
       INNER JOIN [fp].[BudgetConfig] AS [bc] 
       ON [bc].[BudgetConfigID] = [gl].[BudgetConfigID] 
       
       INNER JOIN [fw].[DimAccount] AS [acc] 
       ON [acc].[AccountID] = [gl].[AccountID] 
       
 WHERE [bc].[IsActive] = 1 
   AND [gl].[UnitTypeID] = 34 
   AND [glb].[FlexedValueTotal] != 0 
       
 GROUP BY 
       [gl].[BudgetConfigID], 
       [gl].[DepartmentID], 
       [gl].[EntityID], 
       [gl].[AccountID], 
       [bc].[FiscalYearID], 
       [gl].[VariabilityID], 
       [acc].[PatientClassID];
GO


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

-- fp.viewReportStaffing
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1 	 2021-05-24  BW  	 JAZZ-20170 Added missing EmployeeID in select statements; switch from MAX to SUM
*************************************************************/

CREATE VIEW [fp].[viewReportStaffing]
AS
WITH PivoUnpivo AS (
	SELECT BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
		,SUM([01]) as OriginalValue01
		,SUM([02]) as OriginalValue02
		,SUM([03]) as OriginalValue03
		,SUM([04]) as OriginalValue04
		,SUM([05]) as OriginalValue05
		,SUM([06]) as OriginalValue06
		,SUM([07]) as OriginalValue07
		,SUM([08]) as OriginalValue08
		,SUM([09]) as OriginalValue09
		,SUM([10]) as OriginalValue10
		,SUM([11]) as OriginalValue11
		,SUM([12]) as OriginalValue12
		,SUM([01_2]) as Value01
		,SUM([02_2]) as Value02
		,SUM([03_2]) as Value03
		,SUM([04_2]) as Value04
		,SUM([05_2]) as Value05
		,SUM([06_2]) as Value06
		,SUM([07_2]) as Value07
		,SUM([08_2]) as Value08
		,SUM([09_2]) as Value09
		,SUM([10_2]) as Value10
		,SUM([11_2]) as Value11
		,SUM([12_2]) as Value12
		,SUM([01_3]) as ManagerValue01
		,SUM([02_3]) as ManagerValue02
		,SUM([03_3]) as ManagerValue03
		,SUM([04_3]) as ManagerValue04
		,SUM([05_3]) as ManagerValue05
		,SUM([06_3]) as ManagerValue06
		,SUM([07_3]) as ManagerValue07
		,SUM([08_3]) as ManagerValue08
		,SUM([09_3]) as ManagerValue09
		,SUM([10_3]) as ManagerValue10
		,SUM([11_3]) as ManagerValue11
		,SUM([12_3]) as ManagerValue12
	FROM (
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3
			FROM [fp].[FactReportStaffing] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
			UNION ALL
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3
			FROM [fp].[FactReportStaffing_archive] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
		) X
		PIVOT (SUM(OriginalValue) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1
		PIVOT (SUM(Value) FOR FiscalMonthID_2 IN ([01_2],[02_2],[03_2],[04_2],[05_2],[06_2],[07_2],[08_2],[09_2],[10_2],[11_2],[12_2])) AS Pivot2
		PIVOT (SUM(ManagerValue) FOR FiscalMonthID_3 IN ([01_3],[02_3],[03_3],[04_3],[05_3],[06_3],[07_3],[08_3],[09_3],[10_3],[11_3],[12_3])) AS Pivot1
	GROUP BY 
		BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
),
PivoUnpivoHistory AS (
	SELECT BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
		,SUM([01]) as Value01
		,SUM([02]) as Value02
		,SUM([03]) as Value03
		,SUM([04]) as Value04
		,SUM([05]) as Value05
		,SUM([06]) as Value06
		,SUM([07]) as Value07
		,SUM([08]) as Value08
		,SUM([09]) as Value09
		,SUM([10]) as Value10
		,SUM([11]) as Value11
		,SUM([12]) as Value12
	FROM (
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,Value
			FROM [fp].[FactReportStaffingHistory] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
			UNION ALL
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,Value
			FROM [fp].[FactReportStaffingHistory_archive] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
		) X
		PIVOT (SUM(Value) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot2
	GROUP BY BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
)

-- Manager Budget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID,
	fs.VariabilityID,
    fs.TimeClassID,
    fs.UnitTypeID, 
	fs.EmployeeID,
	ISNULL(fs.ManagerValue01, 0.0) as Month01, 
	ISNULL(fs.ManagerValue02, 0.0) as Month02, 
	ISNULL(fs.ManagerValue03, 0.0) as Month03, 
	ISNULL(fs.ManagerValue04, 0.0) as Month04, 
	ISNULL(fs.ManagerValue05, 0.0) as Month05, 
	ISNULL(fs.ManagerValue06, 0.0) as Month06, 
	ISNULL(fs.ManagerValue07, 0.0) as Month07, 
	ISNULL(fs.ManagerValue08, 0.0) as Month08, 
	ISNULL(fs.ManagerValue09, 0.0) as Month09, 
	ISNULL(fs.ManagerValue10, 0.0) as Month10, 
	ISNULL(fs.ManagerValue11, 0.0) as Month11, 
	ISNULL(fs.ManagerValue12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.ManagerValue01, 0.0) + 
				ISNULL(fs.ManagerValue02, 0.0) + 
				ISNULL(fs.ManagerValue03, 0.0) + 
				ISNULL(fs.ManagerValue04, 0.0) + 
				ISNULL(fs.ManagerValue05, 0.0) + 
				ISNULL(fs.ManagerValue06, 0.0) + 
				ISNULL(fs.ManagerValue07, 0.0) + 
				ISNULL(fs.ManagerValue08, 0.0) + 
				ISNULL(fs.ManagerValue09, 0.0) + 
				ISNULL(fs.ManagerValue10, 0.0) + 
				ISNULL(fs.ManagerValue11, 0.0) + 
				ISNULL(fs.ManagerValue12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
WHERE 
	fs.TimeClassID=2
	
UNION ALL
	
-- Initial Budget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID,
	fs.VariabilityID,
    21 AS TimeClassID,
    fs.UnitTypeID, 
	fs.EmployeeID,
	ISNULL(fs.OriginalValue01, 0.0) as Month01, 
	ISNULL(fs.OriginalValue02, 0.0) as Month02, 
	ISNULL(fs.OriginalValue03, 0.0) as Month03, 
	ISNULL(fs.OriginalValue04, 0.0) as Month04, 
	ISNULL(fs.OriginalValue05, 0.0) as Month05, 
	ISNULL(fs.OriginalValue06, 0.0) as Month06, 
	ISNULL(fs.OriginalValue07, 0.0) as Month07, 
	ISNULL(fs.OriginalValue08, 0.0) as Month08, 
	ISNULL(fs.OriginalValue09, 0.0) as Month09, 
	ISNULL(fs.OriginalValue10, 0.0) as Month10, 
	ISNULL(fs.OriginalValue11, 0.0) as Month11, 
	ISNULL(fs.OriginalValue12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.OriginalValue01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.OriginalValue02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.OriginalValue03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.OriginalValue04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.OriginalValue05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.OriginalValue06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.OriginalValue07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.OriginalValue08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.OriginalValue09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.OriginalValue10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.OriginalValue11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.OriginalValue12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.OriginalValue01, 0.0) + 
				ISNULL(fs.OriginalValue02, 0.0) + 
				ISNULL(fs.OriginalValue03, 0.0) + 
				ISNULL(fs.OriginalValue04, 0.0) + 
				ISNULL(fs.OriginalValue05, 0.0) + 
				ISNULL(fs.OriginalValue06, 0.0) + 
				ISNULL(fs.OriginalValue07, 0.0) + 
				ISNULL(fs.OriginalValue08, 0.0) + 
				ISNULL(fs.OriginalValue09, 0.0) + 
				ISNULL(fs.OriginalValue10, 0.0) + 
				ISNULL(fs.OriginalValue11, 0.0) + 
				ISNULL(fs.OriginalValue12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
WHERE 
	fs.TimeClassID=2
	
UNION ALL

-- Baseline Budget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID,
	fs.VariabilityID,
    18 AS TimeClassID,
    fs.UnitTypeID, 
	fs.EmployeeID,
	ISNULL(fs.Value01, 0.0) as Month01, 
	ISNULL(fs.Value02, 0.0) as Month02, 
	ISNULL(fs.Value03, 0.0) as Month03, 
	ISNULL(fs.Value04, 0.0) as Month04, 
	ISNULL(fs.Value05, 0.0) as Month05, 
	ISNULL(fs.Value06, 0.0) as Month06, 
	ISNULL(fs.Value07, 0.0) as Month07, 
	ISNULL(fs.Value08, 0.0) as Month08, 
	ISNULL(fs.Value09, 0.0) as Month09, 
	ISNULL(fs.Value10, 0.0) as Month10, 
	ISNULL(fs.Value11, 0.0) as Month11, 
	ISNULL(fs.Value12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.Value01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.Value02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.Value03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.Value04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.Value05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.Value06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.Value07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.Value08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.Value09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.Value10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.Value11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.Value12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.Value01, 0.0) + 
				ISNULL(fs.Value02, 0.0) + 
				ISNULL(fs.Value03, 0.0) + 
				ISNULL(fs.Value04, 0.0) + 
				ISNULL(fs.Value05, 0.0) + 
				ISNULL(fs.Value06, 0.0) + 
				ISNULL(fs.Value07, 0.0) + 
				ISNULL(fs.Value08, 0.0) + 
				ISNULL(fs.Value09, 0.0) + 
				ISNULL(fs.Value10, 0.0) + 
				ISNULL(fs.Value11, 0.0) + 
				ISNULL(fs.Value12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
WHERE 
	fs.TimeClassID=2

UNION ALL

-- Manager Projection
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID - 1 as FiscalYearID,
	fs.VariabilityID,
    12 AS TimeClassID,
    fs.UnitTypeID,
	fs.EmployeeID,
	ISNULL(fs.ManagerValue01, 0.0) as Month01, 
	ISNULL(fs.ManagerValue02, 0.0) as Month02, 
	ISNULL(fs.ManagerValue03, 0.0) as Month03, 
	ISNULL(fs.ManagerValue04, 0.0) as Month04, 
	ISNULL(fs.ManagerValue05, 0.0) as Month05, 
	ISNULL(fs.ManagerValue06, 0.0) as Month06, 
	ISNULL(fs.ManagerValue07, 0.0) as Month07, 
	ISNULL(fs.ManagerValue08, 0.0) as Month08, 
	ISNULL(fs.ManagerValue09, 0.0) as Month09, 
	ISNULL(fs.ManagerValue10, 0.0) as Month10, 
	ISNULL(fs.ManagerValue11, 0.0) as Month11, 
	ISNULL(fs.ManagerValue12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.ManagerValue01, 0.0) + 
				ISNULL(fs.ManagerValue02, 0.0) + 
				ISNULL(fs.ManagerValue03, 0.0) + 
				ISNULL(fs.ManagerValue04, 0.0) + 
				ISNULL(fs.ManagerValue05, 0.0) + 
				ISNULL(fs.ManagerValue06, 0.0) + 
				ISNULL(fs.ManagerValue07, 0.0) + 
				ISNULL(fs.ManagerValue08, 0.0) + 
				ISNULL(fs.ManagerValue09, 0.0) + 
				ISNULL(fs.ManagerValue10, 0.0) + 
				ISNULL(fs.ManagerValue11, 0.0) + 
				ISNULL(fs.ManagerValue12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID - 1 and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
WHERE 
	fs.TimeClassID = 12 

UNION ALL	
	
-- PriorYearActual and CurrentYearBudget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.FiscalYearID,
	fs.VariabilityID,
	fs.TimeClassID,
	fs.UnitTypeID,
	fs.EmployeeID,
	ISNULL(fs.Value01, 0.0) AS Month01, 
	ISNULL(fs.Value02, 0.0) AS Month02, 
	ISNULL(fs.Value03, 0.0) AS Month03, 
	ISNULL(fs.Value04, 0.0) AS Month04, 
	ISNULL(fs.Value05, 0.0) AS Month05, 
	ISNULL(fs.Value06, 0.0) AS Month06, 
	ISNULL(fs.Value07, 0.0) AS Month07, 
	ISNULL(fs.Value08, 0.0) AS Month08, 
	ISNULL(fs.Value09, 0.0) AS Month09, 
	ISNULL(fs.Value10, 0.0) AS Month10, 
	ISNULL(fs.Value11, 0.0) AS Month11, 
	ISNULL(fs.Value12, 0.0) AS Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.Value01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.Value02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.Value03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.Value04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.Value05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.Value06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.Value07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.Value08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.Value09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.Value10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.Value11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.Value12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.Value01, 0.0) + 
				ISNULL(fs.Value02, 0.0) + 
				ISNULL(fs.Value03, 0.0) + 
				ISNULL(fs.Value04, 0.0) + 
				ISNULL(fs.Value05, 0.0) + 
				ISNULL(fs.Value06, 0.0) + 
				ISNULL(fs.Value07, 0.0) + 
				ISNULL(fs.Value08, 0.0) + 
				ISNULL(fs.Value09, 0.0) + 
				ISNULL(fs.Value10, 0.0) + 
				ISNULL(fs.Value11, 0.0) + 
				ISNULL(fs.Value12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivoHistory fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID 
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = fs.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
WHERE 
	fs.TimeClassID IN (1, 2)
GO


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

-- fp.viewReportStaffingForEmployeeAndProvider
CREATE VIEW [fp].[viewReportStaffingForEmployeeAndProvider]
AS
WITH PivoUnpivo AS (
	SELECT BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
		,ProviderID
		,ProviderLineItemID
		,ProviderTypeID
		,ProviderSpecialtyID
		,SUM([01]) as OriginalValue01
		,SUM([02]) as OriginalValue02
		,SUM([03]) as OriginalValue03
		,SUM([04]) as OriginalValue04
		,SUM([05]) as OriginalValue05
		,SUM([06]) as OriginalValue06
		,SUM([07]) as OriginalValue07
		,SUM([08]) as OriginalValue08
		,SUM([09]) as OriginalValue09
		,SUM([10]) as OriginalValue10
		,SUM([11]) as OriginalValue11
		,SUM([12]) as OriginalValue12
		,SUM([01_2]) as Value01
		,SUM([02_2]) as Value02
		,SUM([03_2]) as Value03
		,SUM([04_2]) as Value04
		,SUM([05_2]) as Value05
		,SUM([06_2]) as Value06
		,SUM([07_2]) as Value07
		,SUM([08_2]) as Value08
		,SUM([09_2]) as Value09
		,SUM([10_2]) as Value10
		,SUM([11_2]) as Value11
		,SUM([12_2]) as Value12
		,SUM([01_3]) as ManagerValue01
		,SUM([02_3]) as ManagerValue02
		,SUM([03_3]) as ManagerValue03
		,SUM([04_3]) as ManagerValue04
		,SUM([05_3]) as ManagerValue05
		,SUM([06_3]) as ManagerValue06
		,SUM([07_3]) as ManagerValue07
		,SUM([08_3]) as ManagerValue08
		,SUM([09_3]) as ManagerValue09
		,SUM([10_3]) as ManagerValue10
		,SUM([11_3]) as ManagerValue11
		,SUM([12_3]) as ManagerValue12
	FROM (
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,
			ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3
			FROM [fp].[FactReportStaffing] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
			UNION ALL
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,
			ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3
			FROM [fp].[FactReportStaffing_archive] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
		) X
		PIVOT (SUM(OriginalValue) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1
		PIVOT (SUM(Value) FOR FiscalMonthID_2 IN ([01_2],[02_2],[03_2],[04_2],[05_2],[06_2],[07_2],[08_2],[09_2],[10_2],[11_2],[12_2])) AS Pivot2
		PIVOT (SUM(ManagerValue) FOR FiscalMonthID_3 IN ([01_3],[02_3],[03_3],[04_3],[05_3],[06_3],[07_3],[08_3],[09_3],[10_3],[11_3],[12_3])) AS Pivot1
	GROUP BY 
		BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
		,ProviderID
		,ProviderLineItemID
		,ProviderTypeID
		,ProviderSpecialtyID
),
PivoUnpivoHistory AS (
	SELECT BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
		,ProviderID
		,ProviderLineItemID
		,ProviderTypeID
		,ProviderSpecialtyID
		,SUM([01]) as Value01
		,SUM([02]) as Value02
		,SUM([03]) as Value03
		,SUM([04]) as Value04
		,SUM([05]) as Value05
		,SUM([06]) as Value06
		,SUM([07]) as Value07
		,SUM([08]) as Value08
		,SUM([09]) as Value09
		,SUM([10]) as Value10
		,SUM([11]) as Value11
		,SUM([12]) as Value12
	FROM (
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,
			ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, Value
			FROM [fp].[FactReportStaffingHistory] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
			UNION ALL
			SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,
			ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, Value
			FROM [fp].[FactReportStaffingHistory_archive] f with (readuncommitted)
			INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID
		) X
		PIVOT (SUM(Value) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot2
	GROUP BY BudgetConfigID
		,EntityID
		,DepartmentID
		,JobCodeID
		,PayCodeGroupID
		,VariabilityID
		,ProductiveClassID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,EmployeeID
		,ProviderID
		,ProviderLineItemID
		,ProviderTypeID
		,ProviderSpecialtyID
)

-- Manager Budget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID,
	fs.VariabilityID,
    fs.TimeClassID,
    fs.UnitTypeID, 
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderLineItemID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	ISNULL(fs.ManagerValue01, 0.0) as Month01, 
	ISNULL(fs.ManagerValue02, 0.0) as Month02, 
	ISNULL(fs.ManagerValue03, 0.0) as Month03, 
	ISNULL(fs.ManagerValue04, 0.0) as Month04, 
	ISNULL(fs.ManagerValue05, 0.0) as Month05, 
	ISNULL(fs.ManagerValue06, 0.0) as Month06, 
	ISNULL(fs.ManagerValue07, 0.0) as Month07, 
	ISNULL(fs.ManagerValue08, 0.0) as Month08, 
	ISNULL(fs.ManagerValue09, 0.0) as Month09, 
	ISNULL(fs.ManagerValue10, 0.0) as Month10, 
	ISNULL(fs.ManagerValue11, 0.0) as Month11, 
	ISNULL(fs.ManagerValue12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.ManagerValue01, 0.0) + 
				ISNULL(fs.ManagerValue02, 0.0) + 
				ISNULL(fs.ManagerValue03, 0.0) + 
				ISNULL(fs.ManagerValue04, 0.0) + 
				ISNULL(fs.ManagerValue05, 0.0) + 
				ISNULL(fs.ManagerValue06, 0.0) + 
				ISNULL(fs.ManagerValue07, 0.0) + 
				ISNULL(fs.ManagerValue08, 0.0) + 
				ISNULL(fs.ManagerValue09, 0.0) + 
				ISNULL(fs.ManagerValue10, 0.0) + 
				ISNULL(fs.ManagerValue11, 0.0) + 
				ISNULL(fs.ManagerValue12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
	INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID
	INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID
	INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID
	INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID
WHERE 
	fs.TimeClassID=2
	
UNION ALL
	
-- Initial Budget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID,
	fs.VariabilityID,
    21 AS TimeClassID,
    fs.UnitTypeID, 
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderLineItemID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	ISNULL(fs.OriginalValue01, 0.0) as Month01, 
	ISNULL(fs.OriginalValue02, 0.0) as Month02, 
	ISNULL(fs.OriginalValue03, 0.0) as Month03, 
	ISNULL(fs.OriginalValue04, 0.0) as Month04, 
	ISNULL(fs.OriginalValue05, 0.0) as Month05, 
	ISNULL(fs.OriginalValue06, 0.0) as Month06, 
	ISNULL(fs.OriginalValue07, 0.0) as Month07, 
	ISNULL(fs.OriginalValue08, 0.0) as Month08, 
	ISNULL(fs.OriginalValue09, 0.0) as Month09, 
	ISNULL(fs.OriginalValue10, 0.0) as Month10, 
	ISNULL(fs.OriginalValue11, 0.0) as Month11, 
	ISNULL(fs.OriginalValue12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.OriginalValue01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.OriginalValue02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.OriginalValue03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.OriginalValue04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.OriginalValue05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.OriginalValue06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.OriginalValue07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.OriginalValue08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.OriginalValue09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.OriginalValue10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.OriginalValue11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.OriginalValue12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.OriginalValue01, 0.0) + 
				ISNULL(fs.OriginalValue02, 0.0) + 
				ISNULL(fs.OriginalValue03, 0.0) + 
				ISNULL(fs.OriginalValue04, 0.0) + 
				ISNULL(fs.OriginalValue05, 0.0) + 
				ISNULL(fs.OriginalValue06, 0.0) + 
				ISNULL(fs.OriginalValue07, 0.0) + 
				ISNULL(fs.OriginalValue08, 0.0) + 
				ISNULL(fs.OriginalValue09, 0.0) + 
				ISNULL(fs.OriginalValue10, 0.0) + 
				ISNULL(fs.OriginalValue11, 0.0) + 
				ISNULL(fs.OriginalValue12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
	INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID
	INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID
	INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID
	INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID
WHERE 
	fs.TimeClassID=2
	
UNION ALL

-- Baseline Budget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID,
	fs.VariabilityID,
    18 AS TimeClassID,
    fs.UnitTypeID, 
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderLineItemID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	ISNULL(fs.Value01, 0.0) as Month01, 
	ISNULL(fs.Value02, 0.0) as Month02, 
	ISNULL(fs.Value03, 0.0) as Month03, 
	ISNULL(fs.Value04, 0.0) as Month04, 
	ISNULL(fs.Value05, 0.0) as Month05, 
	ISNULL(fs.Value06, 0.0) as Month06, 
	ISNULL(fs.Value07, 0.0) as Month07, 
	ISNULL(fs.Value08, 0.0) as Month08, 
	ISNULL(fs.Value09, 0.0) as Month09, 
	ISNULL(fs.Value10, 0.0) as Month10, 
	ISNULL(fs.Value11, 0.0) as Month11, 
	ISNULL(fs.Value12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.Value01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.Value02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.Value03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.Value04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.Value05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.Value06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.Value07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.Value08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.Value09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.Value10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.Value11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.Value12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.Value01, 0.0) + 
				ISNULL(fs.Value02, 0.0) + 
				ISNULL(fs.Value03, 0.0) + 
				ISNULL(fs.Value04, 0.0) + 
				ISNULL(fs.Value05, 0.0) + 
				ISNULL(fs.Value06, 0.0) + 
				ISNULL(fs.Value07, 0.0) + 
				ISNULL(fs.Value08, 0.0) + 
				ISNULL(fs.Value09, 0.0) + 
				ISNULL(fs.Value10, 0.0) + 
				ISNULL(fs.Value11, 0.0) + 
				ISNULL(fs.Value12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
	INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID
	INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID
	INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID
	INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID
WHERE 
	fs.TimeClassID=2

UNION ALL

-- Manager Projection
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
    fs.JobCodeID,
    fs.PayCodeGroupID,
    bc.FiscalYearID - 1 as FiscalYearID,
	fs.VariabilityID,
    12 AS TimeClassID,
    fs.UnitTypeID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderLineItemID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	ISNULL(fs.ManagerValue01, 0.0) as Month01, 
	ISNULL(fs.ManagerValue02, 0.0) as Month02, 
	ISNULL(fs.ManagerValue03, 0.0) as Month03, 
	ISNULL(fs.ManagerValue04, 0.0) as Month04, 
	ISNULL(fs.ManagerValue05, 0.0) as Month05, 
	ISNULL(fs.ManagerValue06, 0.0) as Month06, 
	ISNULL(fs.ManagerValue07, 0.0) as Month07, 
	ISNULL(fs.ManagerValue08, 0.0) as Month08, 
	ISNULL(fs.ManagerValue09, 0.0) as Month09, 
	ISNULL(fs.ManagerValue10, 0.0) as Month10, 
	ISNULL(fs.ManagerValue11, 0.0) as Month11, 
	ISNULL(fs.ManagerValue12, 0.0) as Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.ManagerValue01, 0.0) + 
				ISNULL(fs.ManagerValue02, 0.0) + 
				ISNULL(fs.ManagerValue03, 0.0) + 
				ISNULL(fs.ManagerValue04, 0.0) + 
				ISNULL(fs.ManagerValue05, 0.0) + 
				ISNULL(fs.ManagerValue06, 0.0) + 
				ISNULL(fs.ManagerValue07, 0.0) + 
				ISNULL(fs.ManagerValue08, 0.0) + 
				ISNULL(fs.ManagerValue09, 0.0) + 
				ISNULL(fs.ManagerValue10, 0.0) + 
				ISNULL(fs.ManagerValue11, 0.0) + 
				ISNULL(fs.ManagerValue12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivo fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID - 1 and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
	INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID
	INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID
	INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID
	INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID
WHERE 
	fs.TimeClassID = 12 

UNION ALL	
	
-- PriorYearActual and CurrentYearBudget
SELECT 
	fs.DepartmentID,
	fs.BudgetConfigID,
	fs.JobCodeID,
	fs.PayCodeGroupID,
	fs.FiscalYearID,
	fs.VariabilityID,
	fs.TimeClassID,
	fs.UnitTypeID,
	fs.EmployeeID,
	fs.ProviderID,
	fs.ProviderLineItemID,
	fs.ProviderTypeID,
	fs.ProviderSpecialtyID,
	ISNULL(fs.Value01, 0.0) AS Month01, 
	ISNULL(fs.Value02, 0.0) AS Month02, 
	ISNULL(fs.Value03, 0.0) AS Month03, 
	ISNULL(fs.Value04, 0.0) AS Month04, 
	ISNULL(fs.Value05, 0.0) AS Month05, 
	ISNULL(fs.Value06, 0.0) AS Month06, 
	ISNULL(fs.Value07, 0.0) AS Month07, 
	ISNULL(fs.Value08, 0.0) AS Month08, 
	ISNULL(fs.Value09, 0.0) AS Month09, 
	ISNULL(fs.Value10, 0.0) AS Month10, 
	ISNULL(fs.Value11, 0.0) AS Month11, 
	ISNULL(fs.Value12, 0.0) AS Month12, 
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end
			) / (
				case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + 
				case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + 
				case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + 
				case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + 
				case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + 
				case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + 
				case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + 
				case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + 
				case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + 
				case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + 
				case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + 
				case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end
			)
		ELSE (
				case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end +
				case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end
			)
		END AS YTD,
	CASE 
		WHEN fs.UnitTypeID = 144 THEN (
				(ISNULL(fs.Value01, 0.0) * fwh.Month01) + 
				(ISNULL(fs.Value02, 0.0) * fwh.Month02) + 
				(ISNULL(fs.Value03, 0.0) * fwh.Month03) + 
				(ISNULL(fs.Value04, 0.0) * fwh.Month04) + 
				(ISNULL(fs.Value05, 0.0) * fwh.Month05) + 
				(ISNULL(fs.Value06, 0.0) * fwh.Month06) + 
				(ISNULL(fs.Value07, 0.0) * fwh.Month07) + 
				(ISNULL(fs.Value08, 0.0) * fwh.Month08) + 
				(ISNULL(fs.Value09, 0.0) * fwh.Month09) + 
				(ISNULL(fs.Value10, 0.0) * fwh.Month10) + 
				(ISNULL(fs.Value11, 0.0) * fwh.Month11) + 
				(ISNULL(fs.Value12, 0.0) * fwh.Month12)
			) / fwh.MonthYearly
		ELSE (
				ISNULL(fs.Value01, 0.0) + 
				ISNULL(fs.Value02, 0.0) + 
				ISNULL(fs.Value03, 0.0) + 
				ISNULL(fs.Value04, 0.0) + 
				ISNULL(fs.Value05, 0.0) + 
				ISNULL(fs.Value06, 0.0) + 
				ISNULL(fs.Value07, 0.0) + 
				ISNULL(fs.Value08, 0.0) + 
				ISNULL(fs.Value09, 0.0) + 
				ISNULL(fs.Value10, 0.0) + 
				ISNULL(fs.Value11, 0.0) + 
				ISNULL(fs.Value12, 0.0)
			)
		END AS Total 
FROM 
	PivoUnpivoHistory fs
	INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID
	INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID
	INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID
	INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID 
	INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = fs.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end
	INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID
	INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID
	INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID
	INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID
	INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID
WHERE 
	fs.TimeClassID IN (1, 2)
GO


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

-- fp.viewReportStaffingForEmployeeAndProvider_Unpivoted
CREATE VIEW [fp].[viewReportStaffingForEmployeeAndProvider_Unpivoted]
AS
	WITH Staffing AS (
		select * from [fp].[FactReportStaffing]
		union all
		select * from [fp].[FactReportStaffing_archive] 
	),
	StaffingHistory AS (
		select * from [fp].[FactReportStaffingHistory]
		union all
		select * from [fp].[FactReportStaffingHistory_archive]
	)
	
	-- Making sure final projection has all months included
	SELECT factReportStaffing_AllMonths.[BudgetConfigID], factReportStaffing_AllMonths.[EntityID],
		factReportStaffing_AllMonths.[DepartmentID], factReportStaffing_AllMonths.[JobCodeID],
		factReportStaffing_AllMonths.[PayCodeGroupID], factReportStaffing_AllMonths.[VariabilityID],
			factReportStaffing_AllMonths.[ProductiveClassID], factReportStaffing_AllMonths.[UnitTypeID],
			factReportStaffing_AllMonths.[TimeClassID], factReportStaffing_AllMonths.[FiscalMonthID],
			factReportStaffing_AllMonths.[FiscalYearID], factReportStaffing_AllMonths.[EmployeeID],
			factReportStaffing_AllMonths.[ProviderID],factReportStaffing_AllMonths.[ProviderLineItemID],			
			factReportStaffing_AllMonths.[ProviderTypeID],factReportStaffing_AllMonths.[ProviderSpecialtyID],
			COALESCE(frs.Value, factReportStaffing_AllMonths.Value) as Value
	FROM (
		SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],
			[ProductiveClassID], [UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID], [EmployeeID],
			[ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], 0 as Value
		FROM fp.viewReportStaffing_MonthsWithValues
		CROSS APPLY (
			select FiscalMonthID
			from [fw].[DimFiscalMonth]
			WHERE FiscalMonthID != 0
		) ca
		WHERE TimeClassID IN (1, 2, 12, 21, 22)
	) factReportStaffing_AllMonths 

	LEFT JOIN (select * from fp.viewReportStaffing_MonthsWithValues) frs
	ON factReportStaffing_AllMonths.BudgetConfigID = frs.BudgetConfigID
		and factReportStaffing_AllMonths.DepartmentID = frs.DepartmentID
		and factReportStaffing_AllMonths.FiscalYearID = frs.FiscalYearID
		and factReportStaffing_AllMonths.TimeClassID = frs.TimeClassID
		and factReportStaffing_AllMonths.VariabilityID = frs.VariabilityID
		and factReportStaffing_AllMonths.FiscalMonthID = frs.FiscalMonthID
		and factReportStaffing_AllMonths.JobCodeID = frs.JobCodeID
		and factReportStaffing_AllMonths.PayCodeGroupID = frs.PayCodeGroupID
		and factReportStaffing_AllMonths.UnitTypeID = frs.UnitTypeID
		and factReportStaffing_AllMonths.EmployeeID = frs.EmployeeID
		and factReportStaffing_AllMonths.ProviderID = frs.ProviderID
		and factReportStaffing_AllMonths.ProviderLineItemID = frs.ProviderLineItemID
		and factReportStaffing_AllMonths.ProviderTypeID = frs.ProviderTypeID
		and factReportStaffing_AllMonths.ProviderSpecialtyID = frs.ProviderSpecialtyID
GO


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

-- fp.viewReportStaffing_MonthsWithValues
CREATE VIEW [fp].[viewReportStaffing_MonthsWithValues] AS
	WITH Staffing AS (
		select * from [fp].[FactReportStaffing]
		union all
		select * from [fp].[FactReportStaffing_archive] 
	),
	StaffingHistory AS (
		select * from [fp].[FactReportStaffingHistory]
		union all
		select * from [fp].[FactReportStaffingHistory_archive]
	)
	-- Manager Budget
		SELECT 
			EntityID,
			DepartmentID,
			fs.BudgetConfigID,
			JobCodeID,
			PayCodeGroupID,
			bc.FiscalYearID,
			VariabilityID,
			TimeClassID,
			UnitTypeID, 
			FiscalMonthID,
			ProductiveClassID,
			EmployeeID,
			ProviderID,
		    ProviderLineItemID,
		    ProviderTypeID,
		    ProviderSpecialtyID,
			ManagerValue as Value
		FROM Staffing fs
			INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID
		WHERE 
			TimeClassID=2
		
		UNION ALL
		
		-- Initial Budget
		SELECT  
			EntityID,
			DepartmentID,
			fs.BudgetConfigID,
			JobCodeID,
			PayCodeGroupID,
			bc.FiscalYearID,
			VariabilityID,
			21 AS TimeClassID,
			UnitTypeID, 
			FiscalMonthID,
			ProductiveClassID,
			EmployeeID,
			ProviderID,
			ProviderLineItemID,
			ProviderTypeID,
			ProviderSpecialtyID,
			OriginalValue as Value
		FROM Staffing fs
			INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID
		WHERE 
			TimeClassID=2
		
		UNION ALL

		-- Baseline Budget
		SELECT  
			EntityID,
			DepartmentID,
			fs.BudgetConfigID,
			JobCodeID,
			PayCodeGroupID,
			bc.FiscalYearID,
			VariabilityID,
			22 AS TimeClassID,
			UnitTypeID, 
			FiscalMonthID,
			ProductiveClassID,
			EmployeeID,
			ProviderID,
			ProviderLineItemID,
			ProviderTypeID,
			ProviderSpecialtyID,
			Value
		FROM Staffing fs
			INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID
		WHERE 
			TimeClassID=2

		UNION ALL

		-- Manager Projection
		SELECT  
			EntityID,
			DepartmentID,
			fs.BudgetConfigID,
			JobCodeID,
			PayCodeGroupID,
			bc.FiscalYearID - 1 as FiscalYearID,
			VariabilityID,
			12 AS TimeClassID,
			UnitTypeID, 
			FiscalMonthID,
			ProductiveClassID,
			EmployeeID,
			ProviderID,
			ProviderLineItemID,
			ProviderTypeID,
			ProviderSpecialtyID,
			ManagerValue as Value
		FROM Staffing fs
			INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID
		WHERE 
			TimeClassID = 12 

		UNION ALL	
		
		-- Prior Year Actual and Current Year Budget
		SELECT  
			EntityID,
			fs.DepartmentID,
			fs.BudgetConfigID,
			fs.JobCodeID,
			fs.PayCodeGroupID,
			fs.FiscalYearID,
			fs.VariabilityID,
			fs.TimeClassID,
			fs.UnitTypeID,
			fs.FiscalMonthID,
			ProductiveClassID,
			EmployeeID,
			ProviderID,
			ProviderLineItemID,
			ProviderTypeID,
			ProviderSpecialtyID,
			fs.Value
		FROM StaffingHistory fs
			INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID 
		WHERE 
			fs.TimeClassID IN (1, 2)
GO


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

-- fp.viewReportStaffing_Unpivoted
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI   Description
 ** 1 	 2020-04-22  LR  	 D-09178	Including months with value zero on projection, so that reports wont have null values.
 ** 2	 2021-04-13  MW		 JAZZ-18056 Adding missing join on EmployeeID to fix overstated data
*************************************************************/
CREATE VIEW [fp].[viewReportStaffing_Unpivoted]
AS
	WITH Staffing AS (
		select * from [fp].[FactReportStaffing]
		union all
		select * from [fp].[FactReportStaffing_archive] 
	),
	StaffingHistory AS (
		select * from [fp].[FactReportStaffingHistory]
		union all
		select * from [fp].[FactReportStaffingHistory_archive]
	)
	
	-- Making sure final projection has all months included
	SELECT factReportStaffing_AllMonths.[BudgetConfigID], factReportStaffing_AllMonths.[EntityID],
		factReportStaffing_AllMonths.[DepartmentID], factReportStaffing_AllMonths.[JobCodeID],
		factReportStaffing_AllMonths.[PayCodeGroupID], factReportStaffing_AllMonths.[VariabilityID],
			factReportStaffing_AllMonths.[ProductiveClassID], factReportStaffing_AllMonths.[UnitTypeID],
			factReportStaffing_AllMonths.[TimeClassID], factReportStaffing_AllMonths.[FiscalMonthID],
			factReportStaffing_AllMonths.[FiscalYearID], factReportStaffing_AllMonths.[EmployeeID],
			COALESCE(frs.Value, factReportStaffing_AllMonths.Value) as Value
	FROM (
		SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],
			[ProductiveClassID], [UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID], [EmployeeID], 0 as Value
		FROM fp.viewReportStaffing_MonthsWithValues
		CROSS APPLY (
			select FiscalMonthID
			from [fw].[DimFiscalMonth]
			WHERE FiscalMonthID != 0
		) ca
		WHERE TimeClassID IN (1, 2, 12, 21, 22)
	) factReportStaffing_AllMonths 

	LEFT JOIN (select * from fp.viewReportStaffing_MonthsWithValues) frs
	ON factReportStaffing_AllMonths.BudgetConfigID = frs.BudgetConfigID
		and factReportStaffing_AllMonths.DepartmentID = frs.DepartmentID
		and factReportStaffing_AllMonths.FiscalYearID = frs.FiscalYearID
		and factReportStaffing_AllMonths.TimeClassID = frs.TimeClassID
		and factReportStaffing_AllMonths.VariabilityID = frs.VariabilityID
		and factReportStaffing_AllMonths.FiscalMonthID = frs.FiscalMonthID
		and factReportStaffing_AllMonths.JobCodeID = frs.JobCodeID
		and factReportStaffing_AllMonths.PayCodeGroupID = frs.PayCodeGroupID
		and factReportStaffing_AllMonths.UnitTypeID = frs.UnitTypeID
		and factReportStaffing_AllMonths.EmployeeID = frs.EmployeeID
GO


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

-- fp.viewReportStatistics
CREATE VIEW [fp].[viewReportStatistics]
AS 
WITH PivoUnpivo AS (
SELECT BudgetConfigID
	,EntityID
	,DepartmentID
	,AccountID
	,PatientClassID
	,PayorID
	,FinancialReportingID
	,UnitTypeID
	,TimeClassID
	,FiscalYearID
	,IsStat	
	,ProviderID
	,ProviderTypeID
	,ProviderSpecialtyID
	,ProviderLineItemID
	,ISNULL(MAX([01])   ,0.0) as OriginalValue01
	,ISNULL(MAX([02])   ,0.0) as OriginalValue02
	,ISNULL(MAX([03])   ,0.0) as OriginalValue03
	,ISNULL(MAX([04])   ,0.0) as OriginalValue04
	,ISNULL(MAX([05])   ,0.0) as OriginalValue05
	,ISNULL(MAX([06])   ,0.0) as OriginalValue06
	,ISNULL(MAX([07])   ,0.0) as OriginalValue07
	,ISNULL(MAX([08])   ,0.0) as OriginalValue08
	,ISNULL(MAX([09])   ,0.0) as OriginalValue09
	,ISNULL(MAX([10])   ,0.0) as OriginalValue10
	,ISNULL(MAX([11])   ,0.0) as OriginalValue11
	,ISNULL(MAX([12])   ,0.0) as OriginalValue12
	,ISNULL(MAX([01_2]) ,0.0) as Value01
	,ISNULL(MAX([02_2]) ,0.0) as Value02
	,ISNULL(MAX([03_2]) ,0.0) as Value03
	,ISNULL(MAX([04_2]) ,0.0) as Value04
	,ISNULL(MAX([05_2]) ,0.0) as Value05
	,ISNULL(MAX([06_2]) ,0.0) as Value06
	,ISNULL(MAX([07_2]) ,0.0) as Value07
	,ISNULL(MAX([08_2]) ,0.0) as Value08
	,ISNULL(MAX([09_2]) ,0.0) as Value09
	,ISNULL(MAX([10_2]) ,0.0) as Value10
	,ISNULL(MAX([11_2]) ,0.0) as Value11
	,ISNULL(MAX([12_2]) ,0.0) as Value12
	,ISNULL(MAX([01_3]) ,0.0) as ManagerValue01
	,ISNULL(MAX([02_3]) ,0.0) as ManagerValue02
	,ISNULL(MAX([03_3]) ,0.0) as ManagerValue03
	,ISNULL(MAX([04_3]) ,0.0) as ManagerValue04
	,ISNULL(MAX([05_3]) ,0.0) as ManagerValue05
	,ISNULL(MAX([06_3]) ,0.0) as ManagerValue06
	,ISNULL(MAX([07_3]) ,0.0) as ManagerValue07
	,ISNULL(MAX([08_3]) ,0.0) as ManagerValue08
	,ISNULL(MAX([09_3]) ,0.0) as ManagerValue09
	,ISNULL(MAX([10_3]) ,0.0) as ManagerValue10
	,ISNULL(MAX([11_3]) ,0.0) as ManagerValue11
	,ISNULL(MAX([12_3]) ,0.0) as ManagerValue12
FROM (
SELECT 
BudgetConfigID,
EntityID,
DepartmentID,
s.AccountID,
s.PatientClassID,
IsStat,
PayorID,
FinancialReportingID,
UnitTypeID,
TimeClassID,
FiscalYearID,
ProviderID,
ProviderTypeID,
ProviderSpecialtyID,
ProviderLineItemID,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID,
OriginalValue,
Value,
ManagerValue,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_2' as FiscalMonthID_2,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_3' as FiscalMonthID_3
FROM [fp].[FactReportStatistics] s 
INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID
inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID
UNION ALL
SELECT 
BudgetConfigID,
EntityID,
DepartmentID,
s.AccountID,
s.PatientClassID,
IsStat,
PayorID,
FinancialReportingID,
UnitTypeID,
TimeClassID,
FiscalYearID,
ProviderID,
ProviderTypeID,
ProviderSpecialtyID,
ProviderLineItemID,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID,
OriginalValue,
Value,
ManagerValue,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_2' as FiscalMonthID_2,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_3' as FiscalMonthID_3
FROM [fp].[FactReportStatistics_archive] s 
INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID
inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID
--WHERE BudgetConfigID = 4 and EntityID = 1 and DepartmentID = 12238 and JobCodeID = 706 and PayCodeGroupID = 1038 and VariabilityID = 1 and ProductiveClassID = 3 and UnitTypeID = 34 and TimeClassID = 2
) X
  PIVOT (MAX(OriginalValue)
      FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1
PIVOT (MAX(Value)
      FOR FiscalMonthID_2 IN ([01_2],[02_2],[03_2],[04_2],[05_2],[06_2],[07_2],[08_2],[09_2],[10_2],[11_2],[12_2])) AS Pivot2
PIVOT (MAX(ManagerValue)
      FOR FiscalMonthID_3 IN ([01_3],[02_3],[03_3],[04_3],[05_3],[06_3],[07_3],[08_3],[09_3],[10_3],[11_3],[12_3])) AS Pivot1
GROUP BY BudgetConfigID
	,EntityID
	,DepartmentID
	,AccountID
	,PatientClassID
	,PayorID
	,FinancialReportingID
	,UnitTypeID
	,TimeClassID
	,FiscalYearID
	,IsStat
	,ProviderID
	,ProviderTypeID
	,ProviderSpecialtyID
	,ProviderLineItemID
),
PivoUnpivoHistory AS (
SELECT BudgetConfigID
	,EntityID
	,DepartmentID
	,AccountID
	,PatientClassID
	,PayorID
	,FinancialReportingID
	,UnitTypeID
	,TimeClassID
	,FiscalYearID
	,IsStat
	,ProviderID
	,ProviderTypeID
	,ProviderSpecialtyID
	,ProviderLineItemID
	,ISNULL(MAX([01]),0.0) as Value01
	,ISNULL(MAX([02]),0.0) as Value02
	,ISNULL(MAX([03]),0.0) as Value03
	,ISNULL(MAX([04]),0.0) as Value04
	,ISNULL(MAX([05]),0.0) as Value05
	,ISNULL(MAX([06]),0.0) as Value06
	,ISNULL(MAX([07]),0.0) as Value07
	,ISNULL(MAX([08]),0.0) as Value08
	,ISNULL(MAX([09]),0.0) as Value09
	,ISNULL(MAX([10]),0.0) as Value10
	,ISNULL(MAX([11]),0.0) as Value11
	,ISNULL(MAX([12]),0.0) as Value12
FROM (
SELECT 
BudgetConfigID,
EntityID,
DepartmentID,
s.AccountID,
s.PatientClassID,
IsStat,
PayorID,
FinancialReportingID,
UnitTypeID,
TimeClassID,
FiscalYearID,
ProviderID,
ProviderTypeID,
ProviderSpecialtyID,
ProviderLineItemID,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID,
Value
FROM [fp].[FactReportStatisticsHistory] s 
INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID
inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID
UNION ALL
SELECT 
BudgetConfigID,
EntityID,
DepartmentID,
s.AccountID,
s.PatientClassID,
IsStat,
PayorID,
FinancialReportingID,
UnitTypeID,
TimeClassID,
FiscalYearID,
ProviderID,
ProviderTypeID,
ProviderSpecialtyID,
ProviderLineItemID,
RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID,
Value
FROM [fp].[FactReportStatisticsHistory_archive] s 
INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID
inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID
--WHERE BudgetConfigID = 4 and EntityID = 1 and DepartmentID = 12238 and JobCodeID = 706 and PayCodeGroupID = 1038 and VariabilityID = 1 and ProductiveClassID = 3 and UnitTypeID = 34 and TimeClassID = 2
) X
PIVOT (MAX(Value)
            FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1
GROUP BY BudgetConfigID
	,EntityID
	,DepartmentID
	,AccountID
	,PatientClassID
	,PayorID
	,FinancialReportingID
	,UnitTypeID
	,TimeClassID
	,FiscalYearID
	,IsStat
	,ProviderID
	,ProviderTypeID
	,ProviderSpecialtyID
	,ProviderLineItemID
)

SELECT
	bc.[BudgetConfigID],
	st.[DepartmentID],
	st.[AccountID],
	bc.[FiscalYearID]-1 as [FiscalYearID],
	[TimeClassID],
	ManagerValue01 as Month01,
	ManagerValue02 as Month02,
	ManagerValue03 as Month03,
	ManagerValue04 as Month04,
	ManagerValue05 as Month05,
	ManagerValue06 as Month06,
	ManagerValue07 as Month07,
	ManagerValue08 as Month08,
	ManagerValue09 as Month09,
	ManagerValue10 as Month10,
	ManagerValue11 as Month11,
	ManagerValue12 as Month12,
	IsStat,
	[UnitTypeID],
	[PatientClassID],
	[ProviderID],
	[ProviderTypeID],
	[ProviderSpecialtyID],
	[ProviderLineItemID],
	ManagerValue01+	ManagerValue02+	ManagerValue03+	ManagerValue04+	ManagerValue05+	ManagerValue06+	ManagerValue07+	ManagerValue08+	ManagerValue09+ManagerValue10+	ManagerValue11+	ManagerValue12 as Total,
	ManagerValue01+	ManagerValue02+	ManagerValue03+	ManagerValue04+	ManagerValue05+	ManagerValue06+	ManagerValue07+	ManagerValue08+	ManagerValue09+ManagerValue10+	ManagerValue11+	ManagerValue12 as YTD
from PivoUnpivo st
INNER JOIN [fp].[BudgetConfig] bc on st.BudgetConfigID = bc.BudgetConfigID
WHERE TimeClassID=12

union all
SELECT
	[BudgetConfigID],
	st.[DepartmentID],
	st.[AccountID],
	[FiscalYearID],
	21 as [TimeClassID],
	OriginalValue01 as Month01,
	OriginalValue02 as Month02,
	OriginalValue03 as Month03,
	OriginalValue04 as Month04,
	OriginalValue05 as Month05,
	OriginalValue06 as Month06,
	OriginalValue07 as Month07,
	OriginalValue08 as Month08,
	OriginalValue09 as Month09,
	OriginalValue10 as Month10,
	OriginalValue11 as Month11,
	OriginalValue12 as Month12,
	IsStat,
	[UnitTypeID],
	[PatientClassID],
	[ProviderID],
	[ProviderTypeID],
	[ProviderSpecialtyID],
	[ProviderLineItemID],
	(OriginalValue01+OriginalValue02+OriginalValue03+OriginalValue04+OriginalValue05+OriginalValue06+OriginalValue07+OriginalValue08+OriginalValue09+OriginalValue10+OriginalValue11+OriginalValue12) as Total,
	(OriginalValue01+OriginalValue02+OriginalValue03+OriginalValue04+OriginalValue05+OriginalValue06+OriginalValue07+OriginalValue08+OriginalValue09+OriginalValue10+OriginalValue11+OriginalValue12) AS YTD
from PivoUnpivo st
WHERE TimeClassID=2

union all
select
	[BudgetConfigID],
	st.[DepartmentID],
	st.[AccountID],
	[FiscalYearID],
	[TimeClassID],
	ManagerValue01 as  Month01,
	ManagerValue02 as  Month02,
	ManagerValue03 as  Month03,
	ManagerValue04 as  Month04,
	ManagerValue05 as  Month05,
	ManagerValue06 as  Month06,
	ManagerValue07 as  Month07,
	ManagerValue08 as  Month08,
	ManagerValue09 as  Month09,
	ManagerValue10 as  Month10,
	ManagerValue11 as  Month11,
	ManagerValue12 as  Month12,
	IsStat,
	[UnitTypeID],
	[PatientClassID],
	[ProviderID],
	[ProviderTypeID],
	[ProviderSpecialtyID],
	[ProviderLineItemID],
	(ManagerValue01+ManagerValue02 +ManagerValue03+ManagerValue04 +	ManagerValue05+ManagerValue06+ManagerValue07+ManagerValue08+ManagerValue09+ManagerValue10+ManagerValue11+ManagerValue12) as Total,
	(ManagerValue01+ManagerValue02 +ManagerValue03+ManagerValue04 +	ManagerValue05+ManagerValue06+ManagerValue07+ManagerValue08+ManagerValue09+ManagerValue10+ManagerValue11+ManagerValue12) as YTD
from PivoUnpivo st
WHERE TimeClassID=2

union all
select
	[BudgetConfigID],
	st.[DepartmentID],
	st.[AccountID],
	[FiscalYearID],
	18 as [TimeClassID],
	Value01 as Month01,
	Value02 as Month02,
	Value03 as Month03,
	Value04 as Month04,
	Value05 as Month05,
	Value06 as Month06,
	Value07 as Month07,
	Value08 as Month08,
	Value09 as Month09,
	Value10 as Month10,
	Value11 as Month11,
	Value12 as Month12,
	IsStat,
	[UnitTypeID],
	[PatientClassID],
	[ProviderID],
	[ProviderTypeID],
	[ProviderSpecialtyID],
	[ProviderLineItemID],
	(Value01+Value02+Value03+Value04+Value05+Value06+Value07+Value08+Value09+Value10+Value11+Value12) as Total,
	(Value01+Value02+Value03+Value04+Value05+Value06+Value07+Value08+Value09+Value10+Value11+Value12) AS YTD
	from PivoUnpivo st
WHERE TimeClassID=2

union all
select
	bc.[BudgetConfigID],
	st.[DepartmentID],
	st.[AccountID],
	st.FiscalYearID,
	[TimeClassID],
	Value01 as Month01,
	Value02 as Month02,
	Value03 as Month03,
	Value04 as Month04,
	Value05 as Month05,
	Value06 as Month06,
	Value07 as Month07,
	Value08 as Month08,
	Value09 as Month09,
	Value10 as Month10,
	Value11 as Month11,
	Value12 as Month12,
	IsStat,
	[UnitTypeID],
	[PatientClassID],
	[ProviderID],
	[ProviderTypeID],
	[ProviderSpecialtyID],
	[ProviderLineItemID],
	CASE 
		    WHEN (SELECT  clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11
			ELSE (Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11 + Value12) END
			AS Total,
	CASE 
		    WHEN (SELECT  clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11
			ELSE (Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11+ Value12) END
			AS YTD
from PivoUnpivoHistory st
INNER JOIN [fp].[BudgetConfig] bc on st.BudgetConfigID = bc.BudgetConfigID
WHERE TimeClassID=1

union all
select
	bc.[BudgetConfigID],
	st.[DepartmentID],
	st.[AccountID],
	bc.[FiscalYearID] - 1 as FiscalYearID,
	2 AS [TimeClassID],
	Value01 as Month01,
	Value02 as Month02,
	Value03 as Month03,
	Value04 as Month04,
	Value05 as Month05,
	Value06 as Month06,
	Value07 as Month07,
	Value08 as Month08,
	Value09 as Month09,
	Value10 as Month10,
	Value11 as Month11,
	Value12 as Month12,
	IsStat,
	[UnitTypeID],
	[PatientClassID],
	[ProviderID],
	[ProviderTypeID],
	[ProviderSpecialtyID],
	[ProviderLineItemID],
	CASE 
		    WHEN (SELECT  clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11
			ELSE (Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11+ Value12) END
			AS Total,
	CASE 
		    WHEN (SELECT  clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10
			WHEN (SELECT  clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11
			ELSE (Value01 + Value02 + Value03 +  Value04 + Value05 + Value06 + Value07 + Value08 + Value09 +  Value10 + Value11+ Value12) END
			AS YTD
from PivoUnpivoHistory st
INNER JOIN [fp].[BudgetConfig] bc on st.BudgetConfigID = bc.BudgetConfigID
WHERE TimeClassID=2
GO


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

-- fp.viewReportStatistics_AccountHistory
CREATE VIEW fp.viewReportStatistics_AccountHistory
AS

SELECT 
		fs.[BudgetConfigID],
		fs.[DepartmentID],
		fs.[AccountID],
		bc.[FiscalYearID] - 2 as FiscalYearID,
		1 AS [TimeClassID],
		fh.PriorYearActualValue01 as Month01,
		fh.PriorYearActualValue02 as Month02,
		fh.PriorYearActualValue03 as Month03,
		fh.PriorYearActualValue04 as Month04,
		fh.PriorYearActualValue05 as Month05,
		fh.PriorYearActualValue06 as Month06,
		fh.PriorYearActualValue07 as Month07,
		fh.PriorYearActualValue08 as Month08,
		fh.PriorYearActualValue09 as Month09,
		fh.PriorYearActualValue10 as Month10,
		fh.PriorYearActualValue11 as Month11,
		fh.PriorYearActualValue12 as Month12,
		acc.IsStat,
		fs.UnitTypeID,
		acc.PatientClassID,
		fh.PriorYearActualValueTotal AS Total,
		0 AS YTD,
		bc.FiscalYearID AS BudgetFiscalYearID
		FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsHistory] fh on fs.StatisticsID = fh.StatisticsID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID
			INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
 UNION
SELECT 
		fs.[BudgetConfigID],
		fs.[DepartmentID],
		fs.[AccountID],
		bc.[FiscalYearID] - 1 as FiscalYearID,
		1 AS [TimeClassID],
		fh.ActualYTDValue01 as Month01,
		fh.ActualYTDValue02 as Month02,
		fh.ActualYTDValue03 as Month03,
		fh.ActualYTDValue04 as Month04,
		fh.ActualYTDValue05 as Month05,
		fh.ActualYTDValue06 as Month06,
		fh.ActualYTDValue07 as Month07,
		fh.ActualYTDValue08 as Month08,
		fh.ActualYTDValue09 as Month09,
		fh.ActualYTDValue10 as Month10,
		fh.ActualYTDValue11 as Month11,
		fh.ActualYTDValue12 as Month12,
		acc.IsStat,
		fs.UnitTypeID,
		acc.PatientClassID,
		fh.ActualYTDValueTotal AS Total,
		0 AS YTD,
		bc.FiscalYearID AS BudgetFiscalYearID
		FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsHistory] fh on fs.StatisticsID = fh.StatisticsID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID
			INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID		
UNION
SELECT 
		fs.[BudgetConfigID],
		fs.[DepartmentID],
		fs.[AccountID],
		bc.[FiscalYearID] - 1 as FiscalYearID,
		2 AS [TimeClassID],
		fh.CurrentYearBudget01 as Month01,
		fh.CurrentYearBudget02 as Month02,
		fh.CurrentYearBudget03 as Month03,
		fh.CurrentYearBudget04 as Month04,
		fh.CurrentYearBudget05 as Month05,
		fh.CurrentYearBudget06 as Month06,
		fh.CurrentYearBudget07 as Month07,
		fh.CurrentYearBudget08 as Month08,
		fh.CurrentYearBudget09 as Month09,
		fh.CurrentYearBudget10 as Month10,
		fh.CurrentYearBudget11 as Month11,
		fh.CurrentYearBudget12 as Month12,
		acc.IsStat,
		fs.UnitTypeID,
		acc.PatientClassID,
		fh.CurrentYearBudgetTotal AS Total,
		0 AS YTD,
		bc.FiscalYearID AS BudgetFiscalYearID
		FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsHistory] fh on fs.StatisticsID = fh.StatisticsID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID
			INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewReportStatistics_BaselineBudget
CREATE VIEW fp.viewReportStatistics_BaselineBudget
AS

SELECT 
		fs.[BudgetConfigID],
		fs.[DepartmentID],
		fs.[AccountID],
		bc.[FiscalYearID],
		18 AS [TimeClassID],
		fp.AdjustedValue01 as Month01,
		fp.AdjustedValue02 as Month02,
		fp.AdjustedValue03 as Month03,
		fp.AdjustedValue04 as Month04,
		fp.AdjustedValue05 as Month05,
		fp.AdjustedValue06 as Month06,
		fp.AdjustedValue07 as Month07,
		fp.AdjustedValue08 as Month08,
		fp.AdjustedValue09 as Month09,
		fp.AdjustedValue10 as Month10,
		fp.AdjustedValue11 as Month11,
		fp.AdjustedValue12 as Month12,
		acc.IsStat,
		fs.UnitTypeID,
		acc.PatientClassID,
		fp.AdjustedValueTotal AS Total,
		0 AS YTD
		FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsBudget] fp on fs.StatisticsID = fp.StatisticsID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID
			INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
		WHERE BudgetPhaseID = 2
GO


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

-- fp.viewReportStatistics_Budget
CREATE VIEW fp.viewReportStatistics_Budget
AS


SELECT 
		fs.[BudgetConfigID],
		fs.[DepartmentID],
		fs.[AccountID],
		bc.[FiscalYearID],
		2 AS [TimeClassID],
		fp.AdjustedValue01 as Month01,
		fp.AdjustedValue02 as Month02,
		fp.AdjustedValue03 as Month03,
		fp.AdjustedValue04 as Month04,
		fp.AdjustedValue05 as Month05,
		fp.AdjustedValue06 as Month06,
		fp.AdjustedValue07 as Month07,
		fp.AdjustedValue08 as Month08,
		fp.AdjustedValue09 as Month09,
		fp.AdjustedValue10 as Month10,
		fp.AdjustedValue11 as Month11,
		fp.AdjustedValue12 as Month12,
		acc.IsStat,
		fs.UnitTypeID,
		acc.PatientClassID,
		fp.AdjustedValueTotal AS Total,
		0 AS YTD
		FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsBudget] fp on fs.StatisticsID = fp.StatisticsID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID
			INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
		WHERE BudgetPhaseID = 3
GO


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

-- fp.viewReportStatistics_InitialBudget
CREATE VIEW fp.viewReportStatistics_InitialBudget
AS

SELECT 
		fs.[BudgetConfigID],
		fs.[DepartmentID],
		fs.[AccountID],
		bc.[FiscalYearID],
		21 AS [TimeClassID],
		fs.InitialBudget01 as Month01,
		fs.InitialBudget02 as Month02,
		fs.InitialBudget03 as Month03,
		fs.InitialBudget04 as Month04,
		fs.InitialBudget05 as Month05,
		fs.InitialBudget06 as Month06,
		fs.InitialBudget07 as Month07,
		fs.InitialBudget08 as Month08,
		fs.InitialBudget09 as Month09,
		fs.InitialBudget10 as Month10,
		fs.InitialBudget11 as Month11,
		fs.InitialBudget12 as Month12,
		acc.IsStat,
		fs.UnitTypeID,
		acc.PatientClassID,
		fs.InitialBudgetTotal AS Total,
		0 AS YTD
		FROM [fp].[FactStatistics] fs 
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID
			INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
GO


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

-- fp.viewReportStatistics_MonthsWithValues
CREATE   VIEW [fp].[viewReportStatistics_MonthsWithValues] AS  
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2024-03-25   MZ      JAZZ-68120		Removed join on [fw].[DimAccount]
 *************************************************************/ 
 WITH Stat AS (  
  select * from [fp].[FactReportStatistics]  
  union all  
  select * from [fp].[FactReportStatistics_archive]  
 ),  
 StatHistory AS (  
  select * from [fp].[FactReportStatisticsHistory]  
  union all  
  select * from [fp].[FactReportStatisticsHistory_archive]  
 )  
   
  -- Manager Projection  
  SELECT  
   bc.BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   bc.FiscalYearID-1 as FiscalYearID,  
   TimeClassID,  
   ManagerValue as Value,  
   UnitTypeID,  
   st.PayorID,  
   st.FinancialReportingID,  
   st.PatientClassID,  
   FiscalMonthID,
   st.ProviderID,
   st.ProviderLineItemID,
   st.ProviderSpecialtyID,
   st.ProviderTypeID
  from Stat st  
  INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID  
  WHERE TimeClassID=12  
  
  union all  
  
  -- Initial Budget  
  SELECT  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   FiscalYearID,  
   21 as TimeClassID,  
   OriginalValue as Value,  
   UnitTypeID,  
   st.PayorID,  
   st.FinancialReportingID,  
   st.PatientClassID,  
   FiscalMonthID,
   st.ProviderID,
   st.ProviderLineItemID,
   st.ProviderSpecialtyID,
   st.ProviderTypeID  
  from Stat st  
  WHERE TimeClassID=2  
  
  union all  
  
  -- Manager Budget  
  select  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   FiscalYearID,  
   TimeClassID,  
   ManagerValue as Value,  
   UnitTypeID,  
   st.PayorID,  
   st.FinancialReportingID,  
   st.PatientClassID,  
   FiscalMonthID,
   st.ProviderID,
   st.ProviderLineItemID,
   st.ProviderSpecialtyID,
   st.ProviderTypeID  
  from Stat st  
  WHERE TimeClassID=2  
  
  union all  
  
  -- Baseline Budget  
  select  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   FiscalYearID,  
   22 as TimeClassID,  
   Value,  
   UnitTypeID,  
   st.PayorID,  
   st.FinancialReportingID,  
   st.PatientClassID,  
   FiscalMonthID,
   st.ProviderID,
   st.ProviderLineItemID,
   st.ProviderSpecialtyID,
   st.ProviderTypeID  
  from Stat st  
  WHERE TimeClassID=2  
  
  union all  
  
  -- Prior Year Actual and Current Year Budget  
  select  
   BudgetConfigID,  
   st.EntityID,  
   st.DepartmentID,  
   st.AccountID,  
   st.FiscalYearID,  
   TimeClassID,  
   Value,  
   UnitTypeID,  
   st.PayorID,  
   st.FinancialReportingID,  
   st.PatientClassID,  
   FiscalMonthID,
   st.ProviderID,
   st.ProviderLineItemID,
   st.ProviderSpecialtyID,
   st.ProviderTypeID  
  from StatHistory st  
  WHERE TimeClassID in(1, 2)
GO


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

-- fp.viewReportStatistics_Projection
CREATE VIEW fp.viewReportStatistics_Projection
AS

SELECT 
		fs.[BudgetConfigID],
		fs.[DepartmentID],
		fs.[AccountID],
		bc.[FiscalYearID] - 1 AS FiscalYearID,
		12 AS [TimeClassID],
		fp.AdjustedValue01 as Month01,
		fp.AdjustedValue02 as Month02,
		fp.AdjustedValue03 as Month03,
		fp.AdjustedValue04 as Month04,
		fp.AdjustedValue05 as Month05,
		fp.AdjustedValue06 as Month06,
		fp.AdjustedValue07 as Month07,
		fp.AdjustedValue08 as Month08,
		fp.AdjustedValue09 as Month09,
		fp.AdjustedValue10 as Month10,
		fp.AdjustedValue11 as Month11,
		fp.AdjustedValue12 as Month12,
		acc.IsStat,
		fs.UnitTypeID,
		acc.PatientClassID,
		fp.AdjustedValueTotal AS Total,
		0 AS YTD
		FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsProjection] fp on fs.StatisticsID = fp.StatisticsID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID
			INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
		WHERE BudgetPhaseID = 3
GO


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

-- fp.viewReportStatistics_Unpivoted
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI          Description  
 ** 1   2020-04-22   LR      D-09178     Including months with value zero on projection, so that reports wont have null values.  
 ** 2   2021-05-07   MD      JAZZ-15686  Adding Provider fields 
 ** 2   2021-07-20   MD      JAZZ-23237  Adding union alls for data transfer tables
*************************************************************/  
CREATE VIEW [fp].[viewReportStatistics_Unpivoted]  
AS   
 WITH Stat AS (  
  select * from [fp].[FactReportStatistics]  
  union all  
  select * from [fp].[FactReportStatistics_archive]  
 ),  
 StatHistory AS (  
  select * from [fp].[FactReportStatisticsHistory]  
  union all  
  select * from [fp].[FactReportStatisticsHistory_archive]  
 ),  
 StatDataTransfer AS (  
  select * from [fp].[FactReportStatisticsDataTransfer]  
 ),  
 StatHistoryDataTransfer AS (  
  select * from [fp].[FactReportStatisticsHistoryDataTransfer]   
 )  
   
 -- Making sure final projection has all months included  
 SELECT factReportStatistics_AllMonths.[BudgetConfigID], factReportStatistics_AllMonths.[EntityID],  
  factReportStatistics_AllMonths.[DepartmentID], factReportStatistics_AllMonths.[AccountID],  
  factReportStatistics_AllMonths.[PatientClassID], factReportStatistics_AllMonths.[PayorID],  
   factReportStatistics_AllMonths.[FinancialReportingID], factReportStatistics_AllMonths.[UnitTypeID],  
   factReportStatistics_AllMonths.[TimeClassID], factReportStatistics_AllMonths.[FiscalMonthID],  
   factReportStatistics_AllMonths.[FiscalYearID], factReportStatistics_AllMonths.[ProviderID],
   factReportStatistics_AllMonths.[ProviderTypeID], factReportStatistics_AllMonths.[ProviderSpecialtyID],
   factReportStatistics_AllMonths.[ProviderLineItemID],
   COALESCE(frs.Value, factReportStatistics_AllMonths.Value) as Value  
 FROM (  
  SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [PatientClassID], [PayorID],  
   [FinancialReportingID], [UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID],
   [ProviderID], [ProviderTypeID], [ProviderSpecialtyID], [ProviderLineItemID],
   0 as Value, 0 as OriginalValue, 0 as ManagerValue  
  FROM fp.viewReportStatistics_MonthsWithValues  
  CROSS APPLY (  
   select FiscalMonthID  
   from [fw].[DimFiscalMonth]  
   WHERE FiscalMonthID != 0  
   ) ca  
  WHERE TimeClassID IN (1, 2, 12, 21, 22)  
 ) factReportStatistics_AllMonths   
  
 LEFT JOIN (select * from fp.viewReportStatistics_MonthsWithValues) frs  
 ON factReportStatistics_AllMonths.BudgetConfigID = frs.BudgetConfigID  
  and factReportStatistics_AllMonths.DepartmentID = frs.DepartmentID  
  and factReportStatistics_AllMonths.AccountID = frs.AccountID  
  and factReportStatistics_AllMonths.FiscalYearID = frs.FiscalYearID  
  and factReportStatistics_AllMonths.TimeClassID = frs.TimeClassID  
  and factReportStatistics_AllMonths.FiscalMonthID = frs.FiscalMonthID  
  and factReportStatistics_AllMonths.PatientClassID = frs.PatientClassID  
  and factReportStatistics_AllMonths.UnitTypeID = frs.UnitTypeID
  and factReportStatistics_AllMonths.ProviderID = frs.ProviderID
  and factReportStatistics_AllMonths.ProviderTypeID = frs.ProviderTypeID
  and factReportStatistics_AllMonths.ProviderSpecialtyID = frs.ProviderSpecialtyID
  and factReportStatistics_AllMonths.ProviderLineItemID = frs.ProviderLineItemID

  UNION ALL

  SELECT 
	sdt.BudgetConfigID,
	sdt.EntityID,
	sdt.DepartmentID,
	sdt.AccountID,
	sdt.PatientClassID,
	sdt.PayorID,
	FinancialReportingID,
	sdt.UnitTypeID,
	sdt.TimeClassID,
	sdt.FiscalMonthID,
	sdt.FiscalYearID,
	0 as ProviderID,
	0 as ProviderTypeID,
	0 as ProviderSpecialityID,
	0 as ProviderLineItemID,
	--OriginalValue, 
	sdt.Value
	--ManagerValue
  FROM StatDataTransfer sdt

    UNION ALL

  SELECT 
	shdt.BudgetConfigID,
	shdt.EntityID,
	shdt.DepartmentID,
	shdt.AccountID,
	shdt.PatientClassID,
	shdt.PayorID,
	FinancialReportingID,
	shdt.UnitTypeID,
	shdt.TimeClassID,
	shdt.FiscalMonthID,
	shdt.FiscalYearID,
	0 as ProviderID,
	0 as ProviderTypeID,
	0 as ProviderSpecialityID,
	0 as ProviderLineItemID,
	--OriginalValue, 
	shdt.Value
	--ManagerValue
  FROM StatHistoryDataTransfer shdt
GO


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

-- fp.viewRevenueAccounts
CREATE VIEW [fp].[viewRevenueAccounts]
AS
	SELECT acc.*
	FROM [fw].[DimAccount] acc
	INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID
	WHERE aph.Name IN ('Gross Charges - Clinic','Gross Charges - ED','Gross Charges - Inpatient','Gross Charges - Observation','Gross Charges - Other','Gross Charges - Outpatient')
GO


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

-- fp.viewRevenueExpenseFlexingConfig
CREATE VIEW [fp].[viewRevenueExpenseFlexingConfig]
AS
SELECT 
	b.EntityGroupConfigGUID,
	b.DepartmentID,
	b.AccountID,
	CASE WHEN b.FlexMethodID = 6 THEN 6
		ELSE COALESCE(ovr.FlexMethodID, b.FlexMethodID) END AS FlexMethodID
FROM (
	SELECT 
		fc.EntityGroupConfigGUID,
		fc.DepartmentID,
		acct.AccountID,
		fc.FlexMethodID
	FROM [fp].[RevenueExpenseFlexingConfig] fc
	CROSS APPLY (SELECT AccountID FROM [fp].[viewRevenueAccounts]) acct
) b
LEFT JOIN [fp].[RevenueFlexingOverrideConfig] ovr
		ON b.DepartmentID = ovr.DepartmentID
		AND b.AccountID = ovr.AccountID
		AND b.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
GO


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

-- fp.viewRosterBudgetBasisResult
CREATE   VIEW [fp].[viewRosterBudgetBasisResult]
/****************************************************************************************************
** Author: srk
** Create Date: 2017.01.25
** Description: Reporting view for the 'OB Roster Budgeting Data' data source
** Last Modified: 2018.02.09
** GM Release: 2017.1.3
****************************************************************************************************
** Change History
****************************************************************************************************
** CID	Date		Author		WI			Description
** 	1	2017.04.17	srk			D-05867		Making sure view pulls in newly added employees
**	2	2017.05.16 	srk			D-05867		Pulling in start month for new employees
**  3   2017.11.16  my          B-17923		Replacing Codes with IDs and removing new employees because new employees are now in the employee dim
**  4	2018.02.09	srk			B-18879		Adding position number, fiscalyearid and comment to view
**  5	2023.03.24	MY			JAZZ-51675	Add IsActive so it only pulls active config
****************************************************************************************************/
AS 
	SELECT 
		DB.DepartmentalBudgetID,
		DB.DepartmentCode,
		ISNULL(BR.EmployeeID,0) as EmployeeID,
		coalesce(DE.Code, 'Not Specified') as EmployeeCode,
		DE.Number,
		Coalesce(NE.PositionNumber, 'Not Specified') as PositionNumber,
		ISNULL(BR.JobCodeID,0) as JobCodeID,
		DE.JobCode,
		BR.PayCodeGroupID,
		PCG.PayCodeGroupCode,
		coalesce(NE.FiscalYearID,0) as NewEmployeeStartYear,
		coalesce(NE.FiscalMonthID,0) as NewEmployeeStartMonth,
		coalesce(NE.Comment, 'Not Specified') as NewEmployeeComments,
		BR.InitialDollars,
		BR.ProjectedDollars,
		BR.Dollars,
		BR.ProjectedFTEs,
		BR.FTEs,
		BR.Comment
	FROM [fp].[RosterBudgetBasisResult] BR
		INNER JOIN fp.BudgetConfig bc ON BR.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN [fw].[DimEmployee] DE ON BR.EmployeeID = DE.EmployeeID
		INNER JOIN [ob].[DimDepartmentalBudget] DB ON BR.DepartmentID = DB.DepartmentID
		INNER JOIN [fw].[DimPayCodeGroup] PCG ON BR.PayCodeGroupID = PCG.PayCodeGroupID
		LEFT JOIN [fp].[RosterBudgetNewEmployee] NE on DE.EmployeeID = NE.EmployeeID
	WHERE bc.IsActive = 1
GO


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

-- fp.viewRosterBudgetRequest
CREATE VIEW [fp].[viewRosterBudgetRequest]
/****************************************************************************************************
** Author: srk
** Create Date: 2018.02.09
** Description: Reporting view for the 'OB Roster Budgeting Approval Requests' data source
** Last Modified: 2018.02.09
** GM Release: 2018.2.1
****************************************************************************************************
** Change History
****************************************************************************************************
** CID	Date		Author		WI		Description
** 	
****************************************************************************************************/
AS 

SELECT 
	BC.BudgetConfigID,
	RBR.UserGuid,
	CASE 
		WHEN RBR.STATUS = 0 THEN 'Pending Approval'
		WHEN RBR.STATUS = 1 THEN 'Approved'
		WHEN RBR.STATUS = 2 THEN 'Denied' END AS Status,
	RBR.Comment,
	RBR.JobCodeID,
	RBR.PayCodeGroupID,
	RBR.DepartmentID,
	RBR.EmployeeID,
	COALESCE(NE.PositionNumber, 'Not Specified') as PositionNumber,
	RBR.dollartype as DollarType,
	RBR.Dollars
FROM [fp].[RosterBudgetRequest] RBR
	INNER JOIN [fp].[BudgetConfig] BC on RBR.BudgetConfigGUID = BC.BudgetConfigGUID
	LEFT JOIN [fp].[RosterBudgetNewEmployee] NE on RBR.EmployeeID = NE.EmployeeID
GO


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

-- fp.viewRosterBudgetToStaffingPC
CREATE view [fp].[viewRosterBudgetToStaffingPC]
/****************************************************************************************************
** Author: cbb
** Create Date: 2016.10.11
** Description: roster budget data formatted for insertion into department budget models
** Last Modified: 2017.02.06
** GM Release: 2017.1.0
****************************************************************************************************
** Change History
****************************************************************************************************
** CID	Date		Author	WI		Description
** 1	2017.02.06	cbb		d05500	filter out inactive plans
****************************************************************************************************/
as

select
	[DepartmentalBudgetID] 	= ob.[DepartmentalBudgetID],
	[PayCodeGroupID]		= pcg.[PayCodeGroupID],
	[PayCodeID]				= 0,
	[JobCodeID]				= jc.[JobCodeID],
	[EmployeeID]			= 0,
	[FiscalYearID]			= case
									when app.MeasureName like 'Projected%'
										then (bc.[FiscalYearID]-1)
									else bc.[FiscalYearID]
								end,
	[TimeClassID]			= case
									when app.MeasureName like 'Projected%'
										then 12
									else 2
								end,
	[UnitTypeID]			= case
									when app.MeasureName like '%FTEs' 
										then 
											case pcg.ProductiveClassID
												when 2 then 146	-- Non-Productive
												when 3 then 148	-- Productive
												when 5 then 147	-- Differential
												when 6 then 52	-- Productive Non-FTE
												else 51
											end
									else 34
								end,
	[DataTypeID]			= 3,
	[Month01]				= app.Amount * whpm.Month01 * 
								case when rem.StartMonthID > 1 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month02]				= app.Amount * whpm.Month02 * 
								case when rem.StartMonthID > 2 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month03]				= app.Amount * whpm.Month03 * 
								case when rem.StartMonthID > 3 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month04]				= app.Amount * whpm.Month04 * 
								case when rem.StartMonthID > 4 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month05]				= app.Amount * whpm.Month05 * 
								case when rem.StartMonthID > 5 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month06]				= app.Amount * whpm.Month06 * 
								case when rem.StartMonthID > 6 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month07]				= app.Amount * whpm.Month07 * 
								case when rem.StartMonthID > 7 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month08]				= app.Amount * whpm.Month08 * 
								case when rem.StartMonthID > 8 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month09]				= app.Amount * whpm.Month09 * 
								case when rem.StartMonthID > 9 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month10]				= app.Amount * whpm.Month10 * 
								case when rem.StartMonthID > 10 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month11]				= app.Amount * whpm.Month11 * 
								case when rem.StartMonthID > 11 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end,
	[Month12]				= app.Amount * whpm.Month12 * 
								case when rem.StartMonthID > 12 then 0
									else 
										case 
											when app.MeasureName like '%FTEs' 
												then 1
											else 1/rem.RemainingHours
										end
								end
FROM [fp].[RosterBudgetBasisResult] data
	cross apply
		(
			values
				('Dollars', data.Dollars),
				('FTEs', data.FTEs),
				('ProjectedDollars', data.ProjectedDollars),
				('ProjectedFTEs', data.ProjectedFTEs)
		) app (MeasureName, Amount)
	inner join [fp].[BudgetConfig] bc
		on bc.BudgetConfigGUID=data.BudgetConfigGUID
	inner join [fw].[DimDepartment] md
		on md.DepartmentID=data.DepartmentID
	inner join [fw].[DimJobCode] jc
		on jc.JobCodeID=data.JobCodeID
	inner join [ob].[DimDepartmentalBudget] ob
		on ob.DepartmentID=md.DepartmentID
	inner join [fw].[DimPayCodeGroup] pcg
		on pcg.PayCodeGroupID=data.PayCodeGroupID
	inner join [client].[FactWorkingHoursPerMonth] whpm 
		on case 
				when jc.WorkWeekOverrideID=-1 
					then ob.EntityDefaultWorkWeekID 
				else 
					jc.WorkWeekOverrideID 
			end = whpm.WorkWeekID 
		and case
				when app.MeasureName like 'Projected%'
					then (bc.[FiscalYearID]-1)
				else bc.[FiscalYearID]
			end = whpm.FiscalYearID
	left join [fp].[RosterBudgetNewEmployee] new
		on data.BudgetConfigGUID = new.BudgetConfigGUID
		and data.EmployeeID = new.EmployeeID
	cross apply
		(
			select 
				StartMonthID	=	case
										when app.MeasureName like 'Projected%'
											then case when new.FiscalMonthID <= ob.MonthsLoaded then (ob.MonthsLoaded+1) else new.FiscalMonthID end
										else 1
									end,
				RemainingHours	=	case
										when app.MeasureName like 'Projected%'
											then 
												case coalesce(new.FiscalMonthID, 1)
													when 1 then  wh.MonthYearly
													when 2 then  wh.Month02 + wh.Month03 + wh.Month04 + wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 3 then  wh.Month03 + wh.Month04 + wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 4 then  wh.Month04 + wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 5 then  wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 6 then  wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 7 then  wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 8 then  wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 9 then  wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12
													when 10 then  wh.Month10 + wh.Month11 + wh.Month12
													when 11 then  wh.Month11 + wh.Month12
													when 12 then  wh.Month12
													else wh.MonthYearly
												end
										else wh.MonthYearly
									end
			from [client].[FactWorkingHoursPerMonth] wh
			where wh.WorkWeekID = whpm.WorkWeekID
				and wh.FiscalYearID = whpm.FiscalYearID
		) rem
where 1=1
	and bc.IsActive=1
-- CID 1 begin
	and ob.OBActivePlans=1
-- CID 2 end
	and 
		(
			(
				bc.IsProjectionHidden = 1
				and app.MeasureName not like 'Projected%'
			)
			or
			bc.IsProjectionHidden = 0
		)
GO


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

-- fp.viewServiceLineAdjustmentImport
CREATE VIEW fp.viewServiceLineAdjustmentImport
AS 

SELECT [RowID]
      ,[AdjustmentGUID]
      ,[EntityID]
      ,[PatientClassID]
      ,[ServiceLineID]
      ,[ServiceLineRollupID]
      ,[AgeCohortID]
      ,[MedicalSurgicalID]
      ,[DepartmentID]
      ,[PayorID]
      ,[PayorGroupID]
      ,[MSDRGID]
      ,[CPTID]
      ,[ProviderID]
      ,[PhysicianSpecialtyID]
      ,[FiscalYearID]
      ,[FiscalMonthID]
      ,[UnitTypeID]
      ,[Value]
      ,[Version]
      ,[TimeClassID]
      ,[BudgetPhaseID]
      ,[IsRecordDeleted]
      ,[AdjustmentID]
  FROM [fp].[ServiceLineEncounterAdjustmentImport]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewServiceLineChargeVolume_aggregate
CREATE   VIEW fp.viewServiceLineChargeVolume_aggregate
as
	SELECT
		sl.EntityID,
		dv.DepartmentID,
		dv.ChargeCodeID,
		--dv.ServiceLineID,
		bc.FiscalYearID,
		bc.BudgetConfigID,
		SUM(sl.TargetAdjusted01 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month01],
		SUM(sl.TargetAdjusted02 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month02],
		SUM(sl.TargetAdjusted03 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month03],
		SUM(sl.TargetAdjusted04 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month04],
		SUM(sl.TargetAdjusted05 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month05],
		SUM(sl.TargetAdjusted06 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month06],
		SUM(sl.TargetAdjusted07 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month07],
		SUM(sl.TargetAdjusted08 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month08],
		SUM(sl.TargetAdjusted09 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month09],
		SUM(sl.TargetAdjusted10 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month10],
		SUM(sl.TargetAdjusted11 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month11],
		SUM(sl.TargetAdjusted12 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month12]
	FROM
		[fp].[ChargeVolume] dv
		INNER JOIN [fw].[DimDepartment] dept on dv.DepartmentID = dept.DepartmentID
		INNER JOIN [fp].[ServiceLineEncounter] sl
			ON dv.BudgetConfigID = sl.BudgetConfigID
			AND dv.ServiceLineID = sl.ServiceLineID
			AND dv.AgeCohortID = sl.AgeCohortID
			AND dv.MedicalSurgicalID = sl.MedicalSurgicalID
			AND dv.PatientClassID = sl.PatientClassID
			AND dept.EntityID = sl.EntityID	
		INNER JOIN [fp].[BudgetConfig] bc
		ON dv.BudgetConfigID = bc.BudgetConfigID
	GROUP BY
		sl.EntityID,
		dv.DepartmentID,
		dv.ChargeCodeID,
		--dv.ServiceLineID,
		bc.FiscalYearID,
		bc.BudgetConfigID
GO


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

-- fp.viewServiceLineEncounterAdjustment
CREATE VIEW fp.viewServiceLineEncounterAdjustment
AS 

SELECT [AdjustmentGUID]
      ,[BudgetConfigGUID]
      ,[AdjustmentType]
      ,[Value]
      ,[AdjustmentFilterJSON]
      ,[GroupingHierarchyJSON]
      ,[AdjustedProperty]
      ,[Comment]
      ,[AuthorGUID]
      ,[AuthorFullName]
      ,[LastModifiedDateUtc]
      ,[DateCreatedUtc]
      ,[GroupingGUID]
      ,[TimeClassID]
      ,[BudgetPhaseID]
      ,[ClassificationGroupID]
      ,[ClassificationCategoryID]
      ,[IsRecordDeleted]
      ,[DimensionMemberJson]
      ,[AdjustmentID]
	  ,[IsErrored]
  FROM [fp].[ServiceLineEncounterAdjustment]
  WHERE IsRecordDeleted = 0;
GO


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

-- fp.viewServiceLineEncounterAdjustmentImport_Pivoted
CREATE   VIEW fp.viewServiceLineEncounterAdjustmentImport_Pivoted
AS
SELECT 
	AdjustmentGUID,
	DepartmentID,
	EntityID,
	PatientClassID,
	ServiceLineID,
	ServiceLineRollupID,
	AgeCohortID,
	MedicalSurgicalID,
	PayorID,
	PayorGroupID,
	MSDRGID,
	CPTID,
	ProviderID,
	PhysicianSpecialtyID,
	UnitTypeID,
	TimeClassID,
	BudgetPhaseID,
	IsRecordDeleted,
	AdjustmentID,
	[Month01],
	[Month02],
	[Month03],
	[Month04],
	[Month05],
	[Month06],
	[Month07],
	[Month08],
	[Month09],
	[Month10],
	[Month11],
	[Month12]
FROM
	(
		SELECT
			AdjustmentGUID,
			DepartmentID,
			EntityID,
			PatientClassID,
			ServiceLineID,
			ServiceLineRollupID,
			AgeCohortID,
			MedicalSurgicalID,
			PayorID,
			PayorGroupID,
			MSDRGID,
			CPTID,
			ProviderID,
			PhysicianSpecialtyID,
			UnitTypeID,
			TimeClassID,
			BudgetPhaseID,
			IsRecordDeleted,
			AdjustmentID,
			m.MonthColumnName,
			Value
		FROM fp.ServiceLineEncounterAdjustmentImport imp
			INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = imp.FiscalMonthID
	) data
	PIVOT (SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pvt
WHERE IsRecordDeleted = 0
GO


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

-- fp.viewServiceLineEncounterChangeHistoryWithRollUpDetail
CREATE VIEW fp.viewServiceLineEncounterChangeHistoryWithRollUpDetail
AS
	SELECT slech.RowID, slech.ServiceLineEncounterID, slech.AdjustmentGUID, slech.GroupingGUID, slech.AdjustmentType, slech.FiscalMonthID, slech.UnitTypeID, slech.TimeClassID, slech.BudgetPhaseID, slech.OldValue, slech.NewValue, slech.BudgetConfigID, slech.DateCreatedUTC, slea.DateCreatedUTC AS AdjustmentDateCreatedUTC, 
		slea.GroupingGUID AS AdjustmentGroupingGUID, CASE WHEN slea.AdjustmentType IN (0, 2, 3) AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' THEN slea2.AdjustmentGUID ELSE slea.AdjustmentGUID END ReportingAdjustmentGUID
	FROM fp.ServiceLineEncounterChangeHistory slech
		INNER JOIN fp.ServiceLineEncounterAdjustment slea ON slech.AdjustmentGUID = slea.AdjustmentGUID
		LEFT JOIN fp.ServiceLineEncounterAdjustment slea2 ON slea.GroupingGUID = slea2.GroupingGUID AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' AND slea2.AdjustmentType IN (12, 13, 14)
GO


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

-- fp.viewServiceLineEncounterChangeHistory_Pivoted
CREATE VIEW  fp.viewServiceLineEncounterChangeHistory_Pivoted  
 AS
WITH months AS 
(
	SELECT 
		FiscalMonthID, 
		REPLACE(MonthColumnName, 'Month', 'OldValue') AS OldMonthColumnName, 
		REPLACE(MonthColumnName, 'Month', 'NewValue') AS NewMonthColumnName 
	FROM fw.DimFiscalMonth
)
SELECT 
	ServiceLineEncounterID, 
	AdjustmentGUID, 
	UnitTypeID,
	TimeClassID ,
	BudgetPhaseID ,
	BudgetConfigID ,
	AdjustmentType ,
	SUM(pvt2.OldValue01) AS OldValue01,
	SUM(pvt2.OldValue02) AS OldValue02,
	SUM(pvt2.OldValue03) AS OldValue03,
	SUM(pvt2.OldValue04) AS OldValue04,
	SUM(pvt2.OldValue05) AS OldValue05,
	SUM(pvt2.OldValue06) AS OldValue06,
	SUM(pvt2.OldValue07) AS OldValue07,
	SUM(pvt2.OldValue08) AS OldValue08,
	SUM(pvt2.OldValue09) AS OldValue09,
	SUM(pvt2.OldValue10) AS OldValue10,
	SUM(pvt2.OldValue11) AS OldValue11,
	SUM(pvt2.OldValue12) AS OldValue12,	
	SUM(pvt2.NewValue01) AS NewValue01,	
	SUM(pvt2.NewValue02) AS NewValue02,	
	SUM(pvt2.NewValue03) AS NewValue03,	
	SUM(pvt2.NewValue04) AS NewValue04,	
	SUM(pvt2.NewValue05) AS NewValue05,	
	SUM(pvt2.NewValue06) AS NewValue06,	
	SUM(pvt2.NewValue07) AS NewValue07,	
	SUM(pvt2.NewValue08) AS NewValue08,	
	SUM(pvt2.NewValue09) AS NewValue09,	
	SUM(pvt2.NewValue10) AS NewValue10,	
	SUM(pvt2.NewValue11) AS NewValue11,	
	SUM(pvt2.NewValue12) AS NewValue12
FROM 
	(
		SELECT 
			ServiceLineEncounterID,
			AdjustmentGUID,
			AdjustmentType,
			UnitTypeID,
			TimeClassID ,
			BudgetPhaseID ,
			BudgetConfigID ,
			m.OldMonthColumnName,
			m.NewMonthColumnName,
			OldValue, 
			NewValue 
		FROM fp.ServiceLineEncounterChangeHistory ch
			INNER JOIN months m ON m.FiscalMonthID = ch.FiscalMonthID
	) data
	PIVOT (SUM(OldValue) for OldMonthColumnName in ([OldValue01],[OldValue02],[OldValue03],[OldValue04],[OldValue05],[OldValue06],[OldValue07],[OldValue08],[OldValue09],[OldValue10],[OldValue11],[OldValue12])) as pvt
	PIVOT (SUM(NewValue) for NewMonthColumnName in ([NewValue01],[NewValue02],[NewValue03],[NewValue04],[NewValue05],[NewValue06],[NewValue07],[NewValue08],[NewValue09],[NewValue10],[NewValue11],[NewValue12])) as pvt2
GROUP BY 
	ServiceLineEncounterID, 
	AdjustmentGUID, 
	UnitTypeID,
	TimeClassID,
	BudgetPhaseID,
	BudgetConfigID,
	AdjustmentType;
GO


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

-- fp.viewServiceLineEncounterPayorGroupMix_Pivoted
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	6-27-2023  MY      JAZZ-56923		Adding Service Line into the SLE to Charge payor mix calc
*************************************************************/
CREATE   VIEW fp.viewServiceLineEncounterPayorGroupMix_Pivoted
 AS
	SELECT budg.BudgetConfigID, budg.EntityGroupConfigID, budg.EntityID, budg.PatientClassID, budg.ServiceLineID, budg.PayorGroupID, 
		budg.MixPercentage AS BudgetMixPercentage, 
		proj.MixPercentage AS ProjectionMixPercentage, 
		budg.InitialMixPercentage AS InitialBudgetMixPercentage, 
		proj.InitialMixPercentage AS InitialProjectionMixPercentage
	FROM fp.ServiceLineEncounterPayorGroupMix budg
		INNER JOIN fp.ServiceLineEncounterPayorGroupMix proj ON 
				budg.BudgetConfigID = proj.BudgetConfigID 
			AND budg.EntityGroupConfigID = proj.EntityGroupConfigID 
			AND budg.EntityID = proj.EntityID
			AND budg.PatientClassID = proj.PatientClassID
			AND budg.ServiceLineID = proj.ServiceLineID
			AND budg.PayorGroupID = proj.PayorGroupID
	WHERE budg.TimeClassID = 2
		AND proj.TimeClassID = 12
GO


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

-- fp.viewServiceLineEncounterSpreads
CREATE VIEW [fp].[viewServiceLineEncounterSpreads]
AS
    SELECT [BudgetConfigID], [EntityID], [ServiceLineID], [PatientClassID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID]
    FROM [fp].[ServiceLineEncounterSpreads] with (readuncommitted)
    WHERE GlobalSpreadID = 1

    UNION ALL

    SELECT bs.[BudgetConfigID], [EntityID], [ServiceLineID], [PatientClassID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID]
    FROM [fp].[ServiceLineEncounterSpreads] bs with (readuncommitted)
    INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID
    WHERE bs.GlobalSpreadID > 1
GO


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

-- fp.viewServiceLineEncounter_AllTotals
CREATE   VIEW [fp].[viewServiceLineEncounter_AllTotals]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-01-16  BK  	 JAZZ-48267  Create view for totals only
 *************************************************************/
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	sl.TargetLockType as TargetLockType,
	sl.TargetLockFlag as TargetLockFlag,
	sl.BudgetLockType as BudgetLockType,
	sl.BudgetLockFlag as BudgetLockFlag,
	sl.ProjectionLockType AS ProjectionLockType,
	sl.ProjectionLockFlag AS ProjectionLockFlag,
	
	CASE WHEN sl.TargetLockType = 6 THEN 1 ELSE 0 END AS TargetSpreadsLockFlag,

	sl.TargetAdjustedTotal as AdjustedTotal,
	sl.BudgetAdjustedTotal as ManagerAdjustedTotal,
	sl.ProjectionAdjustedTotal as AdjustedProjectionTotal,

    hist.PriorYearActualValueTotal as PriorYearActualValueTotal,
    hist.ActualYTDValueTotal as ActualYTDValueTotal,
    hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal,

	sl.SampledBudgetTotal,
    sl.InitialBudgetTotal,
    sl.InitialProjectionTotal,

	sl.TargetAdjusted01 as Adjusted01,
	sl.TargetAdjusted02 as Adjusted02,
	sl.TargetAdjusted03 as Adjusted03,
	sl.TargetAdjusted04 as Adjusted04,
	sl.TargetAdjusted05 as Adjusted05,
	sl.TargetAdjusted06 as Adjusted06,
	sl.TargetAdjusted07 as Adjusted07,
	sl.TargetAdjusted08 as Adjusted08,
	sl.TargetAdjusted09 as Adjusted09,
	sl.TargetAdjusted10 as Adjusted10,
	sl.TargetAdjusted11 as Adjusted11,
	sl.TargetAdjusted12 as Adjusted12,

	sl.BudgetAdjusted01 AS ManagerAdjusted01, 
	sl.BudgetAdjusted02 AS ManagerAdjusted02, 
	sl.BudgetAdjusted03 AS ManagerAdjusted03, 
	sl.BudgetAdjusted04 AS ManagerAdjusted04, 
	sl.BudgetAdjusted05 AS ManagerAdjusted05, 
	sl.BudgetAdjusted06 AS ManagerAdjusted06, 
	sl.BudgetAdjusted07 AS ManagerAdjusted07, 
	sl.BudgetAdjusted08 AS ManagerAdjusted08, 
	sl.BudgetAdjusted09 AS ManagerAdjusted09, 
	sl.BudgetAdjusted10 AS ManagerAdjusted10, 
	sl.BudgetAdjusted11 AS ManagerAdjusted11, 
	sl.BudgetAdjusted12 AS ManagerAdjusted12, 

    sl.ProjectionAdjusted01 AS AdjustedProjection01,
	sl.ProjectionAdjusted02 AS AdjustedProjection02, 
	sl.ProjectionAdjusted03 AS AdjustedProjection03, 
	sl.ProjectionAdjusted04 AS AdjustedProjection04, 
	sl.ProjectionAdjusted05 AS AdjustedProjection05, 
	sl.ProjectionAdjusted06 AS AdjustedProjection06, 
	sl.ProjectionAdjusted07 AS AdjustedProjection07, 
	sl.ProjectionAdjusted08 AS AdjustedProjection08, 
	sl.ProjectionAdjusted09 AS AdjustedProjection09, 
	sl.ProjectionAdjusted10 AS AdjustedProjection10, 
	sl.ProjectionAdjusted11 AS AdjustedProjection11, 
	sl.ProjectionAdjusted12 AS AdjustedProjection12

From fp.ServiceLineEncounter sl
	INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewServiceLineEncounter_BudgetAdjusted
CREATE   VIEW [fp].[viewServiceLineEncounter_BudgetAdjusted]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-01-16  BK  	 JAZZ-48267  Create view for budget adjusted only
 *************************************************************/
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	sl.BudgetAdjustedTotal,
	sl.BudgetAdjusted01,
	sl.BudgetAdjusted02, 
	sl.BudgetAdjusted03, 
	sl.BudgetAdjusted04,
	sl.BudgetAdjusted05,
	sl.BudgetAdjusted06,
	sl.BudgetAdjusted07,
	sl.BudgetAdjusted08,
	sl.BudgetAdjusted09,
	sl.BudgetAdjusted10, 
	sl.BudgetAdjusted11, 
	sl.BudgetAdjusted12


From fp.ServiceLineEncounter sl
	INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewServiceLineEncounter_InitialBudget
CREATE   VIEW [fp].[viewServiceLineEncounter_InitialBudget]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-01-16  BK  	 JAZZ-48267  Create view for inital budget only
 *************************************************************/
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	sl.InitialBudgetTotal,

	sl.InitialBudget01,
	sl.InitialBudget02, 
	sl.InitialBudget03, 
	sl.InitialBudget04,
	sl.InitialBudget05,
	sl.InitialBudget06,
	sl.InitialBudget07,
	sl.InitialBudget08,
	sl.InitialBudget09,
	sl.InitialBudget10, 
	sl.InitialBudget11, 
	sl.InitialBudget12


From fp.ServiceLineEncounter sl
	INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewServiceLineEncounter_InitialProjection
CREATE   VIEW [fp].[viewServiceLineEncounter_InitialProjection]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-01-16  BK  	 JAZZ-48267  Create view for inital projection only
 *************************************************************/
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	sl.InitialProjectionTotal,

	sl.InitialProjection01,
	sl.InitialProjection02, 
	sl.InitialProjection03, 
	sl.InitialProjection04,
	sl.InitialProjection05,
	sl.InitialProjection06,
	sl.InitialProjection07,
	sl.InitialProjection08,
	sl.InitialProjection09,
	sl.InitialProjection10, 
	sl.InitialProjection11, 
	sl.InitialProjection12


From fp.ServiceLineEncounter sl
	INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewServiceLineEncounter_ProjectionAdjusted
CREATE   VIEW [fp].[viewServiceLineEncounter_ProjectionAdjusted]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-01-16  BK  	 JAZZ-48267  Create view for projection adjusted only
 *************************************************************/
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	sl.ProjectionAdjustedTotal,
	sl.ProjectionAdjusted01,
	sl.ProjectionAdjusted02, 
	sl.ProjectionAdjusted03, 
	sl.ProjectionAdjusted04,
	sl.ProjectionAdjusted05,
	sl.ProjectionAdjusted06,
	sl.ProjectionAdjusted07,
	sl.ProjectionAdjusted08,
	sl.ProjectionAdjusted09,
	sl.ProjectionAdjusted10, 
	sl.ProjectionAdjusted11, 
	sl.ProjectionAdjusted12


FROM fp.ServiceLineEncounter sl
	INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewServiceLineEncounter_TargetAdjusted
CREATE   VIEW [fp].[viewServiceLineEncounter_TargetAdjusted]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-01-16  BK  	 JAZZ-48267  Create view for target adjusted only
 *************************************************************/
SELECT 
	sl.ServiceLineEncounterID,
	sl.BudgetConfigID,
	sl.EntityGroupConfigID,
	sl.EntityID,
	sl.PatientClassID,
	sl.ServiceLineID,
	sl.ServiceLineRollupID,
	sl.AgeCohortID,
	sl.MedicalSurgicalID,
	sl.DepartmentID,
	sl.PayorID,
	sl.PayorGroupID,
	sl.MSDRGID,
	sl.CPTID,
	sl.ProviderID,
	sl.PhysicianSpecialtyID,
	sl.UnitTypeID,

	sl.TargetAdjustedTotal,

	sl.TargetAdjusted01,
	sl.TargetAdjusted02, 
	sl.TargetAdjusted03, 
	sl.TargetAdjusted04,
	sl.TargetAdjusted05,
	sl.TargetAdjusted06,
	sl.TargetAdjusted07,
	sl.TargetAdjusted08,
	sl.TargetAdjusted09,
	sl.TargetAdjusted10, 
	sl.TargetAdjusted11, 
	sl.TargetAdjusted12


From fp.ServiceLineEncounter sl
	INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID
GO


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

-- fp.viewServiceLineEncountersSpreadUnlockData
CREATE VIEW [fp].[viewServiceLineEncountersSpreadUnlockData]
AS
SELECT sud.[RowID]
      ,sud.[BudgetConfigID]
      ,sud.[AdjustmentGUID]
      ,sud.[EntityID]
	  ,sud.[PatientClassID]
	  ,sud.[ServiceLineID] 
	  ,sud.[ServiceLineRollupID]
	  ,sud.[AgeCohortID] 
	  ,sud.[MedicalSurgicalID]
	  ,sud.[DepartmentID]
	  ,sud.[PayorID] 
	  ,sud.[PayorGroupID]
	  ,sud.[MSDRGID]
	  ,sud.[CPTID] 
	  ,sud.[ProviderID] 
	  ,sud.[PhysicianSpecialtyID]
      ,sud.[Version]
      ,sud.[Value01]
      ,sud.[Value02]
      ,sud.[Value03]
      ,sud.[Value04]
      ,sud.[Value05]
      ,sud.[Value06]
      ,sud.[Value07]
      ,sud.[Value08]
      ,sud.[Value09]
      ,sud.[Value10]
      ,sud.[Value11]
      ,sud.[Value12]
      ,sud.[IsRecordDeleted]
	  ,adj.[BudgetPhaseID]
  FROM [fp].[ServiceLineEncountersSpreadUnlockData] sud
  INNER JOIN [fp].[ServiceLineEncounterAdjustment] adj ON adj.[AdjustmentGUID] = sud.[AdjustmentGUID]
  WHERE sud.IsRecordDeleted = 0
GO


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

-- fp.viewSpreadsStatsFlexedByChargeVolume
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	5-18-2023  MY      JAZZ-54812		Updated view to restructure
*************************************************************/
CREATE   VIEW fp.viewSpreadsStatsFlexedByChargeVolume
AS
SELECT 
	BudgetConfigID,
	EntityGroupConfigID,
	DepartmentID,
	AccountID,
	SpreadPercentage01,
	SpreadPercentage02,
	SpreadPercentage03,
	SpreadPercentage04,
	SpreadPercentage05,
	SpreadPercentage06,
	SpreadPercentage07,
	SpreadPercentage08,
	SpreadPercentage09,
	SpreadPercentage10,
	SpreadPercentage11,
	1 - (SpreadPercentage01 + SpreadPercentage02 + SpreadPercentage03 + SpreadPercentage04 + SpreadPercentage05 + SpreadPercentage06 + SpreadPercentage07 + SpreadPercentage08 + SpreadPercentage09 + SpreadPercentage10 + SpreadPercentage11) AS SpreadPercentage12
FROM (
		SELECT 
			cv.BudgetConfigID,
			cts.EntityGroupConfigID,
			cts.DepartmentID,
			cts.AccountID,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted01) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage01,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted02) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage02,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted03) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage03,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted04) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage04,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted05) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage05,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted06) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage06,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted07) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage07,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted08) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage08,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted09) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage09,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted10) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage10,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted11) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage11,
			CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted12) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage12
		FROM fp.ChargeVolume cv
			INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cts
				ON cv.EntityGroupConfigID = cts.EntityGroupConfigID
				AND cv.DepartmentID = cts.DepartmentID
				AND cv.ChargeCodeID = cts.ChargeCodeID
				AND cv.PatientClassID = cts.PatientClassID
		WHERE
			cv.UnitTypeID = 145
		GROUP BY 
			cv.BudgetConfigID,
			cts.EntityGroupConfigID,
			cts.DepartmentID,
			cts.AccountID
		) data
GO


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

-- fp.viewStaffing
CREATE   VIEW [fp].[viewStaffing]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-09-23  BW  	 JAZZ-60740		Replacement for [fp].[viewFactStaffing_Pivoted], new data structure
 *************************************************************/

	SELECT
		fs.StaffingID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.FlexingTypeID,

-- Dollars
		fs.TargetDollarsLockType,
		fs.TargetDollarsLockFlag,
		fs.BudgetDollarsLockType,
		fs.BudgetDollarsLockFlag,
		fs.ProjectionDollarsLockType,
		fs.ProjectionDollarsLockFlag,

		CASE WHEN fs.BudgetDollarsLockType = 6 THEN 1 ELSE 0 END AS BudgetDollarsSpreadsLockFlag,

		CASE WHEN fs.BudgetDollarsLockType = 7 THEN 1 ELSE 0 END AS BudgetDollarsAdjustmentLockFlag,
		CASE WHEN fs.TargetDollarsLockType = 7 THEN 1 ELSE 0 END AS TargetDollarsAdjustmentLockFlag,
		CASE WHEN fs.ProjectionDollarsLockType = 7 THEN 1 ELSE 0 END AS ProjectionDollarsAdjustmentLockFlag,

		fs.TargetAdjustedDollarsTotal,
		fs.BudgetAdjustedDollarsTotal,
		fs.ProjectionAdjustedDollarsTotal,

		hist.ActualYTDDollarsTotal,
		hist.CurrentYearBudgetDollarsTotal,
		hist.PriorYearActualDollarsTotal,

		fs.InitialBudgetDollarsTotal,
		fs.InitialBudgetDollars01,
		fs.InitialBudgetDollars02,
		fs.InitialBudgetDollars03,
		fs.InitialBudgetDollars04,
		fs.InitialBudgetDollars05,
		fs.InitialBudgetDollars06,
		fs.InitialBudgetDollars07,
		fs.InitialBudgetDollars08,
		fs.InitialBudgetDollars09,
		fs.InitialBudgetDollars10,
		fs.InitialBudgetDollars11,
		fs.InitialBudgetDollars12,

		fs.InitialProjectionDollarsTotal,

		CASE WHEN fs.FlexingTypeID IN (3, 9) THEN 1 ELSE 0 END AS IsFlexedByStats,

		-- Target Montly Values
		fs.TargetAdjustedDollars01,
		fs.TargetAdjustedDollars02,
		fs.TargetAdjustedDollars03,
		fs.TargetAdjustedDollars04,
		fs.TargetAdjustedDollars05,
		fs.TargetAdjustedDollars06,
		fs.TargetAdjustedDollars07,
		fs.TargetAdjustedDollars08,
		fs.TargetAdjustedDollars09,
		fs.TargetAdjustedDollars10,
		fs.TargetAdjustedDollars11,
		fs.TargetAdjustedDollars12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedDollars01,
		fs.BudgetAdjustedDollars02,
		fs.BudgetAdjustedDollars03,
		fs.BudgetAdjustedDollars04,
		fs.BudgetAdjustedDollars05,
		fs.BudgetAdjustedDollars06,
		fs.BudgetAdjustedDollars07,
		fs.BudgetAdjustedDollars08,
		fs.BudgetAdjustedDollars09,
		fs.BudgetAdjustedDollars10,
		fs.BudgetAdjustedDollars11,
		fs.BudgetAdjustedDollars12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedDollars01,
		fs.ProjectionAdjustedDollars02,
		fs.ProjectionAdjustedDollars03,
		fs.ProjectionAdjustedDollars04,
		fs.ProjectionAdjustedDollars05,
		fs.ProjectionAdjustedDollars06,
		fs.ProjectionAdjustedDollars07,
		fs.ProjectionAdjustedDollars08,
		fs.ProjectionAdjustedDollars09,
		fs.ProjectionAdjustedDollars10,
		fs.ProjectionAdjustedDollars11,
		fs.ProjectionAdjustedDollars12,

-- Hours 
		fs.TargetHoursLockType,
		fs.TargetHoursLockFlag,
		fs.BudgetHoursLockType,
		fs.BudgetHoursLockFlag,
		fs.ProjectionHoursLockType,
		fs.ProjectionHoursLockFlag,

		CASE WHEN fs.BudgetHoursLockType = 6 THEN 1 ELSE 0 END AS BudgetHoursSpreadsLockFlag,

		CASE WHEN fs.BudgetHoursLockType = 7 THEN 1 ELSE 0 END AS BudgetHoursAdjustmentLockFlag,
		CASE WHEN fs.TargetHoursLockType = 7 THEN 1 ELSE 0 END AS TargetHoursAdjustmentLockFlag,
		CASE WHEN fs.ProjectionHoursLockType = 7 THEN 1 ELSE 0 END AS ProjectionHoursAdjustmentLockFlag,

		fs.TargetAdjustedHoursTotal,
		fs.BudgetAdjustedHoursTotal,
		fs.ProjectionAdjustedHoursTotal,

		hist.ActualYTDHoursTotal,
		hist.CurrentYearBudgetHoursTotal,
		hist.PriorYearActualHoursTotal,

		fs.InitialBudgetHoursTotal,
		fs.InitialBudgetHours01,
		fs.InitialBudgetHours02,
		fs.InitialBudgetHours03,
		fs.InitialBudgetHours04,
		fs.InitialBudgetHours05,
		fs.InitialBudgetHours06,
		fs.InitialBudgetHours07,
		fs.InitialBudgetHours08,
		fs.InitialBudgetHours09,
		fs.InitialBudgetHours10,
		fs.InitialBudgetHours11,
		fs.InitialBudgetHours12,

		fs.InitialProjectionHoursTotal,

		-- Target Montly Values
		fs.TargetAdjustedHours01,
		fs.TargetAdjustedHours02,
		fs.TargetAdjustedHours03,
		fs.TargetAdjustedHours04,
		fs.TargetAdjustedHours05,
		fs.TargetAdjustedHours06,
		fs.TargetAdjustedHours07,
		fs.TargetAdjustedHours08,
		fs.TargetAdjustedHours09,
		fs.TargetAdjustedHours10,
		fs.TargetAdjustedHours11,
		fs.TargetAdjustedHours12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedHours01,
		fs.BudgetAdjustedHours02,
		fs.BudgetAdjustedHours03,
		fs.BudgetAdjustedHours04,
		fs.BudgetAdjustedHours05,
		fs.BudgetAdjustedHours06,
		fs.BudgetAdjustedHours07,
		fs.BudgetAdjustedHours08,
		fs.BudgetAdjustedHours09,
		fs.BudgetAdjustedHours10,
		fs.BudgetAdjustedHours11,
		fs.BudgetAdjustedHours12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedHours01,
		fs.ProjectionAdjustedHours02,
		fs.ProjectionAdjustedHours03,
		fs.ProjectionAdjustedHours04,
		fs.ProjectionAdjustedHours05,
		fs.ProjectionAdjustedHours06,
		fs.ProjectionAdjustedHours07,
		fs.ProjectionAdjustedHours08,
		fs.ProjectionAdjustedHours09,
		fs.ProjectionAdjustedHours10,
		fs.ProjectionAdjustedHours11,
		fs.ProjectionAdjustedHours12,
	
-- FTEs 
		fs.TargetFTEsLockType,
		fs.TargetFTEsLockFlag,
		fs.BudgetFTEsLockType,
		fs.BudgetFTEsLockFlag,
		fs.ProjectionFTEsLockType,
		fs.ProjectionFTEsLockFlag,

		CASE WHEN fs.BudgetFTEsLockType = 6 THEN 1 ELSE 0 END AS BudgetFTEsSpreadsLockFlag,

		CASE WHEN fs.BudgetFTEsLockType = 7 THEN 1 ELSE 0 END AS BudgetFTEsAdjustmentLockFlag,
		CASE WHEN fs.TargetFTEsLockType = 7 THEN 1 ELSE 0 END AS TargetFTEsAdjustmentLockFlag,
		CASE WHEN fs.ProjectionFTEsLockType = 7 THEN 1 ELSE 0 END AS ProjectionFTEsAdjustmentLockFlag,

		hist.ActualYTDFTEsTotal,
		hist.CurrentYearBudgetFTEsTotal,
		hist.PriorYearActualFTEsTotal,

		fs.InitialBudgetFTEs01,
		fs.InitialBudgetFTEs02,
		fs.InitialBudgetFTEs03,
		fs.InitialBudgetFTEs04,
		fs.InitialBudgetFTEs05,
		fs.InitialBudgetFTEs06,
		fs.InitialBudgetFTEs07,
		fs.InitialBudgetFTEs08,
		fs.InitialBudgetFTEs09,
		fs.InitialBudgetFTEs10,
		fs.InitialBudgetFTEs11,
		fs.InitialBudgetFTEs12,

		-- Target Montly Values
		fs.TargetAdjustedFTEs01,
		fs.TargetAdjustedFTEs02,
		fs.TargetAdjustedFTEs03,
		fs.TargetAdjustedFTEs04,
		fs.TargetAdjustedFTEs05,
		fs.TargetAdjustedFTEs06,
		fs.TargetAdjustedFTEs07,
		fs.TargetAdjustedFTEs08,
		fs.TargetAdjustedFTEs09,
		fs.TargetAdjustedFTEs10,
		fs.TargetAdjustedFTEs11,
		fs.TargetAdjustedFTEs12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedFTEs01,
		fs.BudgetAdjustedFTEs02,
		fs.BudgetAdjustedFTEs03,
		fs.BudgetAdjustedFTEs04,
		fs.BudgetAdjustedFTEs05,
		fs.BudgetAdjustedFTEs06,
		fs.BudgetAdjustedFTEs07,
		fs.BudgetAdjustedFTEs08,
		fs.BudgetAdjustedFTEs09,
		fs.BudgetAdjustedFTEs10,
		fs.BudgetAdjustedFTEs11,
		fs.BudgetAdjustedFTEs12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedFTEs01,
		fs.ProjectionAdjustedFTEs02,
		fs.ProjectionAdjustedFTEs03,
		fs.ProjectionAdjustedFTEs04,
		fs.ProjectionAdjustedFTEs05,
		fs.ProjectionAdjustedFTEs06,
		fs.ProjectionAdjustedFTEs07,
		fs.ProjectionAdjustedFTEs08,
		fs.ProjectionAdjustedFTEs09,
		fs.ProjectionAdjustedFTEs10,
		fs.ProjectionAdjustedFTEs11,
		fs.ProjectionAdjustedFTEs12,

-- Rates 
		fs.InitialBudgetRate01,
		fs.InitialBudgetRate02,
		fs.InitialBudgetRate03,
		fs.InitialBudgetRate04,
		fs.InitialBudgetRate05,
		fs.InitialBudgetRate06,
		fs.InitialBudgetRate07,
		fs.InitialBudgetRate08,
		fs.InitialBudgetRate09,
		fs.InitialBudgetRate10,
		fs.InitialBudgetRate11,
		fs.InitialBudgetRate12,

		-- Target Montly Values
		fs.TargetAdjustedRate01,
		fs.TargetAdjustedRate02,
		fs.TargetAdjustedRate03,
		fs.TargetAdjustedRate04,
		fs.TargetAdjustedRate05,
		fs.TargetAdjustedRate06,
		fs.TargetAdjustedRate07,
		fs.TargetAdjustedRate08,
		fs.TargetAdjustedRate09,
		fs.TargetAdjustedRate10,
		fs.TargetAdjustedRate11,
		fs.TargetAdjustedRate12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedRate01,
		fs.BudgetAdjustedRate02,
		fs.BudgetAdjustedRate03,
		fs.BudgetAdjustedRate04,
		fs.BudgetAdjustedRate05,
		fs.BudgetAdjustedRate06,
		fs.BudgetAdjustedRate07,
		fs.BudgetAdjustedRate08,
		fs.BudgetAdjustedRate09,
		fs.BudgetAdjustedRate10,
		fs.BudgetAdjustedRate11,
		fs.BudgetAdjustedRate12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedRate01,
		fs.ProjectionAdjustedRate02,
		fs.ProjectionAdjustedRate03,
		fs.ProjectionAdjustedRate04,
		fs.ProjectionAdjustedRate05,
		fs.ProjectionAdjustedRate06,
		fs.ProjectionAdjustedRate07,
		fs.ProjectionAdjustedRate08,
		fs.ProjectionAdjustedRate09,
		fs.ProjectionAdjustedRate10,
		fs.ProjectionAdjustedRate11,
		fs.ProjectionAdjustedRate12,

-- Wage Rate
		wr.TargetWageRateLockType,
		wr.TargetWageRateLockFlag,
		wr.BudgetWageRateLockType,
		wr.BudgetWageRateLockFlag,
		wr.ProjectionWageRateLockType,
		wr.ProjectionWageRateLockFlag,

		wr.InitialBudget01 AS InitialBudgetWageRate01,
		wr.InitialBudget02 AS InitialBudgetWageRate02,
		wr.InitialBudget03 AS InitialBudgetWageRate03,
		wr.InitialBudget04 AS InitialBudgetWageRate04,
		wr.InitialBudget05 AS InitialBudgetWageRate05,
		wr.InitialBudget06 AS InitialBudgetWageRate06,
		wr.InitialBudget07 AS InitialBudgetWageRate07,
		wr.InitialBudget08 AS InitialBudgetWageRate08,
		wr.InitialBudget09 AS InitialBudgetWageRate09,
		wr.InitialBudget10 AS InitialBudgetWageRate10,
		wr.InitialBudget11 AS InitialBudgetWageRate11,
		wr.InitialBudget12 AS InitialBudgetWageRate12,

		-- Target Montly Values
		wr.TargetAdjusted01 AS TargetAdjustedWageRate01,
		wr.TargetAdjusted02 AS TargetAdjustedWageRate02,
		wr.TargetAdjusted03 AS TargetAdjustedWageRate03,
		wr.TargetAdjusted04 AS TargetAdjustedWageRate04,
		wr.TargetAdjusted05 AS TargetAdjustedWageRate05,
		wr.TargetAdjusted06 AS TargetAdjustedWageRate06,
		wr.TargetAdjusted07 AS TargetAdjustedWageRate07,
		wr.TargetAdjusted08 AS TargetAdjustedWageRate08,
		wr.TargetAdjusted09 AS TargetAdjustedWageRate09,
		wr.TargetAdjusted10 AS TargetAdjustedWageRate10,
		wr.TargetAdjusted11 AS TargetAdjustedWageRate11,
		wr.TargetAdjusted12 AS TargetAdjustedWageRate12,

		-- Budgeted Monthly Values
		wr.BudgetAdjusted01 AS BudgetAdjustedWageRate01,
		wr.BudgetAdjusted02 AS BudgetAdjustedWageRate02,
		wr.BudgetAdjusted03 AS BudgetAdjustedWageRate03,
		wr.BudgetAdjusted04 AS BudgetAdjustedWageRate04,
		wr.BudgetAdjusted05 AS BudgetAdjustedWageRate05,
		wr.BudgetAdjusted06 AS BudgetAdjustedWageRate06,
		wr.BudgetAdjusted07 AS BudgetAdjustedWageRate07,
		wr.BudgetAdjusted08 AS BudgetAdjustedWageRate08,
		wr.BudgetAdjusted09 AS BudgetAdjustedWageRate09,
		wr.BudgetAdjusted10 AS BudgetAdjustedWageRate10,
		wr.BudgetAdjusted11 AS BudgetAdjustedWageRate11,
		wr.BudgetAdjusted12 AS BudgetAdjustedWageRate12,

		-- Projected Monthly Values
		wr.ProjectionAdjusted01 AS ProjectionAdjustedWageRate01,
		wr.ProjectionAdjusted02 AS ProjectionAdjustedWageRate02,
		wr.ProjectionAdjusted03 AS ProjectionAdjustedWageRate03,
		wr.ProjectionAdjusted04 AS ProjectionAdjustedWageRate04,
		wr.ProjectionAdjusted05 AS ProjectionAdjustedWageRate05,
		wr.ProjectionAdjusted06 AS ProjectionAdjustedWageRate06,
		wr.ProjectionAdjusted07 AS ProjectionAdjustedWageRate07,
		wr.ProjectionAdjusted08 AS ProjectionAdjustedWageRate08,
		wr.ProjectionAdjusted09 AS ProjectionAdjustedWageRate09,
		wr.ProjectionAdjusted10 AS ProjectionAdjustedWageRate10,
		wr.ProjectionAdjusted11 AS ProjectionAdjustedWageRate11,
		wr.ProjectionAdjusted12 AS ProjectionAdjustedWageRate12

	FROM [fp].[Staffing] fs (READUNCOMMITTED)
	INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
	INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) ON fs.StaffingWageRateID = wr.StaffingWageRateID
GO


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

-- fp.viewStaffingAdjustment
CREATE VIEW [fp].[viewStaffingAdjustment]
AS 

SELECT [AdjustmentGUID]
      ,[BudgetConfigGUID]
      ,[AdjustmentType]
      ,[Value]
      ,[AdjustmentFilterJSON]
      ,[GroupingHierarchyJSON]
      ,[AdjustedProperty]
      ,[Comment]
      ,[AuthorGUID]
      ,[AuthorFullName]
      ,[LastModifiedDateUtc]
      ,[DateCreatedUtc]
      ,[UnitTypeID]
      ,[GroupingGUID]
      ,[ParentFilterJSON]
      ,[TimeClassID]
      ,[BudgetPhaseID]
      ,[ClassificationGroupID]
      ,[ClassificationCategoryID]
      ,[IsRecordDeleted]
      ,[DimensionMemberJson]
      ,[AdjustmentID]
	  ,[SubsectionID]
	  ,[IsErrored]
  FROM [fp].[StaffingAdjustment]
  WHERE IsRecordDeleted = 0;
GO


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

-- fp.viewStaffingAdjustmentImport
CREATE VIEW [fp].[viewStaffingAdjustmentImport]
AS 

SELECT [RowID]
      ,[AdjustmentGUID]
      ,[DepartmentID]
      ,[JobCodeID]
      ,[FiscalYearID]
      ,[UnitTypeID]
      ,[FiscalMonthID]
      ,[Value]
      ,[Version]
      ,[PayCodeGroupID]
      ,[ProductiveClassID]
      ,[VariabilityID]
      ,[EntityID]
      ,[TimeClassID]
      ,[BudgetPhaseID]
      ,[IsRecordDeleted]
      ,[AdjustmentID]
      ,[EmployeeID]
      ,[ProviderID]
      ,[ProviderTypeID]
      ,[ProviderSpecialtyID]
      ,[ProviderLineItemID]
	  ,[OriginalUnitTypeID]
  FROM [fp].[StaffingAdjustmentImport]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewStaffingDollars
CREATE   VIEW [fp].[viewStaffingDollars]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-02-21  MY  	 JAZZ-XXX		Initial
 *************************************************************/

	SELECT
		fs.StaffingID,
		fs.StaffingWageRateID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.FlexingTypeID,
		fs.FixedVariabilityPercentage,
		fs.IsNew,
		fs.AddDate,

		fs.TargetDollarsLockType,
		fs.TargetDollarsLockFlag,
		fs.BudgetDollarsLockType,
		fs.BudgetDollarsLockFlag,
		fs.ProjectionDollarsLockType,
		fs.ProjectionDollarsLockFlag,

		fs.TargetAdjustedDollarsTotal,
		fs.BudgetAdjustedDollarsTotal,
		fs.ProjectionAdjustedDollarsTotal,

		fs.InitialBudgetDollarsTotal,
		fs.SampledBudgetDollarsTotal,
		fs.SampledProjectionDollarsTotal,

		hist.ActualYTDDollarsTotal,
		hist.CurrentYearBudgetDollarsTotal,
		hist.PriorYearActualDollarsTotal,

		-- Target Montly Values
		fs.TargetAdjustedDollars01,
		fs.TargetAdjustedDollars02,
		fs.TargetAdjustedDollars03,
		fs.TargetAdjustedDollars04,
		fs.TargetAdjustedDollars05,
		fs.TargetAdjustedDollars06,
		fs.TargetAdjustedDollars07,
		fs.TargetAdjustedDollars08,
		fs.TargetAdjustedDollars09,
		fs.TargetAdjustedDollars10,
		fs.TargetAdjustedDollars11,
		fs.TargetAdjustedDollars12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedDollars01,
		fs.BudgetAdjustedDollars02,
		fs.BudgetAdjustedDollars03,
		fs.BudgetAdjustedDollars04,
		fs.BudgetAdjustedDollars05,
		fs.BudgetAdjustedDollars06,
		fs.BudgetAdjustedDollars07,
		fs.BudgetAdjustedDollars08,
		fs.BudgetAdjustedDollars09,
		fs.BudgetAdjustedDollars10,
		fs.BudgetAdjustedDollars11,
		fs.BudgetAdjustedDollars12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedDollars01,
		fs.ProjectionAdjustedDollars02,
		fs.ProjectionAdjustedDollars03,
		fs.ProjectionAdjustedDollars04,
		fs.ProjectionAdjustedDollars05,
		fs.ProjectionAdjustedDollars06,
		fs.ProjectionAdjustedDollars07,
		fs.ProjectionAdjustedDollars08,
		fs.ProjectionAdjustedDollars09,
		fs.ProjectionAdjustedDollars10,
		fs.ProjectionAdjustedDollars11,
		fs.ProjectionAdjustedDollars12,

		-- Initial Dollars
		fs.InitialBudgetDollars01,
		fs.InitialBudgetDollars02,
		fs.InitialBudgetDollars03,
		fs.InitialBudgetDollars04,
		fs.InitialBudgetDollars05,
		fs.InitialBudgetDollars06,
		fs.InitialBudgetDollars07,
		fs.InitialBudgetDollars08,
		fs.InitialBudgetDollars09,
		fs.InitialBudgetDollars10,
		fs.InitialBudgetDollars11,
		fs.InitialBudgetDollars12,
		
		-- Sampled Dollars
		fs.SampledBudgetDollars01,
		fs.SampledBudgetDollars02,
		fs.SampledBudgetDollars03,
		fs.SampledBudgetDollars04,
		fs.SampledBudgetDollars05,
		fs.SampledBudgetDollars06,
		fs.SampledBudgetDollars07,
		fs.SampledBudgetDollars08,
		fs.SampledBudgetDollars09,
		fs.SampledBudgetDollars10,
		fs.SampledBudgetDollars11,
		fs.SampledBudgetDollars12,
		
		-- Sampled Projection Dollars
		fs.SampledProjectionDollars01,
		fs.SampledProjectionDollars02,
		fs.SampledProjectionDollars03,
		fs.SampledProjectionDollars04,
		fs.SampledProjectionDollars05,
		fs.SampledProjectionDollars06,
		fs.SampledProjectionDollars07,
		fs.SampledProjectionDollars08,
		fs.SampledProjectionDollars09,
		fs.SampledProjectionDollars10,
		fs.SampledProjectionDollars11,
		fs.SampledProjectionDollars12,

		-- ActualYTD Dollars
		hist.ActualYTDDollars01,
		hist.ActualYTDDollars02,
		hist.ActualYTDDollars03,
		hist.ActualYTDDollars04,
		hist.ActualYTDDollars05,
		hist.ActualYTDDollars06,
		hist.ActualYTDDollars07,
		hist.ActualYTDDollars08,
		hist.ActualYTDDollars09,
		hist.ActualYTDDollars10,
		hist.ActualYTDDollars11,
		hist.ActualYTDDollars12,

		-- CurrentYearBudget Dollars
		hist.CurrentYearBudgetDollars01,
		hist.CurrentYearBudgetDollars02,
		hist.CurrentYearBudgetDollars03,
		hist.CurrentYearBudgetDollars04,
		hist.CurrentYearBudgetDollars05,
		hist.CurrentYearBudgetDollars06,
		hist.CurrentYearBudgetDollars07,
		hist.CurrentYearBudgetDollars08,
		hist.CurrentYearBudgetDollars09,
		hist.CurrentYearBudgetDollars10,
		hist.CurrentYearBudgetDollars11,
		hist.CurrentYearBudgetDollars12,

		-- PriorYearActual Dollars
		hist.PriorYearActualDollars01,
		hist.PriorYearActualDollars02,
		hist.PriorYearActualDollars03,
		hist.PriorYearActualDollars04,
		hist.PriorYearActualDollars05,
		hist.PriorYearActualDollars06,
		hist.PriorYearActualDollars07,
		hist.PriorYearActualDollars08,
		hist.PriorYearActualDollars09,
		hist.PriorYearActualDollars10,
		hist.PriorYearActualDollars11,
		hist.PriorYearActualDollars12,

		-- Target Percent Adjustment Factor Values
		fs.TargetDollarsPercentAdjustmentFactor01,
		fs.TargetDollarsPercentAdjustmentFactor02,
		fs.TargetDollarsPercentAdjustmentFactor03,
		fs.TargetDollarsPercentAdjustmentFactor04,
		fs.TargetDollarsPercentAdjustmentFactor05,
		fs.TargetDollarsPercentAdjustmentFactor06,
		fs.TargetDollarsPercentAdjustmentFactor07,
		fs.TargetDollarsPercentAdjustmentFactor08,
		fs.TargetDollarsPercentAdjustmentFactor09,
		fs.TargetDollarsPercentAdjustmentFactor10,
		fs.TargetDollarsPercentAdjustmentFactor11,
		fs.TargetDollarsPercentAdjustmentFactor12,

		-- Budgeted Percent Adjustment Factor Values
		fs.BudgetDollarsPercentAdjustmentFactor01,
		fs.BudgetDollarsPercentAdjustmentFactor02,
		fs.BudgetDollarsPercentAdjustmentFactor03,
		fs.BudgetDollarsPercentAdjustmentFactor04,
		fs.BudgetDollarsPercentAdjustmentFactor05,
		fs.BudgetDollarsPercentAdjustmentFactor06,
		fs.BudgetDollarsPercentAdjustmentFactor07,
		fs.BudgetDollarsPercentAdjustmentFactor08,
		fs.BudgetDollarsPercentAdjustmentFactor09,
		fs.BudgetDollarsPercentAdjustmentFactor10,
		fs.BudgetDollarsPercentAdjustmentFactor11,
		fs.BudgetDollarsPercentAdjustmentFactor12,

		-- Projected Percent Adjustment Factor Values
		fs.ProjectionDollarsPercentAdjustmentFactor01,
		fs.ProjectionDollarsPercentAdjustmentFactor02,
		fs.ProjectionDollarsPercentAdjustmentFactor03,
		fs.ProjectionDollarsPercentAdjustmentFactor04,
		fs.ProjectionDollarsPercentAdjustmentFactor05,
		fs.ProjectionDollarsPercentAdjustmentFactor06,
		fs.ProjectionDollarsPercentAdjustmentFactor07,
		fs.ProjectionDollarsPercentAdjustmentFactor08,
		fs.ProjectionDollarsPercentAdjustmentFactor09,
		fs.ProjectionDollarsPercentAdjustmentFactor10,
		fs.ProjectionDollarsPercentAdjustmentFactor11,
		fs.ProjectionDollarsPercentAdjustmentFactor12
	FROM [fp].[Staffing] fs (READUNCOMMITTED)
		INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
GO


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

-- fp.viewStaffingExpenseFlexingConfig
CREATE   VIEW [fp].[viewStaffingExpenseFlexingConfig]
AS
SELECT 
	b.EntityGroupConfigGUID,
	b.DepartmentID,
	b.JobCodeID,
	CASE WHEN b.FlexMethodID = 6 THEN 6
		ELSE COALESCE(ovr.FlexMethodID, b.FlexMethodID) END As FlexMethodID
FROM (
	SELECT 
		fc.EntityGroupConfigGUID,
		fc.DepartmentID,
		jc.JobCodeID,
		fc.FlexMethodID
	FROM [fp].[StaffingExpenseFlexingConfig] fc
	CROSS APPLY (SELECT JobCodeID FROM [fw].[DimJobCode] WHERE JobCodeID > 0) jc
)b
LEFT JOIN [fp].[StaffingFlexingOverrideConfig] ovr
	ON b.DepartmentID = ovr.DepartmentID
	AND b.JobCodeID = ovr.JobCodeID
	AND b.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
GO


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

-- fp.viewStaffingExpenseFlexingConfigWithDepartmentInfo
CREATE view fp.viewStaffingExpenseFlexingConfigWithDepartmentInfo
AS
SELECT OBJ.*, d.Name
FROM [fp].[StaffingExpenseFlexingConfig] OBJ
	INNER JOIN [fw].[dimDepartment] d ON OBJ.DepartmentID = d.DepartmentID
GO


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

-- fp.viewStaffingFTEs
CREATE   VIEW [fp].[viewStaffingFTEs]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-02-21  MY  	 JAZZ-XXX		Initial
 *************************************************************/

	SELECT
		fs.StaffingID,
		fs.StaffingWageRateID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.FlexingTypeID,
		fs.FixedVariabilityPercentage,
		fs.IsNew,
		fs.AddDate,

		fs.TargetFTEsLockType,
		fs.TargetFTEsLockFlag,
		fs.BudgetFTEsLockType,
		fs.BudgetFTEsLockFlag,
		fs.ProjectionFTEsLockType,
		fs.ProjectionFTEsLockFlag,

		-- Target Montly Values
		fs.TargetAdjustedFTEs01,
		fs.TargetAdjustedFTEs02,
		fs.TargetAdjustedFTEs03,
		fs.TargetAdjustedFTEs04,
		fs.TargetAdjustedFTEs05,
		fs.TargetAdjustedFTEs06,
		fs.TargetAdjustedFTEs07,
		fs.TargetAdjustedFTEs08,
		fs.TargetAdjustedFTEs09,
		fs.TargetAdjustedFTEs10,
		fs.TargetAdjustedFTEs11,
		fs.TargetAdjustedFTEs12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedFTEs01,
		fs.BudgetAdjustedFTEs02,
		fs.BudgetAdjustedFTEs03,
		fs.BudgetAdjustedFTEs04,
		fs.BudgetAdjustedFTEs05,
		fs.BudgetAdjustedFTEs06,
		fs.BudgetAdjustedFTEs07,
		fs.BudgetAdjustedFTEs08,
		fs.BudgetAdjustedFTEs09,
		fs.BudgetAdjustedFTEs10,
		fs.BudgetAdjustedFTEs11,
		fs.BudgetAdjustedFTEs12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedFTEs01,
		fs.ProjectionAdjustedFTEs02,
		fs.ProjectionAdjustedFTEs03,
		fs.ProjectionAdjustedFTEs04,
		fs.ProjectionAdjustedFTEs05,
		fs.ProjectionAdjustedFTEs06,
		fs.ProjectionAdjustedFTEs07,
		fs.ProjectionAdjustedFTEs08,
		fs.ProjectionAdjustedFTEs09,
		fs.ProjectionAdjustedFTEs10,
		fs.ProjectionAdjustedFTEs11,
		fs.ProjectionAdjustedFTEs12,

		-- Initial FTEs
		fs.InitialBudgetFTEs01,
		fs.InitialBudgetFTEs02,
		fs.InitialBudgetFTEs03,
		fs.InitialBudgetFTEs04,
		fs.InitialBudgetFTEs05,
		fs.InitialBudgetFTEs06,
		fs.InitialBudgetFTEs07,
		fs.InitialBudgetFTEs08,
		fs.InitialBudgetFTEs09,
		fs.InitialBudgetFTEs10,
		fs.InitialBudgetFTEs11,
		fs.InitialBudgetFTEs12,
		
		-- Sampled FTEs
		fs.SampledBudgetFTEs01,
		fs.SampledBudgetFTEs02,
		fs.SampledBudgetFTEs03,
		fs.SampledBudgetFTEs04,
		fs.SampledBudgetFTEs05,
		fs.SampledBudgetFTEs06,
		fs.SampledBudgetFTEs07,
		fs.SampledBudgetFTEs08,
		fs.SampledBudgetFTEs09,
		fs.SampledBudgetFTEs10,
		fs.SampledBudgetFTEs11,
		fs.SampledBudgetFTEs12,
		
		-- Sampled Projection FTEs
		fs.SampledProjectionFTEs01,
		fs.SampledProjectionFTEs02,
		fs.SampledProjectionFTEs03,
		fs.SampledProjectionFTEs04,
		fs.SampledProjectionFTEs05,
		fs.SampledProjectionFTEs06,
		fs.SampledProjectionFTEs07,
		fs.SampledProjectionFTEs08,
		fs.SampledProjectionFTEs09,
		fs.SampledProjectionFTEs10,
		fs.SampledProjectionFTEs11,
		fs.SampledProjectionFTEs12,

		-- ActualYTD FTEs
		hist.ActualYTDFTEs01,
		hist.ActualYTDFTEs02,
		hist.ActualYTDFTEs03,
		hist.ActualYTDFTEs04,
		hist.ActualYTDFTEs05,
		hist.ActualYTDFTEs06,
		hist.ActualYTDFTEs07,
		hist.ActualYTDFTEs08,
		hist.ActualYTDFTEs09,
		hist.ActualYTDFTEs10,
		hist.ActualYTDFTEs11,
		hist.ActualYTDFTEs12,

		-- CurrentYearBudget FTEs
		hist.CurrentYearBudgetFTEs01,
		hist.CurrentYearBudgetFTEs02,
		hist.CurrentYearBudgetFTEs03,
		hist.CurrentYearBudgetFTEs04,
		hist.CurrentYearBudgetFTEs05,
		hist.CurrentYearBudgetFTEs06,
		hist.CurrentYearBudgetFTEs07,
		hist.CurrentYearBudgetFTEs08,
		hist.CurrentYearBudgetFTEs09,
		hist.CurrentYearBudgetFTEs10,
		hist.CurrentYearBudgetFTEs11,
		hist.CurrentYearBudgetFTEs12,

		-- PriorYearActual FTEs
		hist.PriorYearActualFTEs01,
		hist.PriorYearActualFTEs02,
		hist.PriorYearActualFTEs03,
		hist.PriorYearActualFTEs04,
		hist.PriorYearActualFTEs05,
		hist.PriorYearActualFTEs06,
		hist.PriorYearActualFTEs07,
		hist.PriorYearActualFTEs08,
		hist.PriorYearActualFTEs09,
		hist.PriorYearActualFTEs10,
		hist.PriorYearActualFTEs11,
		hist.PriorYearActualFTEs12,

		-- Target Percent Adjustment Factor Values
		fs.TargetFTEsPercentAdjustmentFactor01,
		fs.TargetFTEsPercentAdjustmentFactor02,
		fs.TargetFTEsPercentAdjustmentFactor03,
		fs.TargetFTEsPercentAdjustmentFactor04,
		fs.TargetFTEsPercentAdjustmentFactor05,
		fs.TargetFTEsPercentAdjustmentFactor06,
		fs.TargetFTEsPercentAdjustmentFactor07,
		fs.TargetFTEsPercentAdjustmentFactor08,
		fs.TargetFTEsPercentAdjustmentFactor09,
		fs.TargetFTEsPercentAdjustmentFactor10,
		fs.TargetFTEsPercentAdjustmentFactor11,
		fs.TargetFTEsPercentAdjustmentFactor12,

		-- Budgeted Percent Adjustment Factor Values
		fs.BudgetFTEsPercentAdjustmentFactor01,
		fs.BudgetFTEsPercentAdjustmentFactor02,
		fs.BudgetFTEsPercentAdjustmentFactor03,
		fs.BudgetFTEsPercentAdjustmentFactor04,
		fs.BudgetFTEsPercentAdjustmentFactor05,
		fs.BudgetFTEsPercentAdjustmentFactor06,
		fs.BudgetFTEsPercentAdjustmentFactor07,
		fs.BudgetFTEsPercentAdjustmentFactor08,
		fs.BudgetFTEsPercentAdjustmentFactor09,
		fs.BudgetFTEsPercentAdjustmentFactor10,
		fs.BudgetFTEsPercentAdjustmentFactor11,
		fs.BudgetFTEsPercentAdjustmentFactor12,

		-- Projected Percent Adjustment Factor Values
		fs.ProjectionFTEsPercentAdjustmentFactor01,
		fs.ProjectionFTEsPercentAdjustmentFactor02,
		fs.ProjectionFTEsPercentAdjustmentFactor03,
		fs.ProjectionFTEsPercentAdjustmentFactor04,
		fs.ProjectionFTEsPercentAdjustmentFactor05,
		fs.ProjectionFTEsPercentAdjustmentFactor06,
		fs.ProjectionFTEsPercentAdjustmentFactor07,
		fs.ProjectionFTEsPercentAdjustmentFactor08,
		fs.ProjectionFTEsPercentAdjustmentFactor09,
		fs.ProjectionFTEsPercentAdjustmentFactor10,
		fs.ProjectionFTEsPercentAdjustmentFactor11,
		fs.ProjectionFTEsPercentAdjustmentFactor12
	FROM [fp].[Staffing] fs (READUNCOMMITTED)
		INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
GO


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

-- fp.viewStaffingHours
CREATE   VIEW [fp].[viewStaffingHours]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-02-21  MY  	 JAZZ-XXX		Initial
 *************************************************************/

	SELECT
		fs.StaffingID,
		fs.StaffingWageRateID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.FlexingTypeID,
		fs.FixedVariabilityPercentage,
		fs.IsNew,
		fs.AddDate,

		fs.TargetHoursLockType,
		fs.TargetHoursLockFlag,
		fs.BudgetHoursLockType,
		fs.BudgetHoursLockFlag,
		fs.ProjectionHoursLockType,
		fs.ProjectionHoursLockFlag,

		fs.TargetAdjustedHoursTotal,
		fs.BudgetAdjustedHoursTotal,
		fs.ProjectionAdjustedHoursTotal,

		fs.InitialBudgetHoursTotal,
		fs.SampledBudgetHoursTotal,
		fs.SampledProjectionHoursTotal,

		hist.ActualYTDHoursTotal,
		hist.CurrentYearBudgetHoursTotal,
		hist.PriorYearActualHoursTotal,

		-- Target Montly Values
		fs.TargetAdjustedHours01,
		fs.TargetAdjustedHours02,
		fs.TargetAdjustedHours03,
		fs.TargetAdjustedHours04,
		fs.TargetAdjustedHours05,
		fs.TargetAdjustedHours06,
		fs.TargetAdjustedHours07,
		fs.TargetAdjustedHours08,
		fs.TargetAdjustedHours09,
		fs.TargetAdjustedHours10,
		fs.TargetAdjustedHours11,
		fs.TargetAdjustedHours12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedHours01,
		fs.BudgetAdjustedHours02,
		fs.BudgetAdjustedHours03,
		fs.BudgetAdjustedHours04,
		fs.BudgetAdjustedHours05,
		fs.BudgetAdjustedHours06,
		fs.BudgetAdjustedHours07,
		fs.BudgetAdjustedHours08,
		fs.BudgetAdjustedHours09,
		fs.BudgetAdjustedHours10,
		fs.BudgetAdjustedHours11,
		fs.BudgetAdjustedHours12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedHours01,
		fs.ProjectionAdjustedHours02,
		fs.ProjectionAdjustedHours03,
		fs.ProjectionAdjustedHours04,
		fs.ProjectionAdjustedHours05,
		fs.ProjectionAdjustedHours06,
		fs.ProjectionAdjustedHours07,
		fs.ProjectionAdjustedHours08,
		fs.ProjectionAdjustedHours09,
		fs.ProjectionAdjustedHours10,
		fs.ProjectionAdjustedHours11,
		fs.ProjectionAdjustedHours12,

		-- Initial Hours
		fs.InitialBudgetHours01,
		fs.InitialBudgetHours02,
		fs.InitialBudgetHours03,
		fs.InitialBudgetHours04,
		fs.InitialBudgetHours05,
		fs.InitialBudgetHours06,
		fs.InitialBudgetHours07,
		fs.InitialBudgetHours08,
		fs.InitialBudgetHours09,
		fs.InitialBudgetHours10,
		fs.InitialBudgetHours11,
		fs.InitialBudgetHours12,
		
		-- Sampled Hours
		fs.SampledBudgetHours01,
		fs.SampledBudgetHours02,
		fs.SampledBudgetHours03,
		fs.SampledBudgetHours04,
		fs.SampledBudgetHours05,
		fs.SampledBudgetHours06,
		fs.SampledBudgetHours07,
		fs.SampledBudgetHours08,
		fs.SampledBudgetHours09,
		fs.SampledBudgetHours10,
		fs.SampledBudgetHours11,
		fs.SampledBudgetHours12,
		
		-- Sampled Projection Hours
		fs.SampledProjectionHours01,
		fs.SampledProjectionHours02,
		fs.SampledProjectionHours03,
		fs.SampledProjectionHours04,
		fs.SampledProjectionHours05,
		fs.SampledProjectionHours06,
		fs.SampledProjectionHours07,
		fs.SampledProjectionHours08,
		fs.SampledProjectionHours09,
		fs.SampledProjectionHours10,
		fs.SampledProjectionHours11,
		fs.SampledProjectionHours12,

		-- ActualYTD Hours
		hist.ActualYTDHours01,
		hist.ActualYTDHours02,
		hist.ActualYTDHours03,
		hist.ActualYTDHours04,
		hist.ActualYTDHours05,
		hist.ActualYTDHours06,
		hist.ActualYTDHours07,
		hist.ActualYTDHours08,
		hist.ActualYTDHours09,
		hist.ActualYTDHours10,
		hist.ActualYTDHours11,
		hist.ActualYTDHours12,

		-- CurrentYearBudget Hours
		hist.CurrentYearBudgetHours01,
		hist.CurrentYearBudgetHours02,
		hist.CurrentYearBudgetHours03,
		hist.CurrentYearBudgetHours04,
		hist.CurrentYearBudgetHours05,
		hist.CurrentYearBudgetHours06,
		hist.CurrentYearBudgetHours07,
		hist.CurrentYearBudgetHours08,
		hist.CurrentYearBudgetHours09,
		hist.CurrentYearBudgetHours10,
		hist.CurrentYearBudgetHours11,
		hist.CurrentYearBudgetHours12,

		-- PriorYearActual Hours
		hist.PriorYearActualHours01,
		hist.PriorYearActualHours02,
		hist.PriorYearActualHours03,
		hist.PriorYearActualHours04,
		hist.PriorYearActualHours05,
		hist.PriorYearActualHours06,
		hist.PriorYearActualHours07,
		hist.PriorYearActualHours08,
		hist.PriorYearActualHours09,
		hist.PriorYearActualHours10,
		hist.PriorYearActualHours11,
		hist.PriorYearActualHours12,

		-- Target Percent Adjustment Factor Values
		fs.TargetHoursPercentAdjustmentFactor01,
		fs.TargetHoursPercentAdjustmentFactor02,
		fs.TargetHoursPercentAdjustmentFactor03,
		fs.TargetHoursPercentAdjustmentFactor04,
		fs.TargetHoursPercentAdjustmentFactor05,
		fs.TargetHoursPercentAdjustmentFactor06,
		fs.TargetHoursPercentAdjustmentFactor07,
		fs.TargetHoursPercentAdjustmentFactor08,
		fs.TargetHoursPercentAdjustmentFactor09,
		fs.TargetHoursPercentAdjustmentFactor10,
		fs.TargetHoursPercentAdjustmentFactor11,
		fs.TargetHoursPercentAdjustmentFactor12,

		-- Budgeted Percent Adjustment Factor Values
		fs.BudgetHoursPercentAdjustmentFactor01,
		fs.BudgetHoursPercentAdjustmentFactor02,
		fs.BudgetHoursPercentAdjustmentFactor03,
		fs.BudgetHoursPercentAdjustmentFactor04,
		fs.BudgetHoursPercentAdjustmentFactor05,
		fs.BudgetHoursPercentAdjustmentFactor06,
		fs.BudgetHoursPercentAdjustmentFactor07,
		fs.BudgetHoursPercentAdjustmentFactor08,
		fs.BudgetHoursPercentAdjustmentFactor09,
		fs.BudgetHoursPercentAdjustmentFactor10,
		fs.BudgetHoursPercentAdjustmentFactor11,
		fs.BudgetHoursPercentAdjustmentFactor12,

		-- Projected Percent Adjustment Factor Values
		fs.ProjectionHoursPercentAdjustmentFactor01,
		fs.ProjectionHoursPercentAdjustmentFactor02,
		fs.ProjectionHoursPercentAdjustmentFactor03,
		fs.ProjectionHoursPercentAdjustmentFactor04,
		fs.ProjectionHoursPercentAdjustmentFactor05,
		fs.ProjectionHoursPercentAdjustmentFactor06,
		fs.ProjectionHoursPercentAdjustmentFactor07,
		fs.ProjectionHoursPercentAdjustmentFactor08,
		fs.ProjectionHoursPercentAdjustmentFactor09,
		fs.ProjectionHoursPercentAdjustmentFactor10,
		fs.ProjectionHoursPercentAdjustmentFactor11,
		fs.ProjectionHoursPercentAdjustmentFactor12
	FROM [fp].[Staffing] fs (READUNCOMMITTED)
		INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID
GO


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

-- fp.viewStaffingInitialPlanConfigDetailLogs
CREATE VIEW [fp].[viewStaffingInitialPlanConfigDetailLogs]  
 AS
/*******************************************************************************
    ** Change History
    ********************************************************************************
    ** CID  Date        Author  WI              Description
	 ** 1	04-03-2024    NT      JAZZ-61357      Initial Creation
*******************************************************************************/

 SELECT
	RowID,
	BudgetConfigGUID,
	BudgetConfigID,
	DepartmentID,
	JobCodeID,
	ProductiveClassID,
	PayCodeGroupID,
	VariabilityID,
	TimeClassID,
	UnitTypeID,
	EmployeeID,
	ProviderID,
	ProviderLineItemID,
	ProviderTypeID,
	ProviderSpecialtyID,
	ProjectionMethodID,
	TrailingMonths,
	VersionID
FROM
	[fp].[StaffingInitialPlanConfigDetail]
UNION 
 SELECT
	RowID,
	BudgetConfigGUID,
	BudgetConfigID,
	DepartmentID,
	JobCodeID,
	ProductiveClassID,
	PayCodeGroupID,
	VariabilityID,
	TimeClassID,
	UnitTypeID,
	EmployeeID,
	ProviderID,
	ProviderLineItemID,
	ProviderTypeID,
	ProviderSpecialtyID,
	ProjectionMethodID,
	TrailingMonths,
	VersionID
FROM
	[fp].[StaffingInitialPlanConfigDetailHistory]
GO


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

-- fp.viewStaffingManagerAdjustmentComments
CREATE VIEW [fp].[viewStaffingManagerAdjustmentComments]
AS
SELECT
ROW_NUMBER() OVER(ORDER BY DepartmentID ASC) AS RowID,
bc.BudgetConfigID,
sc.DepartmentID,
sc.JobCodeID,
sc.FiscalYearID,
sc.UnitTypeID,
sc.Comment,
sc.InitialValue,
sc.DeltaValue AS Adjustment,
sc.InitialValue + sc.DeltaValue AS FinalValue,
sc.DateCreatedUtc,
sc.AuthorFullName,
sc.DateModifiedUtc,
0 AS VariabilityID,
'Not Specified' AS AdjustedLevel,
CAST(sc.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateCreated,
CAST(sc.DateModifiedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateModified,
dc.CalendarDateTime AS DateCreatedDate
FROM fp.StaffingManagerAdjustmentComment AS sc 
INNER JOIN fp.BudgetConfig AS bc ON bc.BudgetConfigGUID = sc.BudgetConfigGUID
INNER JOIN [fw].[DimDate] AS dc ON CAST(sc.DateCreatedUtc AS DATE) = dc.CalendarDateTime

UNION ALL

SELECT
ROW_NUMBER() OVER(ORDER BY DepartmentID ASC) AS RowID,
bc.BudgetConfigID,
sc.DepartmentID,
sc.JobCodeID,
sc.FiscalYearID,
sc.UnitTypeID,
sc.Comment,
sc.InitialValue,
sc.Value - sc.InitialValue AS Adjustment,
sc.Value AS FinalValue,
sc.DateCreatedUtc,
sc.AuthorFullName,
sc.DateModifiedUtc,
sc.VariabilityID,
(SELECT ISNULL(STRING_AGG(AdjustedLevel, ', '), '') FROM OPENJSON(AdjustedLevelInfoJSON) WITH ( AdjustedLevel NVARCHAR(MAX) '$.Text')) AS AdjustedLevel,
CAST(sc.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateCreated,
CAST(sc.DateModifiedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateModified,
dc.CalendarDateTime AS DateCreatedDate
FROM fp.StaffingManagerSetAdjustmentComment AS sc 
INNER JOIN fp.BudgetConfig AS bc ON bc.BudgetConfigID = sc.BudgetConfigID
INNER JOIN [fw].[DimDate] AS dc ON CAST(sc.DateCreatedUtc AS DATE) = dc.CalendarDateTime
GO


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

-- fp.viewStaffingRate
CREATE   VIEW [fp].[viewStaffingRate]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-02-21  MY  	 JAZZ-XXX		Initial
 *************************************************************/

	SELECT
		fs.StaffingID,
		fs.StaffingWageRateID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.FlexingTypeID,
		fs.FixedVariabilityPercentage,
		fs.IsNew,
		fs.AddDate,

		-- Target Montly Values
		fs.TargetAdjustedRate01,
		fs.TargetAdjustedRate02,
		fs.TargetAdjustedRate03,
		fs.TargetAdjustedRate04,
		fs.TargetAdjustedRate05,
		fs.TargetAdjustedRate06,
		fs.TargetAdjustedRate07,
		fs.TargetAdjustedRate08,
		fs.TargetAdjustedRate09,
		fs.TargetAdjustedRate10,
		fs.TargetAdjustedRate11,
		fs.TargetAdjustedRate12,

		-- Budgeted Monthly Values
		fs.BudgetAdjustedRate01,
		fs.BudgetAdjustedRate02,
		fs.BudgetAdjustedRate03,
		fs.BudgetAdjustedRate04,
		fs.BudgetAdjustedRate05,
		fs.BudgetAdjustedRate06,
		fs.BudgetAdjustedRate07,
		fs.BudgetAdjustedRate08,
		fs.BudgetAdjustedRate09,
		fs.BudgetAdjustedRate10,
		fs.BudgetAdjustedRate11,
		fs.BudgetAdjustedRate12,

		-- Projected Monthly Values
		fs.ProjectionAdjustedRate01,
		fs.ProjectionAdjustedRate02,
		fs.ProjectionAdjustedRate03,
		fs.ProjectionAdjustedRate04,
		fs.ProjectionAdjustedRate05,
		fs.ProjectionAdjustedRate06,
		fs.ProjectionAdjustedRate07,
		fs.ProjectionAdjustedRate08,
		fs.ProjectionAdjustedRate09,
		fs.ProjectionAdjustedRate10,
		fs.ProjectionAdjustedRate11,
		fs.ProjectionAdjustedRate12,

		-- Initial Rate
		fs.InitialBudgetRate01,
		fs.InitialBudgetRate02,
		fs.InitialBudgetRate03,
		fs.InitialBudgetRate04,
		fs.InitialBudgetRate05,
		fs.InitialBudgetRate06,
		fs.InitialBudgetRate07,
		fs.InitialBudgetRate08,
		fs.InitialBudgetRate09,
		fs.InitialBudgetRate10,
		fs.InitialBudgetRate11,
		fs.InitialBudgetRate12
	FROM [fp].[Staffing] fs (READUNCOMMITTED)
GO


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

-- fp.viewStaffingSpreadUnlockData
CREATE VIEW fp.viewStaffingSpreadUnlockData 
AS   

SELECT [RowID]
      ,[BudgetConfigID]
      ,[AdjustmentGUID]
      ,[EntityID]
      ,[DepartmentID]
      ,[JobCodeID]
      ,[PayCodeGroupID]
      ,[ProductiveClassID]
      ,[UnitTypeID]
      ,[Version]
      ,[Value01]
      ,[Value02]
      ,[Value03]
      ,[Value04]
      ,[Value05]
      ,[Value06]
      ,[Value07]
      ,[Value08]
      ,[Value09]
      ,[Value10]
      ,[Value11]
      ,[Value12]
      ,[IsRecordDeleted]
      ,[EmployeeID]      
      ,[ProviderID]      
      ,[ProviderTypeID]      
      ,[ProviderSpecialtyID]      
      ,[ProviderLineItemID]      
FROM [fp].[StaffingSpreadUnlockData]   
WHERE IsRecordDeleted = 0
GO


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

-- fp.viewStaffingSpreads
CREATE VIEW fp.viewStaffingSpreads
AS
	SELECT [BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID]
	FROM [fp].[StaffingSpreads] gls with (readuncommitted)
	WHERE GlobalSpreadID = 1

	UNION ALL

	SELECT gls.[BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, gls.[GlobalSpreadID]
	FROM [fp].[StaffingSpreads] gls with (readuncommitted)
		 INNER JOIN [fp].[GlobalSpread] gs
		 	ON gls.GlobalSpreadID = gs.GlobalSpreadID
	WHERE gls.GlobalSpreadID > 1
GO


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

-- fp.viewStaffingTotals
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	10-9-2023  MY      JAZZ-61365		Restructure Update
*************************************************************/
CREATE   VIEW [fp].[viewStaffingTotals]
AS
	SELECT
		fs.StaffingID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		34 AS UnitTypeID,
		3 AS BudgetPhaseID, -- Not sure why this is on here when we then break it out by phase??? Will look later
		BudgetDollarsLockType as BudgetLockType,
		BudgetDollarsLockFlag as BudgetLockFlag,
		ProjectionDollarsLockType as ProjectionLockType,
		ProjectionDollarsLockFlag as ProjectionLockFlag,
		fs.SampledBudgetDollarsTotal AS SampledBudgetTotal,
		fs.InitialBudgetDollarsTotal AS InitialBudgetTotal,
		fs.SampledProjectionDollarsTotal AS SampledProjectionTotal,
		fs.InitialProjectionDollarsTotal AS InitialProjectionTotal,
		fs.TargetAdjustedDollarsTotal AS AdjustedValueTotal,
		fs.TargetAdjustedDollarsTotal AS FlexedValueTotal,
		fs.ProjectionAdjustedDollarsTotal AS AdjustedProjectionValueTotal,
		fs.ProjectionAdjustedDollarsTotal AS FlexedProjectionValueTotal,
		fs.BudgetAdjustedDollarsTotal as ManagerAdjustedValueTotal,
		fs.BudgetAdjustedDollarsTotal as ManagerFlexedValueTotal,
		fs.ProjectionAdjustedDollarsTotal as ManagerAdjustedProjectionValueTotal,
		fs.ProjectionAdjustedDollarsTotal as ManagerFlexedProjectionValueTotal,
		COALESCE(hist.PriorYearActualDollarsTotal, 0) as PriorYearActualValueTotal,
		COALESCE(hist.ActualYTDDollarsTotal, 0) as ActualYTDValueTotal,
		COALESCE(hist.CurrentYearBudgetDollarsTotal, 0) as CurrentYearBudgetTotal,
		wh.MonthYearly as WorkingHours,
		histHours.MonthYearly as HistoricalWorkingHours,
		fs.FixedVariabilityPercentage
	FROM [fp].[Staffing] fs
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
		INNER JOIN [fw].[DimEmployee] e on fs.EmployeeID = e.EmployeeID
		INNER JOIN [fw].[DimDepartment] d on fs.DepartmentID = d.DepartmentID
		INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID
		LEFT JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = bc.FiscalYearID
			AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
		LEFT JOIN [client].[FactWorkingHoursPerMonth] histHours ON histHours.FiscalYearID = (bc.FiscalYearID  - 1)
			AND histHours.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
	UNION ALL
	SELECT
		fs.StaffingID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		fs.VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		51 AS UnitTypeID,
		3 AS BudgetPhaseID, -- Not sure why this is on here when we then break it out by phase??? Will look later
		BudgetHoursLockType as BudgetLockType,
		BudgetHoursLockFlag as BudgetLockFlag,
		ProjectionHoursLockType as ProjectionLockType,
		ProjectionHoursLockFlag as ProjectionLockFlag,
		fs.SampledBudgetHoursTotal AS SampledBudgetTotal,
		fs.InitialBudgetHoursTotal AS InitialBudgetTotal,
		fs.SampledProjectionHoursTotal AS SampledProjectionTotal,
		fs.InitialProjectionHoursTotal AS InitialProjectionTotal,
		fs.TargetAdjustedHoursTotal AS AdjustedValueTotal,
		fs.TargetAdjustedHoursTotal AS FlexedValueTotal,
		fs.ProjectionAdjustedHoursTotal AS AdjustedProjectionValueTotal,
		fs.ProjectionAdjustedHoursTotal AS FlexedProjectionValueTotal,
		fs.BudgetAdjustedHoursTotal as ManagerAdjustedValueTotal,
		fs.BudgetAdjustedHoursTotal as ManagerFlexedValueTotal,
		fs.ProjectionAdjustedHoursTotal as ManagerAdjustedProjectionValueTotal,
		fs.ProjectionAdjustedHoursTotal as ManagerFlexedProjectionValueTotal,
		COALESCE(hist.PriorYearActualHoursTotal, 0) as PriorYearActualValueTotal,
		COALESCE(hist.ActualYTDHoursTotal, 0) as ActualYTDValueTotal,
		COALESCE(hist.CurrentYearBudgetHoursTotal, 0) as CurrentYearBudgetTotal,
		wh.MonthYearly as WorkingHours,
		histHours.MonthYearly as HistoricalWorkingHours,
		fs.FixedVariabilityPercentage
	FROM [fp].[Staffing] fs
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
		INNER JOIN [fw].[DimEmployee] e on fs.EmployeeID = e.EmployeeID
		INNER JOIN [fw].[DimDepartment] d on fs.DepartmentID = d.DepartmentID
		INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID
		LEFT JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = bc.FiscalYearID
			AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
		LEFT JOIN [client].[FactWorkingHoursPerMonth] histHours ON histHours.FiscalYearID = (bc.FiscalYearID  - 1)
			AND histHours.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
	-- Excluding FTEs and Wage Rate, because they cannot be summed up across months and must be calculated, if we need to end up pulling them in I can
	-- however, the values coming in before the restructure were wrong so I'm guessing they weren't used
GO


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

-- fp.viewStaffingTotalsFixed_FromStaffing
CREATE VIEW  [fp].[viewStaffingTotalsFixed_FromStaffing]
 AS
 /**************************************************************
** Change History
**************************************************************
** CID  Date		Author		 WI			 Description
** 1	2023-10-23	NT		JAZZ-61396 This is a replacement for viewFactStaffingTotalsFixed_FromFactStaffing as part of
											 Staffing Restructure
*************************************************************/
SELECT
	[StaffingID],
	[BudgetConfigID],
	fs.[EntityGroupConfigID],
	[EntityID],
	[DepartmentID],
	[JobCodeID],
	[PayCodeGroupID],
	[ProductiveClassID],
	[VariabilityID], 
	[EmployeeID],
	[ProviderID],
	[ProviderTypeID],
	[ProviderSpecialtyID],
	[ProviderLineItemID],
	[SubsectionID],
	[UnitTypeID],
	[BudgetPhaseID],
	[BudgetLockType], 
	[BudgetLockFlag],
	[ProjectionLockType],
	[ProjectionLockFlag],
	[SampledBudgetTotal],
	[InitialBudgetTotal],
	[SampledProjectionTotal],
	[InitialProjectionTotal], 
	[AdjustedValueTotal],
	[FlexedValueTotal],
	[AdjustedProjectionValueTotal],
	[FlexedProjectionValueTotal],
	[ManagerAdjustedValueTotal],
	[ManagerFlexedValueTotal], 
	[ManagerAdjustedProjectionValueTotal],
	[ManagerFlexedProjectionValueTotal],
	[PriorYearActualValueTotal],
	[ActualYTDValueTotal],
	[CurrentYearBudgetTotal], 
	[WorkingHours],
	[HistoricalWorkingHours], 
	[FixedVariabilityPercentage]
FROM
	fp.viewStaffingTotals fs
INNER JOIN [fp].[EntityGroupConfig] AS egc ON
	egc.EntityGroupConfigID = fs.EntityGroupConfigID
WHERE
	fs.FixedVariabilityPercentage = 1
GO


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

-- fp.viewStaffingVariability
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2022-04-28	MY		JAZZ-28395	Cache Variability Percentage on FactStaffing
** 2	2022-10-18	MD		JAZZ-44889	Add EGC ID to view
** 3	2022-11-07  MY      JAZZ-35951	Add EmployeeID to FactStaffingVariabilityDetail
** 4	2023-10-09  MY      JAZZ-61365	Upgrade to new structure
*************************************************************/
CREATE   VIEW [fp].[viewStaffingVariability]
AS
SELECT DISTINCT
	pv.BudgetConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.SubsectionID,
	pv.DepartmentID, 
	pv.ProviderLineItemID,
	pv.JobCodeID,
	pv.PayCodeGroupID,
	pv.EmployeeID,
	pv.EntityGroupConfigID,
	ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage
FROM [fp].[Staffing] pv
	INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID
WHERE pv.VariabilityID = 2
GROUP BY pv.BudgetConfigID, 
	pv.EntityGroupConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.SubsectionID,
	pv.DepartmentID, 
	pv.JobCodeID,
	pv.ProviderLineItemID,
	pv.PayCodeGroupID,
	pv.EmployeeID
GO


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

-- fp.viewStaffingVariabilityWithoutPayCodeGroup
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2022-04-28	MY		JAZZ-28395	Cache Variability Percentage on FactStaffing
** 2	2022-08-22	MY		JAZZ-40590	Exclude Dollars Only PCG
** 3	11-7-2022   MY      JAZZ-35951	Add EmployeeID to FactStaffingVariabilityDetail
** 4	10-10-2023  MY      JAZZ-61397	Update Staffing/Provider Comp adjustments to support data model changes
*************************************************************/
CREATE   VIEW [fp].[viewStaffingVariabilityWithoutPayCodeGroup]
AS
SELECT DISTINCT
	bc.BudgetConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.DepartmentID, 
	pv.JobCodeID, -- Eventually need to add PayCodeGroup level here for when ABB clients use this.
	pv.EmployeeID,
	ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage
FROM [fp].[Staffing] pv
	INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID
	INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
	INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID
WHERE pv.ProviderLineItemID = 0 -- Filtering out Provider Line Item lvl variability because they don't have manager adjustments. 
	AND pv.VariabilityID = 2
	AND pv.ProductiveClassID != 4 -- Exclude Dollars as these are always fixed
GROUP BY bc.BudgetConfigID, 
	pv.EntityGroupConfigID, 
	egc.EntityGroupConfigGUID, 
	dd.EntityID, 
	pv.DepartmentID, 
	pv.JobCodeID,
	pv.EmployeeID
GO


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

-- fp.viewStaffingWageRate
CREATE   VIEW [fp].[viewStaffingWageRate]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-02-21  MY  	 JAZZ-XXX		Initial
 *************************************************************/

	SELECT
		fs.StaffingID,
		fs.StaffingWageRateID,
		fs.BudgetConfigID,
		fs.EntityGroupConfigID,
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProductiveClassID,
		3 AS VariabilityID,
		fs.EmployeeID,
		fs.ProviderID,
		fs.ProviderTypeID,
		fs.ProviderSpecialtyID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.FlexingTypeID,
		fs.FixedVariabilityPercentage,
		fs.IsNew,
		fs.AddDate,

		wr.TargetWageRateLockType,
		wr.TargetWageRateLockFlag,
		wr.BudgetWageRateLockType,
		wr.BudgetWageRateLockFlag,
		wr.ProjectionWageRateLockType,
		wr.ProjectionWageRateLockFlag,

		-- Target Montly Values
		wr.TargetAdjusted01,
		wr.TargetAdjusted02,
		wr.TargetAdjusted03,
		wr.TargetAdjusted04,
		wr.TargetAdjusted05,
		wr.TargetAdjusted06,
		wr.TargetAdjusted07,
		wr.TargetAdjusted08,
		wr.TargetAdjusted09,
		wr.TargetAdjusted10,
		wr.TargetAdjusted11,
		wr.TargetAdjusted12,

		-- Budgeted Monthly Values
		wr.BudgetAdjusted01,
		wr.BudgetAdjusted02,
		wr.BudgetAdjusted03,
		wr.BudgetAdjusted04,
		wr.BudgetAdjusted05,
		wr.BudgetAdjusted06,
		wr.BudgetAdjusted07,
		wr.BudgetAdjusted08,
		wr.BudgetAdjusted09,
		wr.BudgetAdjusted10,
		wr.BudgetAdjusted11,
		wr.BudgetAdjusted12,

		-- Projected Monthly Values
		wr.ProjectionAdjusted01,
		wr.ProjectionAdjusted02,
		wr.ProjectionAdjusted03,
		wr.ProjectionAdjusted04,
		wr.ProjectionAdjusted05,
		wr.ProjectionAdjusted06,
		wr.ProjectionAdjusted07,
		wr.ProjectionAdjusted08,
		wr.ProjectionAdjusted09,
		wr.ProjectionAdjusted10,
		wr.ProjectionAdjusted11,
		wr.ProjectionAdjusted12,

		-- Initial 
		wr.InitialBudget01,
		wr.InitialBudget02,
		wr.InitialBudget03,
		wr.InitialBudget04,
		wr.InitialBudget05,
		wr.InitialBudget06,
		wr.InitialBudget07,
		wr.InitialBudget08,
		wr.InitialBudget09,
		wr.InitialBudget10,
		wr.InitialBudget11,
		wr.InitialBudget12,
		
		-- Sampled 
		wr.SampledBudget01,
		wr.SampledBudget02,
		wr.SampledBudget03,
		wr.SampledBudget04,
		wr.SampledBudget05,
		wr.SampledBudget06,
		wr.SampledBudget07,
		wr.SampledBudget08,
		wr.SampledBudget09,
		wr.SampledBudget10,
		wr.SampledBudget11,
		wr.SampledBudget12,
		
		-- Sampled Projection 
		wr.SampledProjection01,
		wr.SampledProjection02,
		wr.SampledProjection03,
		wr.SampledProjection04,
		wr.SampledProjection05,
		wr.SampledProjection06,
		wr.SampledProjection07,
		wr.SampledProjection08,
		wr.SampledProjection09,
		wr.SampledProjection10,
		wr.SampledProjection11,
		wr.SampledProjection12,

		-- Target Percent Adjustment Factor Values
		wr.TargetPercentAdjustmentFactor01,
		wr.TargetPercentAdjustmentFactor02,
		wr.TargetPercentAdjustmentFactor03,
		wr.TargetPercentAdjustmentFactor04,
		wr.TargetPercentAdjustmentFactor05,
		wr.TargetPercentAdjustmentFactor06,
		wr.TargetPercentAdjustmentFactor07,
		wr.TargetPercentAdjustmentFactor08,
		wr.TargetPercentAdjustmentFactor09,
		wr.TargetPercentAdjustmentFactor10,
		wr.TargetPercentAdjustmentFactor11,
		wr.TargetPercentAdjustmentFactor12,

		-- Budgeted Percent Adjustment Factor Values
		wr.BudgetPercentAdjustmentFactor01,
		wr.BudgetPercentAdjustmentFactor02,
		wr.BudgetPercentAdjustmentFactor03,
		wr.BudgetPercentAdjustmentFactor04,
		wr.BudgetPercentAdjustmentFactor05,
		wr.BudgetPercentAdjustmentFactor06,
		wr.BudgetPercentAdjustmentFactor07,
		wr.BudgetPercentAdjustmentFactor08,
		wr.BudgetPercentAdjustmentFactor09,
		wr.BudgetPercentAdjustmentFactor10,
		wr.BudgetPercentAdjustmentFactor11,
		wr.BudgetPercentAdjustmentFactor12,

		-- Projected Percent Adjustment Factor Values
		wr.ProjectionPercentAdjustmentFactor01,
		wr.ProjectionPercentAdjustmentFactor02,
		wr.ProjectionPercentAdjustmentFactor03,
		wr.ProjectionPercentAdjustmentFactor04,
		wr.ProjectionPercentAdjustmentFactor05,
		wr.ProjectionPercentAdjustmentFactor06,
		wr.ProjectionPercentAdjustmentFactor07,
		wr.ProjectionPercentAdjustmentFactor08,
		wr.ProjectionPercentAdjustmentFactor09,
		wr.ProjectionPercentAdjustmentFactor10,
		wr.ProjectionPercentAdjustmentFactor11,
		wr.ProjectionPercentAdjustmentFactor12
	FROM [fp].[Staffing] fs (READUNCOMMITTED)
		INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) ON fs.StaffingWageRateID = wr.StaffingWageRateID
	WHERE fs.VariabilityID = 1 -- Filtering so we only get 1 row
GO


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

-- fp.viewStaffing_DepartmentManager
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2023-10-10  MY      JAZZ-61397		Update Staffing/Provider Comp adjustments to support data model changes
** 2	2024-02-16  BK      JAZZ-67683		Change WageRate VariabilityID to 3 instead of 1
*************************************************************/
CREATE   VIEW [fp].[viewStaffing_DepartmentManager]
AS
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		34 AS UnitTypeID,
		2 as TimeClassID,
		bc.FiscalYearID,
		m.FiscalMonthID,
		staff.TargetDollarsLockFlag AS HasFinalValueAdjustment,
		Target AS Value,
		Budget AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, TargetAdjustedDollars01, BudgetAdjustedDollars01),
				(02, TargetAdjustedDollars02, BudgetAdjustedDollars02),
				(03, TargetAdjustedDollars03, BudgetAdjustedDollars03),
				(04, TargetAdjustedDollars04, BudgetAdjustedDollars04),
				(05, TargetAdjustedDollars05, BudgetAdjustedDollars05),
				(06, TargetAdjustedDollars06, BudgetAdjustedDollars06),
				(07, TargetAdjustedDollars07, BudgetAdjustedDollars07),
				(08, TargetAdjustedDollars08, BudgetAdjustedDollars08),
				(09, TargetAdjustedDollars09, BudgetAdjustedDollars09),
				(10, TargetAdjustedDollars10, BudgetAdjustedDollars10),
				(11, TargetAdjustedDollars11, BudgetAdjustedDollars11),
				(12, TargetAdjustedDollars12, BudgetAdjustedDollars12)		
		) AS CrossApplied (MonthSortOrder, Target, Budget)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		51 AS UnitTypeID,
		2 as TimeClassID,
		bc.FiscalYearID,
		m.FiscalMonthID,
		staff.TargetHoursLockFlag AS HasFinalValueAdjustment,
		Target AS Value,
		Budget AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, TargetAdjustedHours01, BudgetAdjustedHours01),
				(02, TargetAdjustedHours02, BudgetAdjustedHours02),
				(03, TargetAdjustedHours03, BudgetAdjustedHours03),
				(04, TargetAdjustedHours04, BudgetAdjustedHours04),
				(05, TargetAdjustedHours05, BudgetAdjustedHours05),
				(06, TargetAdjustedHours06, BudgetAdjustedHours06),
				(07, TargetAdjustedHours07, BudgetAdjustedHours07),
				(08, TargetAdjustedHours08, BudgetAdjustedHours08),
				(09, TargetAdjustedHours09, BudgetAdjustedHours09),
				(10, TargetAdjustedHours10, BudgetAdjustedHours10),
				(11, TargetAdjustedHours11, BudgetAdjustedHours11),
				(12, TargetAdjustedHours12, BudgetAdjustedHours12)		
		) AS CrossApplied (MonthSortOrder, Target, Budget)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		144 AS UnitTypeID,
		2 as TimeClassID,
		bc.FiscalYearID,
		m.FiscalMonthID,
		staff.TargetFTEsLockFlag AS HasFinalValueAdjustment,
		Target AS Value,
		Budget AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, TargetAdjustedFTEs01, BudgetAdjustedFTEs01),
				(02, TargetAdjustedFTEs02, BudgetAdjustedFTEs02),
				(03, TargetAdjustedFTEs03, BudgetAdjustedFTEs03),
				(04, TargetAdjustedFTEs04, BudgetAdjustedFTEs04),
				(05, TargetAdjustedFTEs05, BudgetAdjustedFTEs05),
				(06, TargetAdjustedFTEs06, BudgetAdjustedFTEs06),
				(07, TargetAdjustedFTEs07, BudgetAdjustedFTEs07),
				(08, TargetAdjustedFTEs08, BudgetAdjustedFTEs08),
				(09, TargetAdjustedFTEs09, BudgetAdjustedFTEs09),
				(10, TargetAdjustedFTEs10, BudgetAdjustedFTEs10),
				(11, TargetAdjustedFTEs11, BudgetAdjustedFTEs11),
				(12, TargetAdjustedFTEs12, BudgetAdjustedFTEs12)		
		) AS CrossApplied (MonthSortOrder, Target, Budget)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		CASE WHEN staff.SubsectionID = 3 THEN 172 ELSE 33 END AS UnitTypeID,
		2 as TimeClassID,
		bc.FiscalYearID,
		m.FiscalMonthID,
		0 AS HasFinalValueAdjustment,
		Target AS Value,
		Budget AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, TargetAdjustedRate01, BudgetAdjustedRate01),
				(02, TargetAdjustedRate02, BudgetAdjustedRate02),
				(03, TargetAdjustedRate03, BudgetAdjustedRate03),
				(04, TargetAdjustedRate04, BudgetAdjustedRate04),
				(05, TargetAdjustedRate05, BudgetAdjustedRate05),
				(06, TargetAdjustedRate06, BudgetAdjustedRate06),
				(07, TargetAdjustedRate07, BudgetAdjustedRate07),
				(08, TargetAdjustedRate08, BudgetAdjustedRate08),
				(09, TargetAdjustedRate09, BudgetAdjustedRate09),
				(10, TargetAdjustedRate10, BudgetAdjustedRate10),
				(11, TargetAdjustedRate11, BudgetAdjustedRate11),
				(12, TargetAdjustedRate12, BudgetAdjustedRate12)		
		) AS CrossApplied (MonthSortOrder, Target, Budget)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		34 AS UnitTypeID,
		12 as TimeClassID,
		bc.FiscalYearID - 1AS FiscalYearID,
		m.FiscalMonthID,
		staff.ProjectionDollarsLockFlag AS HasFinalValueAdjustment,
		Projection AS Value,
		Projection AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, ProjectionAdjustedDollars01),
				(02, ProjectionAdjustedDollars02),
				(03, ProjectionAdjustedDollars03),
				(04, ProjectionAdjustedDollars04),
				(05, ProjectionAdjustedDollars05),
				(06, ProjectionAdjustedDollars06),
				(07, ProjectionAdjustedDollars07),
				(08, ProjectionAdjustedDollars08),
				(09, ProjectionAdjustedDollars09),
				(10, ProjectionAdjustedDollars10),
				(11, ProjectionAdjustedDollars11),
				(12, ProjectionAdjustedDollars12)		
		) AS CrossApplied (MonthSortOrder, Projection)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		51 AS UnitTypeID,
		12 as TimeClassID,
		bc.FiscalYearID - 1 AS FiscalYearID,
		m.FiscalMonthID,
		staff.ProjectionHoursLockFlag AS HasFinalValueAdjustment,
		Projection AS Value,
		Projection AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, ProjectionAdjustedHours01),
				(02, ProjectionAdjustedHours02),
				(03, ProjectionAdjustedHours03),
				(04, ProjectionAdjustedHours04),
				(05, ProjectionAdjustedHours05),
				(06, ProjectionAdjustedHours06),
				(07, ProjectionAdjustedHours07),
				(08, ProjectionAdjustedHours08),
				(09, ProjectionAdjustedHours09),
				(10, ProjectionAdjustedHours10),
				(11, ProjectionAdjustedHours11),
				(12, ProjectionAdjustedHours12)		
		) AS CrossApplied (MonthSortOrder, Projection)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		144 AS UnitTypeID,
		12 as TimeClassID,
		bc.FiscalYearID - 1 AS FiscalYearID,
		m.FiscalMonthID,
		staff.ProjectionFTEsLockFlag AS HasFinalValueAdjustment,
		Projection AS Value,
		Projection AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, ProjectionAdjustedFTEs01),
				(02, ProjectionAdjustedFTEs02),
				(03, ProjectionAdjustedFTEs03),
				(04, ProjectionAdjustedFTEs04),
				(05, ProjectionAdjustedFTEs05),
				(06, ProjectionAdjustedFTEs06),
				(07, ProjectionAdjustedFTEs07),
				(08, ProjectionAdjustedFTEs08),
				(09, ProjectionAdjustedFTEs09),
				(10, ProjectionAdjustedFTEs10),
				(11, ProjectionAdjustedFTEs11),
				(12, ProjectionAdjustedFTEs12)		
		) AS CrossApplied (MonthSortOrder, Projection)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		staff.VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		CASE WHEN staff.SubsectionID = 3 THEN 172 ELSE 33 END AS UnitTypeID,
		12 as TimeClassID,
		bc.FiscalYearID - 1 AS FiscalYearID,
		m.FiscalMonthID,
		0 AS HasFinalValueAdjustment,
		Projection AS Value,
		Projection AS ManagerValue
	FROM fp.Staffing staff
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, ProjectionAdjustedRate01),
				(02, ProjectionAdjustedRate02),
				(03, ProjectionAdjustedRate03),
				(04, ProjectionAdjustedRate04),
				(05, ProjectionAdjustedRate05),
				(06, ProjectionAdjustedRate06),
				(07, ProjectionAdjustedRate07),
				(08, ProjectionAdjustedRate08),
				(09, ProjectionAdjustedRate09),
				(10, ProjectionAdjustedRate10),
				(11, ProjectionAdjustedRate11),
				(12, ProjectionAdjustedRate12)		
		) AS CrossApplied (MonthSortOrder, Projection)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		3 as VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		159 AS UnitTypeID,
		2 as TimeClassID,
		bc.FiscalYearID AS FiscalYearID,
		m.FiscalMonthID,
		swr.TargetWageRateLockFlag AS HasFinalValueAdjustment,
		Target AS Value,
		Budget AS ManagerValue
	FROM fp.StaffingWageRate swr
		INNER JOIN fp.Staffing staff ON swr.StaffingWageRateID = staff.StaffingWageRateID AND staff.VariabilityID = 1 -- Just doing this for 1 row since it'll be the same for both Fixed/Variable
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, TargetAdjusted01, BudgetAdjusted01),
				(02, TargetAdjusted02, BudgetAdjusted02),
				(03, TargetAdjusted03, BudgetAdjusted03),
				(04, TargetAdjusted04, BudgetAdjusted04),
				(05, TargetAdjusted05, BudgetAdjusted05),
				(06, TargetAdjusted06, BudgetAdjusted06),
				(07, TargetAdjusted07, BudgetAdjusted07),
				(08, TargetAdjusted08, BudgetAdjusted08),
				(09, TargetAdjusted09, BudgetAdjusted09),
				(10, TargetAdjusted10, BudgetAdjusted10),
				(11, TargetAdjusted11, BudgetAdjusted11),
				(12, TargetAdjusted12, BudgetAdjusted12)		
		) AS CrossApplied (MonthSortOrder, Target, Budget)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	UNION ALL
	SELECT
		staff.StaffingID,
		staff.BudgetConfigID,
		staff.EntityGroupConfigID,
		staff.EntityID,
		staff.DepartmentID,
		staff.JobCodeID,
		staff.PayCodeGroupID,
		staff.ProductiveClassID,
		3 as VariabilityID,
		staff.EmployeeID,
		staff.ProviderID,
		staff.ProviderTypeID,
		staff.ProviderSpecialtyID,
		staff.ProviderLineItemID,
		staff.SubsectionID,
		159 AS UnitTypeID,
		12 as TimeClassID,
		bc.FiscalYearID - 1AS FiscalYearID,
		m.FiscalMonthID,
		swr.ProjectionWageRateLockFlag AS HasFinalValueAdjustment,
		Projection AS Value,
		Projection AS ManagerValue
	FROM fp.StaffingWageRate swr
		INNER JOIN fp.Staffing staff ON swr.StaffingWageRateID = staff.StaffingWageRateID AND staff.VariabilityID = 1 -- Just doing this for 1 row since it'll be the same for both Fixed/Variable
		INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID
		CROSS APPLY (
			VALUES
				(01, ProjectionAdjusted01),
				(02, ProjectionAdjusted02),
				(03, ProjectionAdjusted03),
				(04, ProjectionAdjusted04),
				(05, ProjectionAdjusted05),
				(06, ProjectionAdjusted06),
				(07, ProjectionAdjusted07),
				(08, ProjectionAdjusted08),
				(09, ProjectionAdjusted09),
				(10, ProjectionAdjusted10),
				(11, ProjectionAdjusted11),
				(12, ProjectionAdjusted12)		
		) AS CrossApplied (MonthSortOrder, Projection)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
GO


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

-- fp.viewStaffing_Unpivoted
CREATE   VIEW [fp].[viewStaffing_Unpivoted]
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			    Description
 ** 1 	 2023-11-16  BW  	 JAZZ-60740		Data model restructure
 *************************************************************/

SELECT staff.StaffingID,
       staff.BudgetConfigID,
       staff.EntityGroupConfigID,
       staff.EntityID,
       staff.DepartmentID,
       staff.JobCodeID,
       staff.PayCodeGroupID,
       staff.ProductiveClassID,
       staff.VariabilityID,
       staff.EmployeeID,
       staff.ProviderID,
       staff.ProviderTypeID,
       staff.ProviderSpecialtyID,
       staff.ProviderLineItemID,
       staff.SubsectionID,
       staff.FlexingTypeID,
       ut.UnitTypeID,
       TargetLockType,
       TargetLockFlag,
       BudgetLockType,
       BudgetLockFlag,
       ProjectionLockType,
       ProjectionLockFlag,
       BudgetSpreadsLockFlag,
       BudgetAdjustmentLockFlag,
       TargetAdjustmentLockFlag,
       ProjectionAdjustmentLockFlag,
       WageRateTargetLockType,
       WageRateTargetLockFlag,
       WageRateBudgetLockType,
       WageRateBudgetLockFlag,
       WageRateProjectionLockType,
       WageRateProjectionLockFlag,
       AdjustedValueTotal,
       ManagerAdjustedValueTotal,
       ManagerAdjustedProjectionValueTotal,
       AdjustedProjectionValueTotal,
       ActualYTDValueTotal,
       CurrentYearBudgetTotal,
       PriorYearActualValueTotal,
       InitialBudgetTotal,
       InitialBudget01,
       InitialBudget02,
       InitialBudget03,
       InitialBudget04,
       InitialBudget05,
       InitialBudget06,
       InitialBudget07,
       InitialBudget08,
       InitialBudget09,
       InitialBudget10,
       InitialBudget11,
       InitialBudget12,
       InitialProjectionTotal,
       IsFlexedByStats,
       AdjustedValue01,
       AdjustedValue02,
       AdjustedValue03,
       AdjustedValue04,
       AdjustedValue05,
       AdjustedValue06,
       AdjustedValue07,
       AdjustedValue08,
       AdjustedValue09,
       AdjustedValue10,
       AdjustedValue11,
       AdjustedValue12,
       ManagerAdjustedValue01,
       ManagerAdjustedValue02,
       ManagerAdjustedValue03,
       ManagerAdjustedValue04,
       ManagerAdjustedValue05,
       ManagerAdjustedValue06,
       ManagerAdjustedValue07,
       ManagerAdjustedValue08,
       ManagerAdjustedValue09,
       ManagerAdjustedValue10,
       ManagerAdjustedValue11,
       ManagerAdjustedValue12,
       AdjustedProjectionValue01,
       AdjustedProjectionValue02,
       AdjustedProjectionValue03,
       AdjustedProjectionValue04,
       AdjustedProjectionValue05,
       AdjustedProjectionValue06,
       AdjustedProjectionValue07,
       AdjustedProjectionValue08,
       AdjustedProjectionValue09,
       AdjustedProjectionValue10,
       AdjustedProjectionValue11,
       AdjustedProjectionValue12,
       ManagerAdjustedProjectionValue01,
       ManagerAdjustedProjectionValue02,
       ManagerAdjustedProjectionValue03,
       ManagerAdjustedProjectionValue04,
       ManagerAdjustedProjectionValue05,
       ManagerAdjustedProjectionValue06,
       ManagerAdjustedProjectionValue07,
       ManagerAdjustedProjectionValue08,
       ManagerAdjustedProjectionValue09,
       ManagerAdjustedProjectionValue10,
       ManagerAdjustedProjectionValue11,
       ManagerAdjustedProjectionValue12
FROM fp.Staffing staff (READUNCOMMITTED)
    INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON staff.StaffingID = hist.StaffingID
    CROSS APPLY (
    VALUES
        (  34, TargetDollarsLockType, TargetDollarsLockFlag, BudgetDollarsLockType, BudgetDollarsLockFlag,
            ProjectionDollarsLockType, ProjectionDollarsLockFlag, 
			CASE WHEN BudgetDollarsLockType = 6 THEN 1 ELSE 0 END, 
			CASE WHEN BudgetDollarsLockType = 7 THEN 1 ELSE 0 END, 
			CASE WHEN TargetDollarsLockType = 7 THEN 1 ELSE 0 END,
            CASE WHEN ProjectionDollarsLockType = 7 THEN 1 ELSE 0 END, 0, 0, 0, 0, 0, 0, TargetAdjustedDollarsTotal, BudgetAdjustedDollarsTotal,
            ProjectionAdjustedDollarsTotal, ProjectionAdjustedDollarsTotal, hist.ActualYTDDollarsTotal,
            hist.CurrentYearBudgetDollarsTotal, hist.PriorYearActualDollarsTotal, InitialBudgetDollarsTotal,
            InitialBudgetDollars01, InitialBudgetDollars02, InitialBudgetDollars03, InitialBudgetDollars04,
            InitialBudgetDollars05, InitialBudgetDollars06, InitialBudgetDollars07, InitialBudgetDollars08,
            InitialBudgetDollars09, InitialBudgetDollars10, InitialBudgetDollars11, InitialBudgetDollars12,
            InitialProjectionDollarsTotal, CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedDollars01, TargetAdjustedDollars02,
            TargetAdjustedDollars03, TargetAdjustedDollars04, TargetAdjustedDollars05, TargetAdjustedDollars06,
            TargetAdjustedDollars07, TargetAdjustedDollars08, TargetAdjustedDollars09, TargetAdjustedDollars10,
            TargetAdjustedDollars11, TargetAdjustedDollars12, BudgetAdjustedDollars01, BudgetAdjustedDollars02,
            BudgetAdjustedDollars03, BudgetAdjustedDollars04, BudgetAdjustedDollars05, BudgetAdjustedDollars06,
            BudgetAdjustedDollars07, BudgetAdjustedDollars08, BudgetAdjustedDollars09, BudgetAdjustedDollars10,
            BudgetAdjustedDollars11, BudgetAdjustedDollars12, ProjectionAdjustedDollars01, ProjectionAdjustedDollars02,
            ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05,
            ProjectionAdjustedDollars06, ProjectionAdjustedDollars07, ProjectionAdjustedDollars08,
            ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11,
            ProjectionAdjustedDollars12, ProjectionAdjustedDollars01, ProjectionAdjustedDollars02,
            ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05,
            ProjectionAdjustedDollars06, ProjectionAdjustedDollars07, ProjectionAdjustedDollars08,
            ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11,
            ProjectionAdjustedDollars12
        ),
        (   51, TargetHoursLockType, TargetHoursLockFlag, BudgetHoursLockType, BudgetHoursLockFlag,
            ProjectionHoursLockType, ProjectionHoursLockFlag, 
			CASE WHEN BudgetHoursLockType = 6 THEN 1 ELSE 0 END, 
			CASE WHEN BudgetHoursLockType = 7 THEN 1 ELSE 0 END, 
			CASE WHEN TargetHoursLockType = 7 THEN 1 ELSE 0 END,
            CASE WHEN ProjectionHoursLockType = 7 THEN 1 ELSE 0 END, 0, 0, 0, 0, 0, 0,
            TargetAdjustedHoursTotal, BudgetAdjustedHoursTotal, ProjectionAdjustedHoursTotal,
            ProjectionAdjustedHoursTotal, hist.ActualYTDHoursTotal, hist.CurrentYearBudgetHoursTotal,
            hist.PriorYearActualHoursTotal, InitialBudgetHoursTotal, InitialBudgetHours01, InitialBudgetHours02,
            InitialBudgetHours03, InitialBudgetHours04, InitialBudgetHours05, InitialBudgetHours06,
            InitialBudgetHours07, InitialBudgetHours08, InitialBudgetHours09, InitialBudgetHours10,
            InitialBudgetHours11, InitialBudgetHours12, InitialProjectionHoursTotal,
            CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedHours01, TargetAdjustedHours02, TargetAdjustedHours03, TargetAdjustedHours04,
            TargetAdjustedHours05, TargetAdjustedHours06, TargetAdjustedHours07, TargetAdjustedHours08,
            TargetAdjustedHours09, TargetAdjustedHours10, TargetAdjustedHours11, TargetAdjustedHours12,
            BudgetAdjustedHours01, BudgetAdjustedHours02, BudgetAdjustedHours03, BudgetAdjustedHours04,
            BudgetAdjustedHours05, BudgetAdjustedHours06, BudgetAdjustedHours07, BudgetAdjustedHours08,
            BudgetAdjustedHours09, BudgetAdjustedHours10, BudgetAdjustedHours11, BudgetAdjustedHours12,
            ProjectionAdjustedHours01, ProjectionAdjustedHours02, ProjectionAdjustedHours03, ProjectionAdjustedHours04,
            ProjectionAdjustedHours05, ProjectionAdjustedHours06, ProjectionAdjustedHours07, ProjectionAdjustedHours08,
            ProjectionAdjustedHours09, ProjectionAdjustedHours10, ProjectionAdjustedHours11, ProjectionAdjustedHours12,
            ProjectionAdjustedHours01, ProjectionAdjustedHours02, ProjectionAdjustedHours03, ProjectionAdjustedHours04,
            ProjectionAdjustedHours05, ProjectionAdjustedHours06, ProjectionAdjustedHours07, ProjectionAdjustedHours08,
            ProjectionAdjustedHours09, ProjectionAdjustedHours10, ProjectionAdjustedHours11, ProjectionAdjustedHours12
        ),
        (   144, TargetFTEsLockType, TargetFTEsLockFlag, BudgetFTEsLockType, BudgetFTEsLockFlag,
            ProjectionFTEsLockType, ProjectionFTEsLockFlag, CASE WHEN BudgetFTEsLockType = 6 THEN 1 ELSE 0 END, 
			CASE WHEN BudgetFTEsLockType = 7 THEN 1 ELSE 0 END, 
			CASE WHEN TargetFTEsLockType = 7 THEN 1 ELSE 0 END,
            CASE WHEN ProjectionFTEsLockType = 7 THEN 1 ELSE 0 END, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            hist.ActualYTDFTEsTotal, hist.CurrentYearBudgetFTEsTotal, hist.PriorYearActualFTEsTotal, 0,
            InitialBudgetFTEs01, InitialBudgetFTEs02, InitialBudgetFTEs03, InitialBudgetFTEs04, InitialBudgetFTEs05,
            InitialBudgetFTEs06, InitialBudgetFTEs07, InitialBudgetFTEs08, InitialBudgetFTEs09, InitialBudgetFTEs10,
            InitialBudgetFTEs11, InitialBudgetFTEs12, 0, CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedFTEs01, TargetAdjustedFTEs02,
            TargetAdjustedFTEs03, TargetAdjustedFTEs04, TargetAdjustedFTEs05, TargetAdjustedFTEs06,
            TargetAdjustedFTEs07, TargetAdjustedFTEs08, TargetAdjustedFTEs09, TargetAdjustedFTEs10,
            TargetAdjustedFTEs11, TargetAdjustedFTEs12, BudgetAdjustedFTEs01, BudgetAdjustedFTEs02,
            BudgetAdjustedFTEs03, BudgetAdjustedFTEs04, BudgetAdjustedFTEs05, BudgetAdjustedFTEs06,
            BudgetAdjustedFTEs07, BudgetAdjustedFTEs08, BudgetAdjustedFTEs09, BudgetAdjustedFTEs10,
            BudgetAdjustedFTEs11, BudgetAdjustedFTEs12, ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs02,
            ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs06,
            ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs10,
            ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs12, ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs02,
            ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs06,
            ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs10,
            ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs12
        ),
        (   172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, InitialBudgetRate01,
            InitialBudgetRate02, InitialBudgetRate03, InitialBudgetRate04, InitialBudgetRate05, InitialBudgetRate06,
            InitialBudgetRate07, InitialBudgetRate08, InitialBudgetRate09, InitialBudgetRate10, InitialBudgetRate11,
            InitialBudgetRate12, 0, CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedRate01, TargetAdjustedRate02, TargetAdjustedRate03,
            TargetAdjustedRate04, TargetAdjustedRate05, TargetAdjustedRate06, TargetAdjustedRate07,
            TargetAdjustedRate08, TargetAdjustedRate09, TargetAdjustedRate10, TargetAdjustedRate11,
            TargetAdjustedRate12, BudgetAdjustedRate01, BudgetAdjustedRate02, BudgetAdjustedRate03,
            BudgetAdjustedRate04, BudgetAdjustedRate05, BudgetAdjustedRate06, BudgetAdjustedRate07,
            BudgetAdjustedRate08, BudgetAdjustedRate09, BudgetAdjustedRate10, BudgetAdjustedRate11,
            BudgetAdjustedRate12, ProjectionAdjustedRate01, ProjectionAdjustedRate02, ProjectionAdjustedRate03,
            ProjectionAdjustedRate04, ProjectionAdjustedRate05, ProjectionAdjustedRate06, ProjectionAdjustedRate07,
            ProjectionAdjustedRate08, ProjectionAdjustedRate09, ProjectionAdjustedRate10, ProjectionAdjustedRate11,
            ProjectionAdjustedRate12, ProjectionAdjustedRate01, ProjectionAdjustedRate02, ProjectionAdjustedRate03,
            ProjectionAdjustedRate04, ProjectionAdjustedRate05, ProjectionAdjustedRate06, ProjectionAdjustedRate07,
            ProjectionAdjustedRate08, ProjectionAdjustedRate09, ProjectionAdjustedRate10, ProjectionAdjustedRate11,
            ProjectionAdjustedRate12
        )
) AS CrossApplied (UnitTypeID, TargetLockType, TargetLockFlag, BudgetLockType, BudgetLockFlag, ProjectionLockType,
                   ProjectionLockFlag, BudgetSpreadsLockFlag, BudgetAdjustmentLockFlag, TargetAdjustmentLockFlag,
                   ProjectionAdjustmentLockFlag, WageRateTargetLockType, WageRateTargetLockFlag,
                   WageRateBudgetLockType, WageRateBudgetLockFlag, WageRateProjectionLockType,
                   WageRateProjectionLockFlag, AdjustedValueTotal, ManagerAdjustedValueTotal,
                   ManagerAdjustedProjectionValueTotal, AdjustedProjectionValueTotal, ActualYTDValueTotal,
                   CurrentYearBudgetTotal, PriorYearActualValueTotal, InitialBudgetTotal, InitialBudget01,
                   InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06,
                   InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11,
                   InitialBudget12, InitialProjectionTotal, IsFlexedByStats, AdjustedValue01, AdjustedValue02,
                   AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07,
                   AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12,
                   ManagerAdjustedValue01, ManagerAdjustedValue02, ManagerAdjustedValue03, ManagerAdjustedValue04,
                   ManagerAdjustedValue05, ManagerAdjustedValue06, ManagerAdjustedValue07, ManagerAdjustedValue08,
                   ManagerAdjustedValue09, ManagerAdjustedValue10, ManagerAdjustedValue11, ManagerAdjustedValue12,
                   AdjustedProjectionValue01, AdjustedProjectionValue02, AdjustedProjectionValue03,
                   AdjustedProjectionValue04, AdjustedProjectionValue05, AdjustedProjectionValue06,
                   AdjustedProjectionValue07, AdjustedProjectionValue08, AdjustedProjectionValue09,
                   AdjustedProjectionValue10, AdjustedProjectionValue11, AdjustedProjectionValue12,
                   ManagerAdjustedProjectionValue01, ManagerAdjustedProjectionValue02,
                   ManagerAdjustedProjectionValue03, ManagerAdjustedProjectionValue04,
                   ManagerAdjustedProjectionValue05, ManagerAdjustedProjectionValue06,
                   ManagerAdjustedProjectionValue07, ManagerAdjustedProjectionValue08,
                   ManagerAdjustedProjectionValue09, ManagerAdjustedProjectionValue10,
                   ManagerAdjustedProjectionValue11, ManagerAdjustedProjectionValue12
                  )
    LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID

UNION ALL

-- Wage Rate
SELECT staff.StaffingID,
       staff.BudgetConfigID,
       staff.EntityGroupConfigID,
       staff.EntityID,
       staff.DepartmentID,
       staff.JobCodeID,
       staff.PayCodeGroupID,
       staff.ProductiveClassID,
       3 AS VariabilityID,
       staff.EmployeeID,
       staff.ProviderID,
       staff.ProviderTypeID,
       staff.ProviderSpecialtyID,
       staff.ProviderLineItemID,
       staff.SubsectionID,
       staff.FlexingTypeID,
       159 AS UnitTypeID,
       0 as TargetLockType,
       0 as TargetLockFlag,
       0 as BudgetLockType,
       0 as BudgetLockFlag,
       0 as ProjectionLockType,
       0 as ProjectionLockFlag,
       0 AS BudgetSpreadsLockFlag,
       0 AS BudgetAdjustmentLockFlag,
       0 AS TargetAdjustmentLockFlag,
       0 AS ProjectionAdjustmentLockFlag,
       wr.TargetWageRateLockType as WageRateTargetLockType,
       wr.TargetWageRateLockFlag as WageRateTargetLockFlag,
       wr.BudgetWageRateLockType as WageRateBudgetLockType,
       wr.BudgetWageRateLockFlag as WageRateBudgetLockFlag,
       wr.ProjectionWageRateLockType as WageRateProjectionLockType,
       wr.ProjectionWageRateLockFlag as WageRateProjectionLockFlag,
       0 as AdjustedValueTotal,
       0 as ManagerAdjustedValueTotal,
       0 as ManagerAdjustedProjectionValueTotal,
       0 as AdjustedProjectionValueTotal,
       0 as ActualYTDValueTotal,
       0 as CurrentYearBudgetTotal,
       0 as PriorYearActualValueTotal,
       0 as InitialBudgetTotal,
       wr.InitialBudget01 AS InitialBudget01,
       wr.InitialBudget02 AS InitialBudget02,
       wr.InitialBudget03 AS InitialBudget03,
       wr.InitialBudget04 AS InitialBudget04,
       wr.InitialBudget05 AS InitialBudget05,
       wr.InitialBudget06 AS InitialBudget06,
       wr.InitialBudget07 AS InitialBudget07,
       wr.InitialBudget08 AS InitialBudget08,
       wr.InitialBudget09 AS InitialBudget09,
       wr.InitialBudget10 AS InitialBudget10,
       wr.InitialBudget11 AS InitialBudget11,
       wr.InitialBudget12 AS InitialBudget12,
       0 as InitialProjectionTotal,
       0 AS IsFlexedByStats,
       wr.TargetAdjusted01 AS AdjustedValue01,
       wr.TargetAdjusted02 AS AdjustedValue02,
       wr.TargetAdjusted03 AS AdjustedValue03,
       wr.TargetAdjusted04 AS AdjustedValue04,
       wr.TargetAdjusted05 AS AdjustedValue05,
       wr.TargetAdjusted06 AS AdjustedValue06,
       wr.TargetAdjusted07 AS AdjustedValue07,
       wr.TargetAdjusted08 AS AdjustedValue08,
       wr.TargetAdjusted09 AS AdjustedValue09,
       wr.TargetAdjusted10 AS AdjustedValue10,
       wr.TargetAdjusted11 AS AdjustedValue11,
       wr.TargetAdjusted12 AS AdjustedValue12,
       wr.BudgetAdjusted01 AS ManagerAdjustedValue01,
       wr.BudgetAdjusted02 AS ManagerAdjustedValue02,
       wr.BudgetAdjusted03 AS ManagerAdjustedValue03,
       wr.BudgetAdjusted04 AS ManagerAdjustedValue04,
       wr.BudgetAdjusted05 AS ManagerAdjustedValue05,
       wr.BudgetAdjusted06 AS ManagerAdjustedValue06,
       wr.BudgetAdjusted07 AS ManagerAdjustedValue07,
       wr.BudgetAdjusted08 AS ManagerAdjustedValue08,
       wr.BudgetAdjusted09 AS ManagerAdjustedValue09,
       wr.BudgetAdjusted10 AS ManagerAdjustedValue10,
       wr.BudgetAdjusted11 AS ManagerAdjustedValue11,
       wr.BudgetAdjusted12 AS ManagerAdjustedValue12,
       wr.ProjectionAdjusted01 AS AdjustedProjectionValue01,
       wr.ProjectionAdjusted02 AS AdjustedProjectionValue02,
       wr.ProjectionAdjusted03 AS AdjustedProjectionValue03,
       wr.ProjectionAdjusted04 AS AdjustedProjectionValue04,
       wr.ProjectionAdjusted05 AS AdjustedProjectionValue05,
       wr.ProjectionAdjusted06 AS AdjustedProjectionValue06,
       wr.ProjectionAdjusted07 AS AdjustedProjectionValue07,
       wr.ProjectionAdjusted08 AS AdjustedProjectionValue08,
       wr.ProjectionAdjusted09 AS AdjustedProjectionValue09,
       wr.ProjectionAdjusted10 AS AdjustedProjectionValue10,
       wr.ProjectionAdjusted11 AS AdjustedProjectionValue11,
       wr.ProjectionAdjusted12 AS AdjustedProjectionValue12,
       wr.ProjectionAdjusted01 AS ManagerAdjustedProjectionValue01,
       wr.ProjectionAdjusted02 AS ManagerAdjustedProjectionValue02,
       wr.ProjectionAdjusted03 AS ManagerAdjustedProjectionValue03,
       wr.ProjectionAdjusted04 AS ManagerAdjustedProjectionValue04,
       wr.ProjectionAdjusted05 AS ManagerAdjustedProjectionValue05,
       wr.ProjectionAdjusted06 AS ManagerAdjustedProjectionValue06,
       wr.ProjectionAdjusted07 AS ManagerAdjustedProjectionValue07,
       wr.ProjectionAdjusted08 AS ManagerAdjustedProjectionValue08,
       wr.ProjectionAdjusted09 AS ManagerAdjustedProjectionValue09,
       wr.ProjectionAdjusted10 AS ManagerAdjustedProjectionValue10,
       wr.ProjectionAdjusted11 AS ManagerAdjustedProjectionValue11,
       wr.ProjectionAdjusted12 AS ManagerAdjustedProjectionValue12
FROM [fp].[Staffing] staff (READUNCOMMITTED)
    INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED)
        ON staff.StaffingWageRateID = wr.StaffingWageRateID
WHERE staff.VariabilityID = 1
GO


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

-- fp.viewStaffing_WorkingHours
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	 2023-10-31  MD      JAZZ-62448		Updated for staffing restructure
*************************************************************/
CREATE   VIEW [fp].[viewStaffing_WorkingHours] AS
SELECT
	b.BudgetConfigID,
	b.EntityGroupConfigID,
	b.EntityID,
	b.DepartmentID,
	b.JobCodeID,
	b.PayCodeGroupID,
	b.ProductiveClassID,
	b.SubsectionID,
	b.VariabilityID,
	b.EmployeeID,
	b.InitialBudgetHours01,
	b.InitialBudgetHours02,
	b.InitialBudgetHours03,
	b.InitialBudgetHours04,
	b.InitialBudgetHours05,
	b.InitialBudgetHours06,
	b.InitialBudgetHours07,
	b.InitialBudgetHours08,
	b.InitialBudgetHours09,
	b.InitialBudgetHours10,
	b.InitialBudgetHours11,
	b.InitialBudgetHours12,
	b.InitialProjectionHours01,
	b.InitialProjectionHours02,
	b.InitialProjectionHours03,
	b.InitialProjectionHours04,
	b.InitialProjectionHours05,
	b.InitialProjectionHours06,
	b.InitialProjectionHours07,
	b.InitialProjectionHours08,
	b.InitialProjectionHours09,
	b.InitialProjectionHours10,
	b.InitialProjectionHours11,
	b.InitialProjectionHours12,
	b.BudgetAdjustedHours01,
	b.BudgetAdjustedHours02,
	b.BudgetAdjustedHours03,
	b.BudgetAdjustedHours04,
	b.BudgetAdjustedHours05,
	b.BudgetAdjustedHours06,
	b.BudgetAdjustedHours07,
	b.BudgetAdjustedHours08,
	b.BudgetAdjustedHours09,
	b.BudgetAdjustedHours10,
	b.BudgetAdjustedHours11,
	b.BudgetAdjustedHours12,
	b.TargetAdjustedHours01,
	b.TargetAdjustedHours02,
	b.TargetAdjustedHours03,
	b.TargetAdjustedHours04,
	b.TargetAdjustedHours05,
	b.TargetAdjustedHours06,
	b.TargetAdjustedHours07,
	b.TargetAdjustedHours08,
	b.TargetAdjustedHours09,
	b.TargetAdjustedHours10,
	b.TargetAdjustedHours11,
	b.TargetAdjustedHours12,
	b.ProjectionAdjustedHours01,
	b.ProjectionAdjustedHours02,
	b.ProjectionAdjustedHours03,
	b.ProjectionAdjustedHours04,
	b.ProjectionAdjustedHours05,
	b.ProjectionAdjustedHours06,
	b.ProjectionAdjustedHours07,
	b.ProjectionAdjustedHours08,
	b.ProjectionAdjustedHours09,
	b.ProjectionAdjustedHours10,
	b.ProjectionAdjustedHours11,
	b.ProjectionAdjustedHours12,
	whBudget.Month01 As BudgetWorkingHours01,
	whBudget.Month02 As BudgetWorkingHours02,
	whBudget.Month03 As BudgetWorkingHours03,
	whBudget.Month04 As BudgetWorkingHours04,
	whBudget.Month05 As BudgetWorkingHours05,
	whBudget.Month06 As BudgetWorkingHours06,
	whBudget.Month07 As BudgetWorkingHours07,
	whBudget.Month08 As BudgetWorkingHours08,
	whBudget.Month09 As BudgetWorkingHours09,
	whBudget.Month10 As BudgetWorkingHours10,
	whBudget.Month11 As BudgetWorkingHours11,
	whBudget.Month12 As BudgetWorkingHours12,
	whProjection.Month01 As ProjectionWorkingHours01,
	whProjection.Month02 As ProjectionWorkingHours02,
	whProjection.Month03 As ProjectionWorkingHours03,
	whProjection.Month04 As ProjectionWorkingHours04,
	whProjection.Month05 As ProjectionWorkingHours05,
	whProjection.Month06 As ProjectionWorkingHours06,
	whProjection.Month07 As ProjectionWorkingHours07,
	whProjection.Month08 As ProjectionWorkingHours08,
	whProjection.Month09 As ProjectionWorkingHours09,
	whProjection.Month10 As ProjectionWorkingHours10,
	whProjection.Month11 As ProjectionWorkingHours11,
	whProjection.Month12 As ProjectionWorkingHours12
FROM
	[fp].[Staffing] b
INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON
	b.BudgetConfigID = bc.BudgetConfigID
INNER JOIN [fw].[DimDepartment] d (READUNCOMMITTED) ON
	d.DepartmentID = b.DepartmentID
INNER JOIN [fw].[DimJobCode] jc (READUNCOMMITTED) ON
	jc.JobCodeID = b.JobCodeID
INNER JOIN [client].[FactWorkingHoursPerMonth] whBudget (READUNCOMMITTED) ON
	whBudget.FiscalYearID = bc.FiscalYearID
	AND whBudget.WorkWeekID =
	(CASE
		WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID
		ELSE d.WorkWeekID
	END)
INNER JOIN [client].[FactWorkingHoursPerMonth] whProjection (READUNCOMMITTED) ON
	whProjection.FiscalYearID = bc.FiscalYearID - 1
	AND whProjection.WorkWeekID =
	(CASE
		WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID
		ELSE d.WorkWeekID
	END)
INNER JOIN [fw].[DimEmployee] e (READUNCOMMITTED) ON
	e.EmployeeID = b.EmployeeID;
GO


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

-- fp.viewStatisticsAdjustment
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-01-04  MZ		 JAZZ-47034	Added BudgetPhaseID
 *************************************************************/

CREATE   VIEW [fp].[viewStatisticsAdjustment]
AS 

SELECT [AdjustmentGUID]
      ,[BudgetConfigGUID]
      ,[AdjustmentType]
      ,[Value]
      ,[AdjustmentFilterJSON]
      ,[GroupingHierarchyJSON]
      ,[AdjustedProperty]
      ,[Comment]
      ,[AuthorGUID]
      ,[AuthorFullName]
      ,[LastModifiedDateUtc]
      ,[DateCreatedUtc]
      ,[GroupingGUID]
      ,[ParentFilterJSON]
      ,[TimeClassID]
	  ,[BudgetPhaseID]
      ,[ClassificationGroupID]
      ,[ClassificationCategoryID]
      ,[IsRecordDeleted]
      ,[DimensionMemberJson]
      ,[AdjustmentID]
      ,[SubsectionID]
      ,[IsErrored]
  FROM [fp].[StatisticsAdjustment]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewStatisticsAdjustmentImport
CREATE VIEW [fp].[viewStatisticsAdjustmentImport]
AS 
SELECT [RowID]
      ,[AdjustmentGUID]
      ,[DepartmentID]
      ,[EntityID]
      ,[AccountID]
      ,[FinancialReportingID]
      ,[PayorID]
      ,[PatientClassID]
      ,[ProviderID]
      ,[ProviderTypeID]
      ,[ProviderLineItemID]
      ,[ProviderSpecialtyID]
      ,[FiscalYearID]
      ,[FiscalMonthID]
      ,[UnitTypeID]
      ,[Value]
      ,[Version]
      ,[TimeClassID]
      ,[BudgetPhaseID]
      ,[IsRecordDeleted]
      ,[AdjustmentID]
  FROM [fp].[StatisticsAdjustmentImport]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewStatisticsInitialPlanConfigDetailLogs
CREATE   VIEW fp.viewStatisticsInitialPlanConfigDetailLogs AS

SELECT RowID,
	BudgetConfigGUID,
	BudgetConfigID,
	EntityID,
	DepartmentID,
	AccountID,
	PatientClassID,
	TimeClassID,
	FinancialReportingID,
	PayorID,
	ProviderSpecialtyID,
	ProviderTypeID,
	ProviderID,
    ProviderLineItemID,
    VariabilityID,
	ProjectionMethodID,
	TrailingMonths,
	VersionID
	FROM [fp].[StatisticsInitialPlanConfigDetailHistory]
	UNION
	SELECT RowID,
		BudgetConfigGUID,
		BudgetConfigID,
		EntityID,
		DepartmentID,
		AccountID,
		PatientClassID,
		TimeClassID,
		FinancialReportingID,
		PayorID,
		ProviderSpecialtyID,
		ProviderTypeID,
		ProviderID,
   		ProviderLineItemID,
   		VariabilityID,
		ProjectionMethodID,
		TrailingMonths,
		VersionID
	FROM [fp].[StatisticsInitialPlanConfigDetail]
GO


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

-- fp.viewStatisticsSpreadUnlockData
CREATE VIEW fp.viewStatisticsSpreadUnlockData
AS 

SELECT [RowID]
      ,[BudgetConfigID]
      ,[AdjustmentGUID]
      ,[EntityID]
      ,[DepartmentID]
      ,[AccountID]
      ,[FinancialReportingID]
      ,[PayorID]
      ,[PatientClassID]
      ,[ProviderID]
      ,[ProviderTypeID]
      ,[ProviderLineItemID]
      ,[ProviderSpecialtyID] 
      ,[Version]
      ,[Value01]
      ,[Value02]
      ,[Value03]
      ,[Value04]
      ,[Value05]
      ,[Value06]
      ,[Value07]
      ,[Value08]
      ,[Value09]
      ,[Value10]
      ,[Value11]
      ,[Value12]
      ,[IsRecordDeleted]
  FROM [fp].[StatisticsSpreadUnlockData]
  WHERE IsRecordDeleted = 0
GO


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

-- fp.viewStatisticsSpreads
CREATE   VIEW [fp].[viewStatisticsSpreads]
AS
    SELECT [BudgetConfigID], [DepartmentID], [AccountID], [ProviderID], [ProviderLineItemID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID]
    FROM [fp].[StatisticsSpreads] with (readuncommitted)
    WHERE GlobalSpreadID = 1

    UNION ALL

    SELECT bs.[BudgetConfigID], [DepartmentID], [AccountID], [ProviderID], [ProviderLineItemID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID]
    FROM [fp].[StatisticsSpreads] bs with (readuncommitted)
    INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID
    WHERE bs.GlobalSpreadID > 1
GO


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

-- fp.viewUserViewGeneralLedgerAdjustments
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2024-10-22  MY  	 JAZZ-77735 	Initial
 *************************************************************/
CREATE   VIEW [fp].[viewUserViewGeneralLedgerAdjustments]
AS

	-- WAIT, STOP WHAT YOU ARE DOING. What are you using this for? If you are using this to get back adjustments
	-- from the user perspective, then you are in the right place. If you are looking at it in any other way look elsewhere.
	-- This translates the GeneralLedgerAdjustment table to what the user sees. So for exmaple, when you make a roll up adjustment,
	-- it creates X amount of adjustments, where X is the number of departments underneath it. From the user perspective, this creates 1 adjustment.
	-- This for that roll up adjustment will return back 1, not X.

	WITH glAdjustments AS (
		SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID
		FROM fp.GeneralLedgerAdjustment WHERE IsRecordDeleted = 0
	),
	-- These are all rollup adjustments (aka the parent adjustment)
	rollUpAdjustments AS (
		SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID
		FROM glAdjustments	WHERE AdjustmentType IN (12, 13, 14)
	),
	-- These are all adjustments that are not part of a roll up
	planEditorAdjustments AS (
		SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID
		FROM glAdjustments WHERE AdjustmentType IN (0, 2, 3) AND GroupingGUID = '00000000-0000-0000-0000-000000000000'
	),
	-- GL Adjustments does not have FTE adjustments so we can avoid extra processing
	-- Exclude Incrementals, Sets, and Final, as well as their roll up counterparts
	-- because these are included in the above queries
	otherAdjustments AS (
		SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID
		FROM glAdjustments WHERE AdjustmentType NOT IN (0, 2, 3, 12, 13, 14)
	)

	SELECT * FROM otherAdjustments
	UNION ALL
	SELECT * FROM planEditorAdjustments
	UNION ALL
	SELECT * FROM rollUpAdjustments
GO


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

-- fp.viewWorkingHours
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	10-9-2023  MY      JAZZ-61397		Update Staffing/Provider Comp adjustments to support data model changes
*************************************************************/
CREATE   VIEW fp.viewWorkingHours  
 AS
 	SELECT 
		b.StaffingID, b.BudgetConfigID, b.EntityGroupConfigID, b.EntityID, b.DepartmentID, b.JobCodeID, b.PayCodeGroupID, 
		b.ProductiveClassID, b.VariabilityID, b.EmployeeID, b.ProviderID, b.ProviderTypeID, b.ProviderSpecialtyID, 
		b.ProviderLineItemID, b.SubsectionID, b.AddDate, b.IsNew,

		whBudget.Month01 As BudgetWorkingHours01, whBudget.Month02 As BudgetWorkingHours02, whBudget.Month03 As BudgetWorkingHours03, 
		whBudget.Month04 As BudgetWorkingHours04, whBudget.Month05 As BudgetWorkingHours05, whBudget.Month06 As BudgetWorkingHours06, 
		whBudget.Month07 As BudgetWorkingHours07, whBudget.Month08 As BudgetWorkingHours08, whBudget.Month09 As BudgetWorkingHours09, 
		whBudget.Month10 As BudgetWorkingHours10, whBudget.Month11 As BudgetWorkingHours11, whBudget.Month12 As BudgetWorkingHours12,

		whProjection.Month01 As ProjectionWorkingHours01, whProjection.Month02 As ProjectionWorkingHours02, whProjection.Month03 As ProjectionWorkingHours03, whProjection.Month04 As ProjectionWorkingHours04,
		whProjection.Month05 As ProjectionWorkingHours05, whProjection.Month06 As ProjectionWorkingHours06, whProjection.Month07 As ProjectionWorkingHours07, whProjection.Month08 As ProjectionWorkingHours08, 
		whProjection.Month09 As ProjectionWorkingHours09, whProjection.Month10 As ProjectionWorkingHours10, whProjection.Month11 As ProjectionWorkingHours11, whProjection.Month12 As ProjectionWorkingHours12,

		b.FlexingTypeID,
		b.ChangeHistoryGroupingGUID
	FROM [fp].[Staffing] b
		INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON b.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] d (READUNCOMMITTED) ON d.DepartmentID = b.DepartmentID 
		INNER JOIN [fw].[DimJobCode] jc (READUNCOMMITTED) ON jc.JobCodeID = b.JobCodeID 
		INNER JOIN [client].[FactWorkingHoursPerMonth] whBudget (READUNCOMMITTED) ON whBudget.FiscalYearID = bc.FiscalYearID
	        AND whBudget.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
		INNER JOIN [client].[FactWorkingHoursPerMonth] whProjection (READUNCOMMITTED) ON whProjection.FiscalYearID = bc.FiscalYearID - 1
	        AND whProjection.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
GO


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

-- fp.viewWorkingHoursPerMonthWithBreakdown
CREATE VIEW  fp.viewWorkingHoursPerMonthWithBreakdown  
 AS
	SELECT base.FiscalYearID, base.FiscalMonthID, base.WorkWeekID, base.AnnualHours, base.YTDHours, ISNULL(base.AnnualHours - base.PreviousMonthsYTDHours, base.AnnualHours) AS RemainingAnnualHours
	FROM
	(
		SELECT base.FiscalYearID, base.FiscalMonthID, base.WorkWeekID, whpm.MonthYearly AS AnnualHours, base.YTDHours,
			LAG(base.YTDHours) OVER (PARTITION BY base.FiscalYearID, base.WorkWeekID ORDER BY base.FiscalYearID, fm.SortOrder) AS PreviousMonthsYTDHours
		FROM [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] base
			INNER JOIN [fw].[DimFiscalMonth] fm ON base.FiscalMonthID = fm.FiscalMonthID
			INNER JOIN [client].[FactWorkingHoursPerMonth] whpm ON base.FiscalYearID = whpm.FiscalYearID
				AND base.WorkWeekID = whpm.WorkWeekID
	) base
GO


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

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

-- fp.BenefitsAdjustment_SEL_LIST
CREATE   PROCEDURE [fp].[BenefitsAdjustment_SEL_LIST]
	@budgetGUID UNIQUEIDENTIFIER,
	@start INT,
	@end INT,
	@search VARCHAR(MAX),
	@filter VARCHAR(MAX),
	@userGUID UNIQUEIDENTIFIER,
	@isDataSecured BIT,
	@dateTimeFormat VARCHAR(30),
	@userTimeZone VARCHAR(50)
AS 
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2020-06-03  LR  	 JAZZ-134		Now including deleted items to be displayed in the activity pane
 ** 2 	 2020-07-01  OP  	 JAZZ-635		Added AP Entity Config roles support
 ** 3 	 2020-08-20  OP  	 JAZZ-4123		Fixed import comment
 ** 4	 2023-01-10	 NT		 JAZZ-45457		Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card
 ** 5    2024-02-22  MY      JAZZ-67143		Filters acting unexpectedly post-adjustment - Issue #2
 *************************************************************/
	BEGIN

	CREATE TABLE #departmentsSecurity (
		DepartmentID INT NULL,
		EntityID INT NULL
	)	

	CREATE TABLE #securedAdjustments (
		AdjustmentGUID UNIQUEIDENTIFIER
	)

	DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]()
	DECLARE @pageSize INT = @end - @start;

	SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
	SET @filter = LOWER(NULLIF(@filter, ''))

	SELECT		AdjustmentGUID
				,GroupingHierarchyJSON					
				,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
				,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID
				,AdjustmentType
				,GroupingGUID
	INTO	#adjustments
	FROM	fp.BenefitsAdjustment AS slea WITH (NOLOCK)	
	WHERE	slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14) -- Supported Adjustment types for Benefits Adjustments
		AND slea.BudgetConfigGUID = @budgetGUID

	IF @isDataSecured = 1
	BEGIN
		INSERT INTO #departmentsSecurity
		EXEC fp.DepartmentsSecurity_SEL 
			@userGUID = @userGUID,
			@pageName = 'Benefits'

		CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

		SELECT	AdjustmentGUID
				,ahd.ID AS DepartmentID
		INTO	#adjustmentGroupingHierarchyDepartments
		FROM (
				SELECT	adj.AdjustmentGUID
						,adj.GroupingHierarchyJSON
				FROM	#adjustments AS adj
				WHERE	adj.EntityID IS NULL
						AND adj.DepartmentID IS NULL) AS slea
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd
		GROUP BY AdjustmentGUID
				,ahd.ID

		SELECT	adj.AdjustmentGUID,
				ahe.ID AS EntityID
		INTO	#adjustmentGroupingHierarchyEntities
		FROM	#adjustments AS adj
				JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID
																		AND adhd.DepartmentID IS NULL
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
		GROUP BY adj.AdjustmentGUID	
				,ahe.ID
		
		INSERT INTO	#securedAdjustments
		SELECT	res.AdjustmentGUID
		FROM	(
			SELECT	slea.AdjustmentGUID
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID
			GROUP BY slea.AdjustmentGUID 

			UNION ALL

			SELECT	slea.AdjustmentGUID		
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
			WHERE	slea.DepartmentID IS NULL
			GROUP BY slea.AdjustmentGUID

			UNION ALL

			SELECT	aghd.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyDepartments AS aghd
					JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID
			WHERE	dshd.DepartmentID IS NOT NULL
			GROUP BY aghd.AdjustmentGUID

			UNION ALL

			SELECT	aghe.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyEntities AS aghe
					JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
			GROUP BY aghe.AdjustmentGUID

			UNION ALL

			SELECT	adj.AdjustmentGUID
			FROM	#adjustments AS adj
					JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID
					JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID
			WHERE	adj.DepartmentID IS NULL
					AND adj.EntityID IS NULL
					AND aghd.DepartmentID IS NULL
					AND aghe.EntityID IS NULL
			GROUP BY adj.AdjustmentGUID
		) AS res

		-- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2)
		-- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the 
		-- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine.
		-- Essentially what we are doing here is using the child adjustments to find if they fall in security.
		-- In the event we have a child, populate the parent adjustment in the list.
		-- Find all the GroupingGuid's for any child adjustments that fall into security.
		
		SELECT DISTINCT adj.GroupingGUID
		INTO #groupingAdjustments
		FROM #securedAdjustments secured
			INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID
		WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments.

		-- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment.
		INSERT INTO #securedAdjustments
		SELECT adj.AdjustmentGUID
		FROM #adjustments adj
			INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID
			LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID
		WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments
			AND secured.AdjustmentGUID IS NULL

	END
	ELSE 
		BEGIN

			INSERT INTO #securedAdjustments
			SELECT	AdjustmentGUID
			FROM	#adjustments

		END

	CREATE CLUSTERED	INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID)

	SELECT	iadj.AdjustmentGuid, 
			iadj.UnitTypeID
	INTO	#importAdjustments
	FROM	fp.BenefitsAdjustmentImport AS iadj WITH (NOLOCK)
			JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID
			LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID
	WHERE	ds.DepartmentID IS NOT NULL
			OR @isDataSecured = 0
	GROUP BY iadj.AdjustmentGuid,
			iadj.UnitTypeID
	
	CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID)

	SELECT res.TotalRowsCount
		,res.AdjustmentGUID
		,res.BudgetConfigGUID
		,res.AdjustmentType
		,res.[Value]
		,res.AdjustmentFilterJSON
		,res.GroupingHierarchyJSON
		,res.AdjustedProperty
		,res.Comment
		,res.AuthorGUID
		,res.AuthorFullName
		,res.LastModifiedDateUtc
		,res.DateCreatedUtc
		,res.GroupingGUID
		,res.TimeClassID
		,res.BudgetPhaseID
		,res.ClassificationGroupID
		,res.ClassificationCategoryID
		,res.JobCode
		,res.JobCodeCount
		,res.DepartmentCode
		,res.DepartmentCount
		,res.UnitTypeID
		,res.ImportUnitTypeIDs
		,res.IsRecordDeleted
		,res.IsErrored
	FROM (
		SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount,
			   *
		FROM (
			SELECT	ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
				  , slea.AdjustmentGUID
				  ,slea.BudgetConfigGUID
				  ,slea.AdjustmentType
				  ,slea.[Value]
				  ,slea.AdjustmentFilterJSON
				  ,slea.GroupingHierarchyJSON
				  ,slea.AdjustedProperty
				  ,ISNULL(ag.Description, slea.Comment) AS Comment
				  ,slea.AuthorGUID
				  ,slea.AuthorFullName
				  ,slea.LastModifiedDateUtc
				  ,slea.DateCreatedUtc
				  ,slea.GroupingGUID
				  ,slea.TimeClassID
				  ,slea.BudgetPhaseID
				  ,slea.ClassificationGroupID
				  ,slea.ClassificationCategoryID
				  ,slea.UnitTypeID
				  ,NULL AS JobCode
				  ,NULL AS JobCodeCount
				  ,NULL AS DepartmentCode
				  ,NULL AS DepartmentCount
				  ,sai.ImportUnitTypeIDs
				  ,slea.IsRecordDeleted
				  ,slea.IsErrored
			FROM	fp.BenefitsAdjustment AS slea WITH (NOLOCK)
					JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
					LEFT JOIN (
						SELECT	p.AdjustmentGUID, 
								ImportUnitTypeIDs =
									TRIM(STUFF(
										(SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5))
										FROM	#importAdjustments AS p2
										WHERE	p2.AdjustmentGUID = p.AdjustmentGUID
										GROUP BY p2.AdjustmentGUID, 
												p2.UnitTypeID
										FOR XML PATH(N''))
									, 1, 0, N''))
						FROM	#importAdjustments AS p
						GROUP BY p.AdjustmentGUID
					) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID
					LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
					LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
					LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
																	AND slea.ClassificationCategoryID = acc.CategoryID
					LEFT JOIN (
						SELECT	nsa.GroupingGUID
						FROM	fp.BenefitsAdjustment as nsa WITH (NOLOCK)
						WHERE	nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types
								AND nsa.BudgetConfigGUID = @budgetGUID
						GROUP BY nsa.GroupingGUID
					) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
			WHERE	(slea.AdjustmentType <> 4 
						OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment
					AND slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14) -- Supported Adjustment types for Benefits Adjustments
					AND (ra.GroupingGUID IS NULL
						OR slea.AdjustmentType IN (12, 13, 14))
					AND (@search IS NULL 
						OR (
								LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
								OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\'
								OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR acc.[Name] LIKE @search ESCAPE '\'
								OR acg.[Name] LIKE @search ESCAPE '\'
								OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
								OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
								OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1
							)
						)
					AND (@filter IS NULL
						OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
							SELECT	[value]
							FROM	STRING_SPLIT(@filter, ' ')
							)
						)
			) AS res_inner
		WHERE res_inner.RowNumber = 1 ) AS res
	WHERE res.RowNumber = 1
	ORDER BY res.DateCreatedUtc DESC
	OFFSET @start ROWS
	FETCH NEXT @pageSize ROWS ONLY;
END;
GO


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

-- fp.ChargeVolumeADDProviderRateCalculations
/**************************************************************
** CID  Date         Author  WI			 Description
** 1	 2022-09-01	 JB		 JAZZ-32095	 Remove Payor and PayorGroupID from joins.
** 2	 2022-11-10	 AO		 JAZZ-45578	 Remove PayorID and PayorGroupID from main select.
** 3	 2023-05-18	 MY		 JAZZ-55153	 Update to restructure
*************************************************************/	 
CREATE   PROCEDURE [fp].[ChargeVolumeADDProviderRateCalculations]
	@BudgetConfigID INT,
	@MonthsLoaded TINYINT,
	@NewProviderID INT,
    @BenchProvidersList [dbo].[SqlInt32ListTableType] READONLY,
	@IsDataSecured BIT,
	@DeptList [dbo].[SqlInt32ListTableType] READONLY


 AS
 BEGIN

	 IF OBJECT_ID('tempdb..#BenchProviders') IS NOT NULL
		DROP TABLE #BenchProviders

	IF OBJECT_ID('tempdb..#DepartmentsSecurity') IS NOT NULL
		DROP TABLE #DepartmentsSecurity

	 IF OBJECT_ID('tempdb..#FactChargeVolumeTemp') IS NOT NULL
		DROP TABLE #FactChargeVolumeTemp

	IF OBJECT_ID('tempdb..#FactChargeVolumeTempUnits') IS NOT NULL
		DROP TABLE #FactChargeVolumeTempUnits

	IF OBJECT_ID('tempdb..#FactServiceLineTempUnits') IS NOT NULL
		DROP TABLE #FactServiceLineTempUnits

 	CREATE TABLE #BenchProviders (
	ProviderID INT
	)
	   
	INSERT INTO #BenchProviders (ProviderID)
	SELECT value
	FROM @BenchProvidersList

	DECLARE @NumBenchProviders int 	
	SELECT @NumBenchProviders = COUNT(*) FROM #BenchProviders

	CREATE TABLE #FactChargeVolumeTemp(
		  ChargeVolumeID INT,
		  BudgetConfigID INT,
		  EntityGroupConfigID INT,
		  EntityID INT,
		  DepartmentID INT,
		  ServiceLineID INT,
		  PatientClassID INT,
		  AgeCohortID INT,
		  MedicalSurgicalID INT,
		  ChargeCodeID INT,
		  UnitTypeID INT ,
		  ServiceEntityID INT,
		  MSDRGID INT,
		  UBRevCodeID INT,
		  PrimaryCPTID INT,
		  ServiceProviderID INT,
		  ServiceProviderSpecialtyID INT,
		  PerformingProviderID INT,
		  PerformingProviderSpecialtyID INT,
		  BillingCPTID INT
	)

	 -- select into temporary table data with changed PerformingProviderID to new if this provider is matched to selected benchmark providers
  IF( @IsDataSecured = 1)
	BEGIN
		CREATE TABLE #DepartmentsSecurity (
		DepartmentID INT )	

		INSERT INTO #DepartmentsSecurity (DepartmentID)
		SELECT value
		FROM @DeptList

		INSERT INTO #FactChargeVolumeTemp
		   SELECT
			  fcv.ChargeVolumeID,
			  fcv.BudgetConfigID,
			  fcv.EntityGroupConfigID ,
			  fcv.EntityID,
			  fcv.DepartmentID,
			  fcv.ServiceLineID ,
			  fcv.PatientClassID,
			  fcv.AgeCohortID,
			  fcv.MedicalSurgicalID,
			  fcv.ChargeCodeID,
			  fcv.UnitTypeID ,
			  fcv.ServiceEntityID,
			  fcv.MSDRGID,
			  fcv.UBRevCodeID,
			  fcv.PrimaryCPTID,
			  fcv.ServiceProviderID,
			  fcv.ServiceProviderSpecialtyID,
			  case when fcv.PerformingProviderID IN (select ProviderID from #BenchProviders) then @NewProviderID
						else fcv.PerformingProviderID
						end as PerformingProviderID,
			  fcv.PerformingProviderSpecialtyID,
			  fcv.BillingCPTID 
			  FROM fp.ChargeVolume fcv
			  INNER JOIN #DepartmentsSecurity ds on ds.DepartmentID = fcv.DepartmentID
			  WHERE BudgetConfigID = @BudgetConfigID
					and UnitTypeID = 145
					and ServiceProviderID in (SELECT ProviderID FROM #BenchProviders)
		END
ELSE
	BEGIN
		INSERT INTO #FactChargeVolumeTemp
		SELECT
		  ChargeVolumeID,
		  BudgetConfigID,
		  EntityGroupConfigID ,
		  EntityID,
		  DepartmentID,
		  ServiceLineID ,
		  PatientClassID,
		  AgeCohortID,
		  MedicalSurgicalID,
		  ChargeCodeID,
		  UnitTypeID ,
		  ServiceEntityID,
		  MSDRGID,
		  UBRevCodeID,
		  PrimaryCPTID,
		  ServiceProviderID,
		  ServiceProviderSpecialtyID,
		  case when PerformingProviderID IN (select ProviderID from #BenchProviders) then @NewProviderID
					else PerformingProviderID
					end as PerformingProviderID,
		  PerformingProviderSpecialtyID,
		  BillingCPTID 
		  FROM fp.ChargeVolume
		  WHERE BudgetConfigID = @BudgetConfigID
				and UnitTypeID = 145
				and ServiceProviderID in (SELECT ProviderID FROM #BenchProviders)
END

----------- select chargeVolume units -------------------
	Select 
		  BudgetConfigID,
		  EntityGroupConfigID ,
		  EntityID,
		  DepartmentID,
		  ServiceLineID ,
		  PatientClassID,
		  AgeCohortID,
		  MedicalSurgicalID,
		  ChargeCodeID,
		  UnitTypeID ,
		  ServiceEntityID,
		  MSDRGID,
		  UBRevCodeID,
		  PrimaryCPTID,
		  @NewProviderID  as ServiceProviderID,
		  ServiceProviderSpecialtyID,
		  PerformingProviderID ,
		  PerformingProviderSpecialtyID,
		  BillingCPTID,
		  --Charge Units
			case @Monthsloaded
				when 1 then SUM(fcvh.ActualYTDValue01+fcvh.PriorYearActualValue02+fcvh.PriorYearActualValue03+fcvh.PriorYearActualValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 2 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.PriorYearActualValue03+fcvh.PriorYearActualValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 3 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.PriorYearActualValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 4 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 5 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 6 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 7 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 8 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 9 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 10 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.ActualYTDValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12)
				when 11 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.ActualYTDValue10+fcvh.ActualYTDValue11+fcvh.PriorYearActualValue12)
				else SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.ActualYTDValue10+fcvh.ActualYTDValue11+fcvh.ActualYTDValue12)
			end/@NumBenchProviders as CV_Units --needs to be devided by number of selected benchmark providers			
	into #FactChargeVolumeTempUnits
		 from #FactChargeVolumeTemp fcv
			INNER JOIN [fp].[ChargeVolumeHistory] fcvh on fcv.ChargeVolumeID = fcvh.ChargeVolumeID
		GROUP BY
		BudgetConfigID,
		  EntityGroupConfigID ,
		  EntityID,
		  DepartmentID,
		  ServiceLineID ,
		  PatientClassID,
		  AgeCohortID,
		  MedicalSurgicalID,
		  ChargeCodeID,
		  UnitTypeID ,
		  ServiceEntityID,
		  MSDRGID,
		  UBRevCodeID,
		  PrimaryCPTID,
		  ServiceProviderSpecialtyID,
		  PerformingProviderID ,
		  PerformingProviderSpecialtyID,
		  BillingCPTID


-------- select ServiceLineUnits -------------

		SELECT
			sd.BudgetConfigID,
			sd.EntityGroupConfigID,
			sd.EntityID,
			sd.PatientClassID,
			sd.ServiceLineID,
			sd.ServiceLineRollupID,
			sd.AgeCohortID,
			sd.MedicalSurgicalID,
			sd.DepartmentID,
			sd.PayorID,
			sd.PayorGroupID,
			sd.MSDRGID,
			sd.CPTID,
			@NewProviderID as ProviderID,
			sd.PhysicianSpecialtyID,
			case @Monthsloaded
				when 1 then SUM(sdh.ActualYTDValue01+sdh.PriorYearActualValue02+sdh.PriorYearActualValue03+sdh.PriorYearActualValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 2 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.PriorYearActualValue03+sdh.PriorYearActualValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 3 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.PriorYearActualValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 4 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 5 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 6 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 7 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 8 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 9 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 10 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.ActualYTDValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12)
				when 11 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.ActualYTDValue10+sdh.ActualYTDValue11+sdh.PriorYearActualValue12)
				else SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.ActualYTDValue10+sdh.ActualYTDValue11+sdh.ActualYTDValue12)
			end/@NumBenchProviders as SL_Encounters --needs to be devided by number of selected benchmark providers
	into #FactServiceLineTempUnits
		from [fp].[ServiceLineEncounter] sd
			INNER JOIN [fp].[ServiceLineEncounterHistory] sdh on sd.ServiceLineEncounterID = sdh.ServiceLineEncounterID
		WHERE sd.ProviderID in (SELECT ProviderID FROM #BenchProviders)	
		group by 
		sd.BudgetConfigID,
			sd.EntityID,
			sd.EntityGroupConfigID,
			sd.PatientClassID,
			sd.ServiceLineID,
			sd.ServiceLineRollupID,
			sd.AgeCohortID,
			sd.MedicalSurgicalID,
			sd.DepartmentID,
			sd.PayorID,
			sd.PayorGroupID,
			sd.MSDRGID,
			sd.CPTID,
			sd.PhysicianSpecialtyID

	---- main select for calculate charge volume rate
	SELECT sub.*, ISNULL(sub.CV_Units/nullif (sub.SL_EncountersSum,0),0) AS Charge_Rate
	FROM
	(
		SELECT
			fcv.ServiceLineID,
			fcv.PatientClassID,
			fcv.AgeCohortID,
			fcv.MedicalSurgicalID,
			fcv.ServiceEntityID,
			fcv.MSDRGID,
			fcv.PrimaryCPTID,
			fcv.ServiceProviderID,
			fcv.ServiceProviderSpecialtyID,
			fcv.DepartmentID,
			fcv.UBRevCodeID,
			fcv.ChargeCodeID,
			fcv.PerformingProviderID,
			fcv.PerformingProviderSpecialtyID,
			fcv.BillingCPTID,
			fcv.EntityID,
			fcv.CV_Units,
			Sum(sd.SL_Encounters) as SL_EncountersSum	
		FROM #FactChargeVolumeTempUnits	fcv		
			INNER JOIN #FactServiceLineTempUnits sd
				ON fcv.AgeCohortID = sd.AgeCohortID
				AND fcv.MedicalSurgicalID = sd.MedicalSurgicalID
				AND fcv.PatientClassID = sd.PatientClassID
				AND fcv.ServiceLineID = sd.ServiceLineID
				AND fcv.ServiceEntityID = sd.EntityID	
				AND fcv.MSDRGID = sd.MSDRGID				
				AND fcv.PrimaryCPTID = sd.CPTID
		 		AND fcv.ServiceProviderID = sd.ProviderID
				AND fcv.BudgetConfigID = sd.BudgetConfigID
				AND fcv.EntityGroupConfigID = sd.EntityGroupConfigID
		GROUP BY
			fcv.ServiceLineID,
			fcv.PatientClassID,
			fcv.AgeCohortID,
			fcv.MedicalSurgicalID,
			fcv.ServiceEntityID,
			fcv.MSDRGID,
			fcv.PrimaryCPTID,
			fcv.ServiceProviderSpecialtyID,
			fcv.DepartmentID,
			fcv.UBRevCodeID,
			fcv.ChargeCodeID,
			fcv.PerformingProviderID,
			fcv.PerformingProviderSpecialtyID,
			fcv.BillingCPTID, 
			fcv.EntityID,
			fcv.CV_Units,
			fcv.ServiceProviderID
			
	) sub --End subquery
END
GO


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

-- fp.DepartmentChargeVolumeAdjustment_SEL_LIST
CREATE   PROCEDURE [fp].[DepartmentChargeVolumeAdjustment_SEL_LIST]
	@budgetGUID UNIQUEIDENTIFIER,
	@start INT,
	@end INT,
	@search VARCHAR(MAX),
	@filter VARCHAR(MAX),
	@userGUID UNIQUEIDENTIFIER,
	@isDataSecured BIT,
	@dateTimeFormat VARCHAR(30),
	@userTimeZone VARCHAR(50)
AS 
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2020-06-03  LR  	 JAZZ-134		Now including deleted items to be displayed in the activity pane
 ** 2 	 2020-07-01  OP  	 JAZZ-635		Added AP Entity Config roles support
 ** 3 	 2020-08-20  OP  	 JAZZ-4123		Fixed import comment
 ** 4	 2023-01-10	 NT		 JAZZ-45457		Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card
 ** 5    2024-02-22  MY      JAZZ-67143		Filters acting unexpectedly post-adjustment - Issue #2
 *************************************************************/
BEGIN
	CREATE TABLE #departmentsSecurity (
		DepartmentID INT NULL,
		EntityID INT NULL
	)	

	CREATE TABLE #securedAdjustments (
		AdjustmentGUID UNIQUEIDENTIFIER
	)

	DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]()
	DECLARE @pageSize INT = @end - @start;

	SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
	SET @filter = LOWER(NULLIF(@filter, ''))

	SELECT		AdjustmentGUID
				,GroupingHierarchyJSON					
				,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
				,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID
				,AdjustmentType
				,GroupingGUID
	INTO	#adjustments
	FROM	fp.DepartmentChargeVolumeAdjustment AS slea WITH (NOLOCK)	
	WHERE	slea.AdjustmentType IN (0, 1, 2, 3, 4, 12, 13, 14) -- Supported Adjustment types for Charges Adjustments
		AND slea.BudgetConfigGUID = @budgetGUID

	IF @isDataSecured = 1
	BEGIN
		INSERT INTO #departmentsSecurity
		EXEC fp.DepartmentsSecurity_SEL 
		@userGUID = @userGUID,
		@pageName = 'Charge Volumes'

		CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

		SELECT	AdjustmentGUID
				,ahd.ID AS DepartmentID
		INTO	#adjustmentGroupingHierarchyDepartments
		FROM (
				SELECT	adj.AdjustmentGUID
						,adj.GroupingHierarchyJSON
				FROM	#adjustments AS adj
				WHERE	adj.EntityID IS NULL
						AND adj.DepartmentID IS NULL) AS slea
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd
		GROUP BY AdjustmentGUID
				,ahd.ID

		SELECT	adj.AdjustmentGUID,
				ahe.ID AS EntityID
		INTO	#adjustmentGroupingHierarchyEntities
		FROM	#adjustments AS adj
				JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID
																		AND adhd.DepartmentID IS NULL
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
		GROUP BY adj.AdjustmentGUID	
				,ahe.ID
		
		INSERT INTO	#securedAdjustments
		SELECT	res.AdjustmentGUID
		FROM	(
			SELECT	slea.AdjustmentGUID
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID
			GROUP BY slea.AdjustmentGUID 

			UNION ALL

			SELECT	slea.AdjustmentGUID		
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
			WHERE	slea.DepartmentID IS NULL
			GROUP BY slea.AdjustmentGUID

			UNION ALL

			SELECT	aghd.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyDepartments AS aghd
					JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID
			WHERE	dshd.DepartmentID IS NOT NULL
			GROUP BY aghd.AdjustmentGUID

			UNION ALL

			SELECT	aghe.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyEntities AS aghe
					JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
			GROUP BY aghe.AdjustmentGUID

			UNION ALL

			SELECT	adj.AdjustmentGUID
			FROM	#adjustments AS adj
					JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID
					JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID
			WHERE	adj.DepartmentID IS NULL
					AND adj.EntityID IS NULL
					AND aghd.DepartmentID IS NULL
					AND aghe.EntityID IS NULL
			GROUP BY adj.AdjustmentGUID
		) AS res

		-- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2)
		-- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the 
		-- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine.
		-- Essentially what we are doing here is using the child adjustments to find if they fall in security.
		-- In the event we have a child, populate the parent adjustment in the list.
		-- Find all the GroupingGuid's for any child adjustments that fall into security.
		
		SELECT DISTINCT adj.GroupingGUID
		INTO #groupingAdjustments
		FROM #securedAdjustments secured
			INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID
		WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments.

		-- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment.
		INSERT INTO #securedAdjustments
		SELECT adj.AdjustmentGUID
		FROM #adjustments adj
			INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID
			LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID
		WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments
			AND secured.AdjustmentGUID IS NULL

	END
	ELSE 
		BEGIN

			INSERT INTO #securedAdjustments
			SELECT	AdjustmentGUID
			FROM	#adjustments

		END

	CREATE CLUSTERED	INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID)

	SELECT	iadj.AdjustmentGuid
	INTO	#importAdjustments
	FROM	fp.DepartmentChargeAdjustmentImport AS iadj WITH (NOLOCK)
			JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID
			LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID
	WHERE	ds.DepartmentID IS NOT NULL
			OR @isDataSecured = 0
	GROUP BY iadj.AdjustmentGuid

	CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID)	

	SELECT res.TotalRowsCount
		,res.AdjustmentGUID
		,res.BudgetConfigGUID
		,res.AdjustmentType
		,res.[Value]
		,res.AdjustmentFilterJSON
		,res.GroupingHierarchyJSON
		,res.AdjustedProperty
		,res.Comment
		,res.AuthorGUID
		,res.AuthorFullName
		,res.LastModifiedDateUtc
		,res.DateCreatedUtc
		,res.GroupingGUID
		,res.TimeClassID
		,res.BudgetPhaseID
		,res.ClassificationGroupID
		,res.ClassificationCategoryID
		,res.JobCode
		,res.JobCodeCount
		,res.DepartmentCode
		,res.DepartmentCount
		,res.UnitTypeID
		,res.IsRecordDeleted
		,res.IsErrored
		,CAST(res.UnitTypeID AS VARCHAR(5)) AS ImportUnitTypeIDs
	FROM (
		SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount,
			   *
		FROM (
			SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
				  ,slea.AdjustmentGUID
				  ,slea.BudgetConfigGUID
				  ,slea.AdjustmentType
				  ,slea.[Value]
				  ,slea.AdjustmentFilterJSON
				  ,slea.GroupingHierarchyJSON
				  ,slea.AdjustedProperty
				  ,ISNULL(ag.Description, slea.Comment) AS Comment
				  ,slea.AuthorGUID
				  ,slea.AuthorFullName
				  ,slea.LastModifiedDateUtc
				  ,slea.DateCreatedUtc
				  ,slea.GroupingGUID
				  ,slea.TimeClassID
				  ,slea.BudgetPhaseID
				  ,slea.ClassificationGroupID
				  ,slea.ClassificationCategoryID
				  ,slea.UnitTypeId
				  ,NULL AS JobCode
				  ,NULL AS JobCodeCount
				  ,NULL AS DepartmentCode
				  ,NULL AS DepartmentCount
				  ,slea.IsRecordDeleted
				  ,slea.IsErrored
			FROM  (	SELECT	adj.*
							,CAST(145 AS TINYINT) AS UnitTypeId -- UNITS
							,CASE WHEN (AdjustmentType = 7	-- Manager
									OR AdjustmentType = 9)		-- SpreadUnlock
								THEN CAST(3 AS TINYINT) -- Departments
								ELSE CAST(2 AS TINYINT) -- Admin
							END AS BudgetPhaseID
						FROM	fp.DepartmentChargeVolumeAdjustment AS adj WITH (NOLOCK)
								JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = adj.AdjustmentGUID) AS slea
					LEFT JOIN (
						SELECT	p.AdjustmentGuid, 
								ImportUnitTypeIDs = '145'
						FROM	#importAdjustments AS p
						GROUP BY p.AdjustmentGuid
					) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID
					LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
					LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
																	AND slea.ClassificationCategoryID = acc.CategoryID
					LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
					LEFT JOIN (
						SELECT	nsa.GroupingGUID
						FROM	fp.DepartmentChargeVolumeAdjustment as nsa WITH (NOLOCK)
						WHERE	nsa.AdjustmentType IN (12, 13, 14) -- Rollups, keep this so we have a way to filter out the dept adj for the rollups
								AND nsa.BudgetConfigGUID = @budgetGUID
						GROUP BY nsa.GroupingGUID
					) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
			WHERE	(slea.AdjustmentType <> 4 
						OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment
					AND (ra.GroupingGUID IS NULL
						OR slea.AdjustmentType IN (12, 13, 14))
					AND (@search IS NULL 
						OR (
								LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
								OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\'
								OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR acc.[Name] LIKE @search ESCAPE '\'
								OR acg.[Name] LIKE @search ESCAPE '\'
								OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
								OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
							)
						)
					AND (@filter IS NULL
						OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
							SELECT	[value]
							FROM	STRING_SPLIT(@filter, ' ' )
							)
						)
			) AS res_inner
		WHERE res_inner.RowNumber = 1 ) AS res
	ORDER BY res.DateCreatedUtc DESC
	OFFSET @start ROWS
	FETCH NEXT @pageSize ROWS ONLY;
END
GO


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

-- fp.DepartmentsSecurity_SEL
CREATE     PROCEDURE [fp].[DepartmentsSecurity_SEL] (
	@userGUID UNIQUEIDENTIFIER,
	@pageName VARCHAR(30)
)
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI   Description
 ** 1 	 2020-07-01  OP  	 JAZZ-635	Added AP Entity Config roles support
 ** 2    2020-07-31  OP		 JAZZ-3423  Applied entity config roles
 ** 3	 2021-03-21  OP      JAZZ-1144	Removed #FullAccess temp table
 ** 4	 2022-06-02  YR      JAZZ-37924	Added distinct to result
 *************************************************************/
BEGIN
	IF NOT EXISTS(
		SELECT 1 
		FROM UserProfile (readuncommitted) 
		WHERE UserGUID = @UserGUID) 
	BEGIN 
		RETURN 
	END

	--everything user has access to
	CREATE TABLE #UserACL(LootGroupPrefix nvarchar(100), LootID nvarchar(128), IsFullAccess bit, IsReadable bit, IsWritable bit, IsSecurable bit, IsDeletable bit, IsCreatable bit)
	INSERT #UserACL 
		SELECT 
			LootGroupPrefix, 
			LootID, 
			CAST(0 as bit) as IsFullAccess,
			IsReadable, 
			IsWritable, 
			IsSecurable, 
			IsDeletable, 
			IsCreatable 
		FROM 
			dbo.ufn_GetS3ACLByUserGuid(@UserGUID) 
		
	--include items user has no access to
	INSERT #UserACL 
	SELECT
		L.LootGroupPrefix,
		L.LootID as LootID,
		CAST(0 as bit) as IsFullAccess,
		CAST(0 as bit) as IsReadable,
		CAST(0 as bit) as IsWritable,
		CAST(0 as bit) as IsSecurable,
		CAST(0 as bit) as IsDeletable,
		CAST(0 as bit) as IsCreatable
	FROM
		S3Loot L (readuncommitted)
	WHERE
		not exists (select 1 from #UserACL acl where acl.LootID = L.LootID)

	SELECT DISTINCT	res.DepartmentID,
			d.EntityID
	FROM	(
			SELECT	CAST(REPLACE(allAccess.LootID, 'DEPT|', '') AS INT) AS DepartmentID			
			FROM	#UserACL AS allAccess
			WHERE	(allAccess.IsFullAccess = 1 
						OR allAccess.IsReadable = 1) 
					AND allAccess.LootGroupPrefix = 'DEPT'
					) as res
			JOIN fw.DimDepartment AS d ON d.DepartmentID = res.DepartmentID
			JOIN fp.viewDepartmentAccessByUser AS dabu ON dabu.DepartmentID = res.DepartmentID
			JOIN fp.EntityGroupConfig AS ecg ON ecg.EntityGroupConfigID = dabu.EntityGroupConfigID
			JOIN fp.EntityGroupConfigMapping AS ecgm ON ecgm.EntityGroupConfigGuid = ecg.EntityGroupConfigGuid
	WHERE	dabu.AccessType > 0 -- Has Read or Write access
			AND dabu.Section = @pageName
			AND dabu.UserGUID = @UserGUID
			AND d.EntityID = ecgm.EntityID
END
GO


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

-- fp.FactStatisticsProviderLineItemGetEstimatedVolumes
CREATE   PROCEDURE [fp].[FactStatisticsProviderLineItemGetEstimatedVolumes]
	@BudgetConfigID tinyint,
	@ProviderIds [dbo].[SqlInt32ListTableType] readonly,
	@NumBenchProviders smallint,
	@MonthsLoaded tinyint,	
	@DepartmentIds [dbo].[SqlInt32ListTableType] readonly,
	@SubsectionID int = 1,
	@UnitTypeID tinyint = 140
 AS

/**************************************************************

Change History
**************************************************************
CID		Date		Author	WI			Description
1		2021-11-12	AO		JAZZ-26991	Not specified ProviderLineItems shouldn't return
2		2023-04-25	VZ		JAZZ-36898	Removed CheckDepartment parameter 
*************************************************************/

 BEGIN

-- TEST CALL
--DECLARE @BudgetConfigId smallint
--DECLARE @ProviderIds dbo.SqlInt32ListTableType
--DECLARE @NumBenchProviders int
--DECLARE @MonthsLoaded tinyint
--DECLARE @DepartmentIds dbo.SqlInt32ListTableType

--SET @BudgetConfigId = 4
--SET @NumBenchProviders = 2
--SET @MonthsLoaded = 5

--INSERT INTO @ProviderIds values(45272)
--INSERT INTO @ProviderIds values(45393)

--INSERT INTO @DepartmentIds values(0)

--EXEC [fp].[FactStatisticsProviderLineItemGetEstimatedVolumes] @BudgetConfigId, @ProviderIds, @NumBenchProviders, @MonthsLoaded, @DepartmentIds
--END TEST CALL

	SELECT main.*, pli.[Description] as ProviderLineItemDescription from
	(SELECT
		fs.ProviderLineItemID,
		fs.AccountID,
		fs.PayorID,
		fs.PatientClassID,		
		case @Monthsloaded
			when 1 then	SUM(fsh.ActualYTDValue01+fsh.PriorYearActualValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 2 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 3 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 4 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 5 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 6 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 7 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 8 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 9 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 10 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
			when 11 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.PriorYearActualValue12)
			else SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.ActualYTDValue12)
		end/@NumBenchProviders as EstimatedVolume
	FROM [fp].[FactStatistics] fs
	INNER JOIN [fp].[FactStatisticsHistory] fsh on fsh.StatisticsID = fs.StatisticsID
	WHERE fs.BudgetConfigID = @BudgetConfigID
		AND fs.SubsectionID = @SubsectionID
		AND fs.UnitTypeID = @UnitTypeID		
		AND fs.ProviderID IN (SELECT [value] from @ProviderIds)
		AND fs.DepartmentID IN (SELECT [value] from @DepartmentIds)
		AND fs.ProviderLineItemID <> 0
	GROUP BY
		fs.ProviderLineItemID,
		fs.AccountID,
		fs.PayorID,
		fs.PatientClassID) as main
	INNER JOIN [fp].[ProviderLineItem] pli ON main.ProviderLineItemID = pli.ProviderLineItemID
		
END
GO


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

-- fp.GeneralLedgerAdjustment_SEL_LIST
CREATE     PROCEDURE [fp].[GeneralLedgerAdjustment_SEL_LIST]
    @budgetGUID UNIQUEIDENTIFIER,
    @start INT,
    @end INT,
    @search VARCHAR(MAX),
    @filter VARCHAR(MAX),
    @userGUID UNIQUEIDENTIFIER,
    @isDataSecured BIT,
    @dateTimeFormat VARCHAR(30),
    @userTimeZone VARCHAR(50)
AS 
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI   			Description
 ** 1 	 2020-06-03  LR  	 JAZZ-134		Now including deleted items to be displayed in the activity pane
 ** 2 	 2020-07-01  OP  	 JAZZ-635		Added AP Entity Config roles support
 ** 3 	 2020-08-20  OP  	 JAZZ-4123		Fixed import comment
 ** 4 	 2020-11-23  BW  	 JAZZ-9982		Now including non-staffing (My Budgets) adjustments (AdjustmentType 16) to be displayed in the activity pane
 ** 5 	 2020-03-10  MD  	 JAZZ-10331		Updating manager adjustment pull to bring back distinct accounts and not count of rows
 ** 6	 2021-05-14  ZH		 JAZZ-18180 	Adding view more details for projection time class activity cards 
 ** 7	 2021-07-09  OP		 JAZZ-22930 	Fixed search by Projection for Manager Cards (Adjustment Type 16)
 ** 8	 2021-11-19  MY		 JAZZ-28801 	Added Variable Reset to Acceptable Types
 ** 9	 2021-11-19  YR		 JAZZ-34640 	Added SubAccountItemized adjustment type
 ** 10	 2022-05-26  YR		 JAZZ-38119 	Fixed search SubAccountItemized adjustment type by comment
 ** 11	 2022-06-02  YR		 JAZZ-37924 	Hide restricted SubAccountItemized cards for user
 ** 12	 2022-06-30  AO		 JAZZ-37651 	Hide restricted Manager Adjustment cards for local user
 ** 13   2022-07-04  DM      JAZZ-40016     Fixed an issue with STRING_AGG
 ** 14   2022-11-25  YR      JAZZ-46173     Added AddAccount adjustment type
 ** 15   2022-12-06  YR      JAZZ-42980     Return AdjustmentID
 ** 16   2023-01-10  NT		 JAZZ-45457		Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card
 ** 17   2023-01-26  DM      JAZZ-48779		Changed table for old my budgets adjustments retrievement
 ** 18   2023-11-08  DM      JAZZ-61425		Changed import adjustments unit type selection to support dollars per uos
 ** 19   2024-02-22  MY      JAZZ-67143		Filters acting unexpectedly post-adjustment - Issue #2
 ** 20   2024-05-03  MZ		 JAZZ-69734		Renamed GeneralLedgerAdjustmentItemization to GeneralLedgerMyBudgetAdjustment
*************************************************************/
BEGIN
    
	EXEC [dbo].[procSysDropTempTable] '#departmentsSecurity'
	EXEC [dbo].[procSysDropTempTable] '#securedAdjustments'
	EXEC [dbo].[procSysDropTempTable] '#adjustments'
	EXEC [dbo].[procSysDropTempTable] '#adjustmentGroupingHierarchyDepartments'
	EXEC [dbo].[procSysDropTempTable] '#adjustmentGroupingHierarchyEntities'
	EXEC [dbo].[procSysDropTempTable] '#groupingAdjustments'

    CREATE TABLE #departmentsSecurity (
        DepartmentID INT NULL,
        EntityID INT NULL
    )    

    CREATE TABLE #securedAdjustments (
        AdjustmentGUID UNIQUEIDENTIFIER
    )

    DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]()
    DECLARE @pageSize INT = @end - @start;

    SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
    SET @filter = LOWER(NULLIF(@filter, ''))

    SELECT 
		AdjustmentGUID,
        GroupingHierarchyJSON,
        JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID,
        JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID,
		AdjustmentType,
		GroupingGUID
    INTO #adjustments
    FROM fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK)    
    WHERE slea.AdjustmentType IN (0, 1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14, 16, 18, 19) -- Supported Adjustment types for GL Adjustments. MY: Need to look to see if this necessary. I don't think we really need to be filtering out types.
        AND slea.BudgetConfigGUID = @budgetGUID
        
    IF @isDataSecured = 1
    BEGIN
        INSERT INTO #departmentsSecurity
        EXEC fp.DepartmentsSecurity_SEL 
			@userGUID = @userGUID,
			@pageName = 'General Ledger'

        CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

        SELECT    AdjustmentGUID
                ,ahd.ID AS DepartmentID
        INTO    #adjustmentGroupingHierarchyDepartments
        FROM (
                SELECT    adj.AdjustmentGUID
                        ,adj.GroupingHierarchyJSON
                FROM    #adjustments AS adj
                WHERE    adj.EntityID IS NULL
                        AND adj.DepartmentID IS NULL) AS slea
                OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd
        GROUP BY AdjustmentGUID
                ,ahd.ID

        SELECT    adj.AdjustmentGUID,
                ahe.ID AS EntityID
        INTO    #adjustmentGroupingHierarchyEntities
        FROM    #adjustments AS adj
                JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID
                                                                        AND adhd.DepartmentID IS NULL
                OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
        GROUP BY adj.AdjustmentGUID    
                ,ahe.ID
        
        INSERT INTO #securedAdjustments
        SELECT    res.AdjustmentGUID
        FROM    (
            SELECT    slea.AdjustmentGUID
            FROM    #adjustments AS slea
                    JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID
            GROUP BY slea.AdjustmentGUID 

            UNION ALL

            SELECT    slea.AdjustmentGUID        
            FROM    #adjustments AS slea
                    JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
            WHERE    slea.DepartmentID IS NULL
            GROUP BY slea.AdjustmentGUID

            UNION ALL

            SELECT    aghd.AdjustmentGUID        
            FROM    #adjustmentGroupingHierarchyDepartments AS aghd
                    JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID
            WHERE    dshd.DepartmentID IS NOT NULL
            GROUP BY aghd.AdjustmentGUID

            UNION ALL

            SELECT    aghe.AdjustmentGUID        
            FROM    #adjustmentGroupingHierarchyEntities AS aghe
                    JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
            GROUP BY aghe.AdjustmentGUID

            UNION ALL

            SELECT    adj.AdjustmentGUID
            FROM    #adjustments AS adj
                    JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID
                    JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID
            WHERE    adj.DepartmentID IS NULL
                    AND adj.EntityID IS NULL
                    AND aghd.DepartmentID IS NULL
                    AND aghe.EntityID IS NULL
            GROUP BY adj.AdjustmentGUID
        ) AS res

		-- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2)
		-- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the 
		-- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine.
		-- Essentially what we are doing here is using the child adjustments to find if they fall in security.
		-- In the event we have a child, populate the parent adjustment in the list.

		-- Find all the GroupingGuid's for any child adjustments that fall into security.
		SELECT DISTINCT adj.GroupingGUID
		INTO #groupingAdjustments
		FROM #securedAdjustments secured
			INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID
		WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments.

		-- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment.
		INSERT INTO #securedAdjustments
		SELECT adj.AdjustmentGUID
		FROM #adjustments adj
			INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID
			LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID
		WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments
			AND secured.AdjustmentGUID IS NULL

    END
    ELSE 
    BEGIN
        INSERT INTO #securedAdjustments
        SELECT AdjustmentGUID
        FROM #adjustments
    END

    CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID)

    SELECT    iadj.AdjustmentGuid, 
            iadj.UnitTypeID,
			iadj.OriginalUnitTypeID
    INTO    #importAdjustments
    FROM    fp.GeneralLedgerAdjustmentImport AS iadj WITH (NOLOCK)
            JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID
            LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID
    WHERE    ds.DepartmentID IS NOT NULL
            OR @isDataSecured = 0
    GROUP BY iadj.AdjustmentGuid,
            iadj.UnitTypeID,
			iadj.OriginalUnitTypeID

    CREATE CLUSTERED    INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID)

    SELECT res.TotalRowsCount
        ,res.AdjustmentGUID
		,res.AdjustmentID
        ,res.BudgetConfigGUID
        ,res.AdjustmentType
        ,res.[Value]
        ,res.AdjustmentFilterJSON
        ,res.GroupingHierarchyJSON
        ,res.AdjustedProperty
        ,res.Comment
        ,res.AuthorGUID
        ,res.AuthorFullName
        ,res.LastModifiedDateUtc
        ,res.DateCreatedUtc
        ,res.GroupingGUID
        ,res.TimeClassID
        ,res.BudgetPhaseID
        ,res.ClassificationGroupID
        ,res.ClassificationCategoryID
        ,res.JobCode
        ,res.JobCodeCount
        ,res.DepartmentCode
        ,res.DepartmentName
        ,res.DepartmentCount
		,res.AccountCount
        ,res.AccountName
        ,res.UnitTypeID
        ,res.ImportUnitTypeIDs
		,res.IsRecordDeleted
		,res.IsErrored
    FROM (
        SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, 
                *
        FROM (
            SELECT    ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
       ,slea.AdjustmentGUID
					,slea.AdjustmentID
                    ,slea.BudgetConfigGUID
                    ,slea.AdjustmentType
                    ,slea.[Value]
                    ,slea.AdjustmentFilterJSON
                    ,slea.GroupingHierarchyJSON
                    ,slea.AdjustedProperty
                    ,ISNULL(ag.Description, slea.Comment) AS Comment
                    ,slea.AuthorGUID
                    ,slea.AuthorFullName
                    ,slea.LastModifiedDateUtc
                    ,slea.DateCreatedUtc
                    ,slea.GroupingGUID
                    ,slea.TimeClassID
                    ,slea.BudgetPhaseID
                    ,slea.ClassificationGroupID
                    ,slea.ClassificationCategoryID
                    ,slea.UnitTypeId
                    ,NULL AS JobCode
                    ,NULL AS JobCodeCount
                    ,NULL AS DepartmentCode
                    ,NULL AS DepartmentName
                    ,NULL AS DepartmentCount
					,NULL AS AccountCount
                    ,NULL AS AccountName
                    ,sai.ImportUnitTypeIDs
					,slea.IsRecordDeleted
					,slea.IsErrored
            FROM    fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK)
                    JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
                    LEFT JOIN (
                        SELECT    p.AdjustmentGUID, 
                                ImportUnitTypeIDs =
                                TRIM(STUFF(
                                    (SELECT N' ' + CAST(ISNULL(p2.OriginalUnitTypeID, p2.UnitTypeID) AS VARCHAR(5))
                                    FROM    #importAdjustments AS p2
                                    WHERE    p2.AdjustmentGUID = p.AdjustmentGUID
                                    GROUP BY p2.AdjustmentGUID, 
                                            p2.UnitTypeID,
											p2.OriginalUnitTypeID
                                    FOR XML PATH(N''))
                                , 1, 0, N''))
                        FROM    #importAdjustments AS p
                        GROUP BY p.AdjustmentGUID
                    ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID
                    LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
                    LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
                    LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
                                                                    AND slea.ClassificationCategoryID = acc.CategoryID
                    LEFT JOIN (
                        SELECT    nsa.GroupingGUID
                        FROM    fp.GeneralLedgerAdjustment as nsa WITH (NOLOCK)
                        WHERE    nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types
                                AND nsa.BudgetConfigGUID = @budgetGUID
                        GROUP BY nsa.GroupingGUID
                    ) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
            WHERE    (slea.AdjustmentType <> 4 
                        OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment
                    AND slea.AdjustmentType NOT IN (7, 16, 18, 19) 
                    AND (ra.GroupingGUID IS NULL
                        OR slea.AdjustmentType IN (12, 13, 14))
                    AND (@search IS NULL 
                        OR (
                                LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                                OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\'
                                OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR acc.[Name] LIKE @search ESCAPE '\'
                                OR acg.[Name] LIKE @search ESCAPE '\'
                                OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
                                OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
                                OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1
                            )
                        )
                    AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
                            SELECT    [value]
          FROM    STRING_SPLIT(@filter, ' ' )
                            )
                        )
            UNION ALL
            
            -- Manager Adjustments
            SELECT    ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, adjComment.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                 ,slea.AdjustmentGUID
				 ,slea.AdjustmentID
                 ,slea.BudgetConfigGUID
                 ,slea.AdjustmentType
                 ,NULL AS [Value]
                 ,slea.AdjustmentFilterJSON
                 ,slea.GroupingHierarchyJSON
                 ,slea.AdjustedProperty
                 ,NULL AS Comment
                 ,slea.AuthorGUID
                 ,slea.AuthorFullName
                 ,slea.LastModifiedDateUtc
                 ,slea.DateCreatedUtc
                 ,slea.GroupingGUID
                 ,adjComment.TimeClassID
                 ,slea.BudgetPhaseID
                 ,slea.ClassificationGroupID
                 ,slea.ClassificationCategoryID
                 ,slea.UnitTypeId
                 ,NULL AS JobCode
                 ,NULL AS JobCodeCount
                 ,NULL AS DepartmentCode
                 ,adjComment.DepartmentName
                 ,adjComment.DepartmentCount
				 ,NULL AS AccountCount
                 ,adjComment.AccountName
                 ,NULL AS ImportUnitTypeIDs
				 ,slea.IsRecordDeleted
				 ,slea.IsErrored
            FROM    fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK)
                        JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
                        LEFT JOIN (
                            SELECT
                                 oldMyBudg.AdjustmentGUID
								 ,oldMyBudg.TimeClassID
                                 ,dept.Name AS DepartmentName
                                 ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName
                                 ,COUNT(dept.DepartmentID) AS DepartmentCount
                            FROM  (
									SELECT
										 OBJ.AdjustmentGUID
										 ,OBJ.TimeClassID
										 ,OBJ.DepartmentID
										 ,OBJ.AccountID
									FROM  fp.GeneralLedgerManagerAdjustmentData AS OBJ WITH (NOLOCK)
									GROUP BY OBJ.AdjustmentGUID, OBJ.DepartmentID, OBJ.AccountID, OBJ.TimeClassID
							) oldMyBudg
								  JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = oldMyBudg.DepartmentID      
								  JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = oldMyBudg.AccountID
								  LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = oldMyBudg.DepartmentID 
							WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL
                            GROUP BY oldMyBudg.AdjustmentGUID, dept.Name, oldMyBudg.TimeClassID
                        ) AS adjComment ON adjComment.AdjustmentGUID = slea.AdjustmentGUID
                        LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
                        LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID
                                                                                           AND slea.ClassificationCategoryID = acc.CategoryID
            WHERE    slea.AdjustmentType = 7
                AND (@search IS NULL
                OR (
                        LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                        OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                        OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                        OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                        OR acc.[Name] LIKE @search ESCAPE '\'
                        OR acg.[Name] LIKE @search ESCAPE '\'
                        OR 'my budgets' LIKE @search ESCAPE '\'
                        OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\'
                        OR LOWER(adjComment.AccountName) LIKE @search ESCAPE '\'
                    )
                )
                AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, adjComment.TimeClassID, slea.BudgetPhaseID) IN (SELECT [value] FROM  STRING_SPLIT(@filter, ' ' ) )
                        )
				AND adjComment.DepartmentName IS NOT NULL
            UNION ALL



		-- SubAccount Adjustments
            SELECT    ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                 ,slea.AdjustmentGUID
				 ,slea.AdjustmentID
                 ,slea.BudgetConfigGUID
                 ,slea.AdjustmentType
                 ,NULL AS [Value]
                 ,slea.AdjustmentFilterJSON
                 ,slea.GroupingHierarchyJSON
                 ,slea.AdjustedProperty
				 ,slea.Comment
                 ,slea.AuthorGUID
                 ,slea.AuthorFullName
                 ,slea.LastModifiedDateUtc
                 ,slea.DateCreatedUtc
                 ,slea.GroupingGUID
                 ,TimeClassID
                 ,slea.BudgetPhaseID
                 ,slea.ClassificationGroupID
                 ,slea.ClassificationCategoryID
                 ,slea.UnitTypeId
                 ,NULL AS JobCode
                 ,NULL AS JobCodeCount
                 ,NULL AS DepartmentCode
                 ,subAccountAdj.DepartmentName
                 ,subAccountAdj.DepartmentCount
				 ,subAccountAdj.AccountCount
                 ,subAccountAdj.AccountName
                 ,NULL AS ImportUnitTypeIDs
				 ,slea.IsRecordDeleted
				 ,slea.IsErrored
            FROM    fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK)
                        JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
                        LEFT JOIN (
                            SELECT
                                 OBJ.AdjustmentID AS AdjustmentID
								 ,STRING_AGG(CAST(dept.Name AS NVARCHAR(MAX)), ';') AS DepartmentName
								 ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName
								 ,COUNT(distinct acc.AccountID) AS AccountCount
                                 ,COUNT(distinct dept.DepartmentID) AS DepartmentCount
                            FROM  fp.GeneralLedgerSubAccountItemizedAdjustment AS OBJ WITH (NOLOCK)
                                      JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID      
                                      JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = OBJ.AccountID
									  LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID 
							WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL
                            GROUP BY OBJ.AdjustmentID
                        ) AS subAccountAdj ON subAccountAdj.AdjustmentID = slea.AdjustmentID
                        LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
                        LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID
                                                                                           AND slea.ClassificationCategoryID = acc.CategoryID
            WHERE    slea.AdjustmentType = 18
           AND (@search IS NULL
                OR (
                        LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                        OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
						OR LOWER(slea.Comment) LIKE @search ESCAPE '\'
                        OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                        OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                        OR acc.[Name] LIKE @search ESCAPE '\'
                        OR acg.[Name] LIKE @search ESCAPE '\'
                        OR 'sub-account detail' LIKE @search ESCAPE '\'
                        OR LOWER(subAccountAdj.DepartmentName) LIKE @search ESCAPE '\'
                        OR LOWER(subAccountAdj.AccountName) LIKE @search ESCAPE '\'
                    )
                )
				AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (SELECT [value] FROM  STRING_SPLIT(@filter, ' ' ) )
                    )
				AND subAccountAdj.DepartmentName IS NOT NULL
				
				UNION ALL


		 -- AddAccount Adj
		 SELECT    ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                 ,slea.AdjustmentGUID
				 ,slea.AdjustmentID
                 ,slea.BudgetConfigGUID
                 ,slea.AdjustmentType
                 ,NULL AS [Value]
                 ,slea.AdjustmentFilterJSON
                 ,slea.GroupingHierarchyJSON
                 ,slea.AdjustedProperty
				 ,slea.Comment
                 ,slea.AuthorGUID
                 ,slea.AuthorFullName
                 ,slea.LastModifiedDateUtc
                 ,slea.DateCreatedUtc
                 ,slea.GroupingGUID
                 ,TimeClassID
                 ,slea.BudgetPhaseID
                 ,NULL AS ClassificationGroupID
                 ,NULL AS ClassificationCategoryID
                 ,slea.UnitTypeId
                 ,NULL AS JobCode
                 ,NULL AS JobCodeCount
                 ,NULL AS DepartmentCode
                 ,addAccountAdj.DepartmentName
                 ,addAccountAdj.DepartmentCount
				 ,addAccountAdj.AccountCount
                 ,addAccountAdj.AccountName
                 ,NULL AS ImportUnitTypeIDs
				 ,slea.IsRecordDeleted
				 ,slea.IsErrored
            FROM    fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK)
                        JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
                        LEFT JOIN (
                            SELECT
                                 OBJ.AdjustmentID AS AdjustmentID
								 ,STRING_AGG(CAST(dept.Name AS NVARCHAR(MAX)), ';') AS DepartmentName
								 ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName
								 ,STRING_AGG(CAST(OBJ.Comment AS NVARCHAR(MAX)), ';') AS Comment
								 ,COUNT(distinct acc.AccountID) AS AccountCount
                                 ,COUNT(distinct dept.DepartmentID) AS DepartmentCount
                            FROM  fp.GeneralLedgerAddAccountAdjustment AS OBJ WITH (NOLOCK)
                                      JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID      
                                      JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = OBJ.AccountID
									  LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID 
							WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL
                            GROUP BY OBJ.AdjustmentID
                        ) AS addAccountAdj ON addAccountAdj.AdjustmentID = slea.AdjustmentID
            WHERE    slea.AdjustmentType = 19
                AND (@search IS NULL
                OR (
                        LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
						OR LOWER(addAccountAdj.Comment) LIKE @search ESCAPE '\'
                        OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                        OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                        OR 'add account' LIKE @search ESCAPE '\'
                        OR LOWER(addAccountAdj.DepartmentName) LIKE @search ESCAPE '\'
                        OR LOWER(addAccountAdj.AccountName) LIKE @search ESCAPE '\'
                    )
                )
				AND addAccountAdj.DepartmentName IS NOT NULL

		 UNION ALL
            -- Manager Adjustments - non-staffing adj type 16
         SELECT    ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, glai.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                 ,slea.AdjustmentGUID
				 ,slea.AdjustmentID
                 ,slea.BudgetConfigGUID
                 ,slea.AdjustmentType
                 ,NULL AS [Value]
                 ,slea.AdjustmentFilterJSON
                 ,slea.GroupingHierarchyJSON
                 ,slea.AdjustedProperty
                 ,NULL AS Comment
                 ,slea.AuthorGUID
                 ,slea.AuthorFullName
                 ,slea.LastModifiedDateUtc
                 ,slea.DateCreatedUtc
                 ,slea.GroupingGUID
                 ,glai.TimeClassID
                 ,slea.BudgetPhaseID
                 ,slea.ClassificationGroupID
                 ,slea.ClassificationCategoryID
                 ,slea.UnitTypeId
                 ,NULL AS JobCode
                 ,NULL AS JobCodeCount
                 ,NULL AS DepartmentCode
                 ,adjComment.DepartmentName
                 ,adjComment.DepartmentCount
				 ,NULL AS AccountCount
                 ,adjComment.AccountName
                 ,NULL AS ImportUnitTypeIDs
				 ,slea.IsRecordDeleted
				 ,slea.IsErrored
            FROM    fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK)
						JOIN fp.GeneralLedgerMyBudgetAdjustment glai on slea.AdjustmentID = glai.AdjustmentID
                        JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
                        LEFT JOIN (
                            SELECT
                                 OBJ.AdjustmentID
                                 ,OBJ.TimeClassID
                                 ,dept.Name AS DepartmentName
                                 ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName
								 --JAZZ-10331
                                 ,COUNT(DISTINCT acc.AccountID) AS DepartmentCount
                            FROM  fp.GeneralLedgerMyBudgetAdjustment AS OBJ WITH (NOLOCK)
                                      JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID      
                                      JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = OBJ.AccountID
                            -- JAZZ-18180 adding time class to group by
                            GROUP BY OBJ.AdjustmentID, OBJ.TimeClassID, dept.Name
                        ) AS adjComment ON adjComment.AdjustmentID = slea.AdjustmentID and adjComment.TimeClassID = glai.TimeClassID
                        LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
                        LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID
                                                                                           AND slea.ClassificationCategoryID = acc.CategoryID
            WHERE    slea.AdjustmentType = 16
                AND (@search IS NULL
                OR (
                        LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                        OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                        OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                        OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                        OR acc.[Name] LIKE @search ESCAPE '\'
                        OR acg.[Name] LIKE @search ESCAPE '\'
                        OR 'my budgets' LIKE @search ESCAPE '\'
                        OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\'
                        OR LOWER(adjComment.AccountName) LIKE @search ESCAPE '\'
                    )
                )
                AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, glai.TimeClassID, slea.BudgetPhaseID) IN (SELECT [value] FROM  STRING_SPLIT(@filter, ' ' ) )
                        )
            ) AS res_inner
        WHERE res_inner.RowNumber = 1 ) AS res
    ORDER BY res.DateCreatedUtc DESC    
    OFFSET @start ROWS
    FETCH NEXT @pageSize ROWS ONLY
END
GO


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

-- fp.GetAllDepartmentsAccessInfo
CREATE PROCEDURE fp.GetAllDepartmentsAccessInfo (@entityGroupConfigIds [dbo].[SqlInt32ListTableType] READONLY, @userGUID UNIQUEIDENTIFIER)
 WITH RECOMPILE
 AS
 BEGIN
 	IF OBJECT_ID('tempdb..#entityGroupConfigIds') IS NOT NULL drop table #entityGroupConfigIds
	IF OBJECT_ID('tempdb..#deptAccess') IS NOT NULL drop table #deptAccess
	IF OBJECT_ID('tempdb..#workflows') IS NOT NULL drop table #workflows
	IF OBJECT_ID('tempdb..#DistinctRoleID') IS NOT NULL drop table #DistinctRoleID
	IF OBJECT_ID('tempdb..#validRoleIDs') IS NOT NULL drop table #validRoleIDs
	IF OBJECT_ID('tempdb..#workflowSecurityItems') IS NOT NULL drop table #workflowSecurityItems
	IF OBJECT_ID('tempdb..#APEDepartmentWorkflowStatus') IS NOT NULL drop table #APEDepartmentWorkflowStatus
	IF OBJECT_ID('tempdb..#possibleRoleIds') IS NOT NULL drop table #possibleRoleIds
	
	DECLARE @MONET_USERGUID UNIQUEIDENTIFIER = '10101010-1111-0000-1111-101010101010'
	DECLARE @DEPT_SECURITY_LOOT_PREFIX VARCHAR(50) = 'DEPT';

	CREATE TABLE #entityGroupConfigIds (EntityGroupConfigId INT PRIMARY KEY CLUSTERED)

	INSERT INTO #entityGroupConfigIds (EntityGroupConfigId)
	SELECT value
	FROM @entityGroupConfigIds

	CREATE TABLE #deptAccess (
		DepartmentID INT PRIMARY KEY CLUSTERED,
		CanAccess BIT,
		CanEdit BIT,
		STATUS INT
,
		CanReject BIT,
		CanSubmit BIT,
		CurrentStepID BIT,
		CurrentStepName VARCHAR(max)
		)

	CREATE TABLE #workflows (
		WorkflowStepID INT,
		NAME VARCHAR(max),
		WorkflowStepOrder INT,
		EntityGroupConfigID INT,
		RoleID INT,
		IsEditable BIT,
		IsDeleted BIT
		)
	
	CREATE UNIQUE CLUSTERED INDEX IX_tmpWorkflow ON #workflows
	(
		EntityGroupConfigID,
		WorkflowStepID,
		RoleID
	)

	INSERT INTO #workflows
	SELECT apwf.WorkflowStepID,
		apwf.NAME,
		apwf.WorkflowStepOrder,
		apwf.EntityGroupConfigID,
		apwfr.RoleID,
		apwf.IsEditable,
		0 AS isDeleted
	FROM fp.APEWorkflow apwf with (readuncommitted)
	INNER JOIN fp.APEWorkflowRole apwfr with (readuncommitted) ON apwf.WorkflowStepID = apwfr.WorkflowStepID
	INNER JOIN #entityGroupConfigIds egc ON apwf.EntityGroupConfigID = egc.EntityGroupConfigId

	CREATE TABLE #DistinctRoleID 
	(
		RoleID INT,
		WorkflowStepID INT
	)

	CREATE UNIQUE CLUSTERED INDEX IX_tmpDistinctRoleID ON #DistinctRoleID
	(
		RoleID,
		WorkflowStepID
	)

	INSERT INTO #DistinctRoleID (RoleID, WorkflowStepID)
	SELECT DISTINCT RoleID, WorkflowStepID
	FROM #workflows

	CREATE TABLE #possibleRoleIds (RoleID INT,WorkflowStepID INT)

	CREATE UNIQUE CLUSTERED INDEX IX_tmpPossibleRoleID ON #possibleRoleIds
	(
		RoleID,
		WorkflowStepID
	)

	INSERT INTO #possibleRoleIds
	SELECT RoleID, WorkflowStepID
	FROM #DistinctRoleID
	UNION
	SELECT AdminRoleID, WorkflowStepID
	FROM [fp].[APEEntityGroupConfigSetting] AEGC with (readuncommitted)
	inner join #workflows wf on wf.EntityGroupConfigId = AEGC.EntityGroupConfigID
	INNER JOIN #entityGroupConfigIds egc ON AEGC.EntityGroupConfigID = egc.EntityGroupConfigId

	CREATE TABLE #workflowSecurityItems (
		DepartmentID INT,
		UserGUID UNIQUEIDENTIFIER,
		RoleID INT,
		LootID NVARCHAR(128)
		)
	CREATE UNIQUE CLUSTERED INDEX IX_tmpWorkflowSecurityItems ON #workflowSecurityItems
	(
		DepartmentID,
		UserGUID,
		RoleID
	)


	CREATE TABLE #validRoleIds (RoleID INT PRIMARY KEY CLUSTERED)
	INSERT INTO #validRoleIds
	SELECT DISTINCT DR.RoleID
	FROM
	dbo.S3LootGroup LG with (readuncommitted)
	INNER JOIN dbo.S3RoleAssignment RA with (readuncommitted) on LG.LootGroupID = RA.LootGroupID
	INNER JOIN #DistinctRoleID dr ON dr.RoleID = RA.RoleID and Ra.IdentityGUID = @userGUID and @userGuid <> @MONET_USERGUID
	WHERE LootID LIKE 'Dept|%'

	declare @validRoleIdsCount int = (select count(*) from #validRoleIds)

	INSERT INTO #workflowSecurityItems
	SELECT DepartmentID = Replace(LootID, 'Dept|', ''),
		UserGUID,
		RoleID,
		LootID
	FROM [dbo].[viewS3ACLDetail] acl where UserGUID = @userGuid and @userGuid <> @MONET_USERGUID
	and LootID LIKE 'Dept|%' and CASE WHEN acl.WriteAllowpts > acl.WriteDenypts then CAST(1 as bit) else CAST(0 as bit) end = 1 -- IsWritable
	and (acl.RoleID in (select distinct RoleID from #validRoleIds) or @validRoleIdsCount = 0)

	UNION

	SELECT DepartmentID,
		UserGUID = @userGUID,
		R.RoleID,
		LootID = @DEPT_SECURITY_LOOT_PREFIX + '|' + CAST(DepartmentID AS VARCHAR(20))
	FROM #DistinctRoleID R
	CROSS JOIN fw.viewDimDepartment_Real vw
	WHERE @userGUID = @MONET_USERGUID

	CREATE TABLE #APEDepartmentWorkflowStatus (
		DepartmentWorkflowStatusID INT,
		WorkflowStepID INT,
		WorkflowStepOrder INT,
		DepartmentID INT,
		EnteredStepDateTimeUtc DATETIME,
		STATUS TINYINT,
		NAME VARCHAR(250),
		RoleID INT,
		CanAccess BIT,
	
	RN int
		)
	CREATE UNIQUE CLUSTERED INDEX IX_tmpAPEDepartmentWorkflowStatus ON #APEDepartmentWorkflowStatus
	(
		DepartmentWorkflowStatusID,
		WorkflowStepID,
		DepartmentID,
		RoleID,
		RN
	)

	INSERT INTO #APEDepartmentWorkflowStatus
	SELECT wfs.DepartmentWorkflowStatusID,
		wfs.WorkflowStepID,
		wf.WorkflowStepOrder,
		wfs.DepartmentID,
		wfs.EnteredStepDateTimeUtc,
		wfs.STATUS,
		wf.NAME,
		wfsi.RoleID,
		CanAccess = MAX(isnull(wfsi.RoleID / wfsi.RoleID, 0)) over (partition by wfs.DepartmentID),
		RN = Row_number() over (partition by wfs.DepartmentID,wf.[EntityGroupConfigID] order BY wfs.EnteredStepDateTimeUtc desc)
	FROM #entityGroupConfigIds egc
	INNER JOIN [fp].[APEWorkflow] wf  ON wf.[EntityGroupConfigID] = egc.[EntityGroupConfigID]
	INNER JOIN fp.APEWorkflowRole wfr  on wfr.WorkflowStepID = wf.WorkflowStepID
	inner JOIN fp.APEDepartmentWorkflowStatus wfs  ON wf.WorkflowStepID = wfs.WorkflowStepID
	inner JOIN #workflowSecurityItems wfsi ON wfsi.DepartmentID = wfs.DepartmentID
	WHERE wfs.DepartmentID IS NOT NULL

	CREATE TABLE #AccessRules
	(
		DepartmentID INT,
		WorkflowStepID INT
	)

	CREATE UNIQUE CLUSTERED INDEX IX_tmpAccessRules ON #AccessRules
	(
		DepartmentID,
		WorkflowStepID
	)

	INSERT INTO #AccessRules
	SELECT Distinct DepartmentID,dws.WorkflowStepID
	FROM #possibleRoleIds pri
	INNER JOIN #APEDepartmentWorkflowStatus dws ON dws.RoleID = pri.RoleID AND dws.[WorkflowStepID] = pri.WorkflowStepID


	SELECT dws.DepartmentID,
		dws.STATUS,
		CAST(dws.CanAccess as BIT) as CanAccess,
		CanEdit = CAST(CASE WHEN canAccess = 0 OR NOT EXISTS (SELECT 1 FROM #DistinctRoleID) THEN 0 
					   WHEN EXISTS (SELECT 1 FROM #AccessRules VR WHERE VR.DepartmentID = dws.DepartmentID and VR.WorkflowStepID = dws.WorkflowStepID) THEN 1 
					   ELSE 0 
				  END as BIT),
		CanReject = CAST(CASE WHEN (WorkflowStepOrder > 1 AND WorkflowStepOrder < 1000)
							  AND CASE WHEN canAccess = 0 OR NOT EXISTS (SELECT 1 FROM #DistinctRoleID) THEN 0 
									   WHEN EXISTS (SELECT 1 FROM #AccessRules VR WHERE VR.DepartmentID = dws.DepartmentID and VR.WorkflowStepID = dws.WorkflowStepID) THEN 1 
									   ELSE 0 
								  END = 1 THEN 1 
						ELSE 0 
					END as BIT),
		CanSubmit = CAST(CASE WHEN canAccess = 0	AND NOT EXISTS (SELECT 1 FROM #DistinctRoleID) THEN 0 
						WHEN EXISTS (SELECT 1 FROM #AccessRules VR WHERE VR.DepartmentID = dws.DepartmentID and VR.WorkflowStepID = dws.WorkflowStepID) THEN 1 
						ELSE 0
					END as BIT),
		CurrentStepID = WorkflowStepID,
		CurrentStepName = dws.NAME
	FROM #APEDepartmentWorkflowStatus dws
	JOIN	FW.DimDepartment	as dd
		ON	dws.DepartmentID = dd.DepartmentID
	JOIN	FW.DimEntity		as de
		ON dd.EntityID = de.EntityID
	JOIN	fp.EntityGroupConfigMapping as egcm
		ON egcm.EntityID = de.EntityID
	JOIN	fp.EntityGroupConfig as EGC
		on egcm.EntityGroupConfigGUID = EGC.EntityGroupConfigGUID
	JOIN	#entityGroupConfigIds AS GC
		on	EGC.EntityGroupConfigID = GC.EntityGroupConfigId
	WHERE RN = 1
END
GO


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

-- fp.ProcReportFactChargeToStatisticsCrosswalkBackup
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI				Description
** 1    2020-05-08  LR          JAZZ-20			Initial
** 2	2020-13-08  MY			JAZZ-4079		Adding feature flag to short circuit the proc
** 3	2020-13-08  MY			JAZZ-4098		Performance tuning
** 4	2020-01-02  MY			JAZZ-14421		Remove old FF call that is no longer needed
** 5	2021-11-10  BW			JAZZ-1358		Add dept to the filter when untargeted, to remove orphans 
** 6	2021-11-16  MD			JAZZ-27519		Update charge data pull based on IsChargeDollarsRemoved on budget config
** 7	2021-12-16  BW			JAZZ-31087		Filter source data for IsChargeDollarsRemoved dupes via the union to avoid merge error
** 8	2022-09-01  JB			JAZZ-32095		Remove Payor and PayorGroupID from joins.
** 9	2023-03-15  MY			JAZZ-51265		1Plan RefreshChargeToStatCrosswalkDataSource fails more often than not due to bad query plan
** 10	2023-03-21	MY			JAZZ-49993		Update reporting to support new data model
** 11	2023-08-08	MY			JAZZ-58719		Budget Process Times Out During Refresh Charge To Stat Crosswalk Data Source Action
*************************************************************/
CREATE   PROCEDURE [fp].[procReportFactChargeToStatisticsCrosswalkBackup] (
  @BudgetConfigID INT,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN 

	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#departments'
	EXEC [dbo].[procSysDropTempTable] '#charges'

	DECLARE @FiscalYearID INT,
			@ProjectedFiscalYearID INT;

	SET @FiscalYearID = (SELECT FiscalYearID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID);
	SET @ProjectedFiscalYearID = (SELECT FiscalYearID - 1 FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID);

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
  
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.ChargeVolume
		WHERE BudgetConfigID = @BudgetConfigID
	END

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		PatientClassID INT,
		ChargeCodeID INT,
		ServiceLineID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		RVUWeight DECIMAL(12, 4),
		UnitTypeID SMALLINT,
		TimeClassID TINYINT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		OriginalValue DECIMAL(19, 8),
		Value DECIMAL(19, 8),
		ManagerValue DECIMAL(19, 8)
	)

	-- IF THERE ARE PERFORMANCE PROBLEMS WITH THIS PROC PLEASE READ
	-- IF THERE ARE PERFORMANCE PROBLEMS WITH THIS PROC PLEASE READ
	-- IF THERE ARE PERFORMANCE PROBLEMS WITH THIS PROC PLEASE READ

	-- JAZZ-51265 AND JAZZ-58719: Important note, I was not able to determine the root cause of JAZZ-51265/JAZZ-58719 and merely attempted to simply the logic as I think
	-- this can sometimes cause query plan issues. If the problem still occurs we need more information and exactly what is causing the problem per the DBAs. 
	-- Previously we were just told to simplify the logic and thus are kind of trying to fix it blind as this has not been repeatable in Dev. 
	-- What I did this second time was combine everything before pivoting it out into months on rows. 
	-- We have to unpivot the data, so if the DBAs have better recommenedations for that, it would be appreciated.

	-- Initial Projection is not included because it not necessary as it's never shown to the user
	SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
		cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cc.AccountID, cc.RVUWeight, cv.UnitTypeID, 
			SUM(InitialBudget01) AS InitialBudget01, SUM(InitialBudget02) AS InitialBudget02, SUM(InitialBudget03) AS InitialBudget03, 
			SUM(InitialBudget04) AS InitialBudget04, SUM(InitialBudget05) AS InitialBudget05, SUM(InitialBudget06) AS InitialBudget06, 
			SUM(InitialBudget07) AS InitialBudget07, SUM(InitialBudget08) AS InitialBudget08, SUM(InitialBudget09) AS InitialBudget09, 
			SUM(InitialBudget10) AS InitialBudget10, SUM(InitialBudget11) AS InitialBudget11, SUM(InitialBudget12) AS InitialBudget12, 
			SUM(TargetAdjusted01) AS TargetValue01, SUM(TargetAdjusted02) AS TargetValue02, SUM(TargetAdjusted03) AS TargetValue03, 
			SUM(TargetAdjusted04) AS TargetValue04, SUM(TargetAdjusted05) AS TargetValue05, SUM(TargetAdjusted06) AS TargetValue06, 
			SUM(TargetAdjusted07) AS TargetValue07, SUM(TargetAdjusted08) AS TargetValue08,	SUM(TargetAdjusted09) AS TargetValue09, 
			SUM(TargetAdjusted10) AS TargetValue10, SUM(TargetAdjusted11) AS TargetValue11, SUM(TargetAdjusted12) AS TargetValue12,
			SUM(BudgetAdjusted01) AS ManagerValue01, SUM(BudgetAdjusted02) AS ManagerValue02, SUM(BudgetAdjusted03) AS ManagerValue03, 
			SUM(BudgetAdjusted04) AS ManagerValue04, SUM(BudgetAdjusted05) AS ManagerValue05, SUM(BudgetAdjusted06) AS ManagerValue06, 
			SUM(BudgetAdjusted07) AS ManagerValue07, SUM(BudgetAdjusted08) AS ManagerValue08, SUM(BudgetAdjusted09) AS ManagerValue09, 
			SUM(BudgetAdjusted10) AS ManagerValue10, SUM(BudgetAdjusted11) AS ManagerValue11, SUM(BudgetAdjusted12) AS ManagerValue12,
			SUM(ProjectionAdjusted01) AS ProjectedValue01, SUM(ProjectionAdjusted02) AS ProjectedValue02, SUM(ProjectionAdjusted03) AS ProjectedValue03, 
			SUM(ProjectionAdjusted04) AS ProjectedValue04, SUM(ProjectionAdjusted05) AS ProjectedValue05, SUM(ProjectionAdjusted06) AS ProjectedValue06, 
			SUM(ProjectionAdjusted07) AS ProjectedValue07, SUM(ProjectionAdjusted08) AS ProjectedValue08, SUM(ProjectionAdjusted09) AS ProjectedValue09, 
			SUM(ProjectionAdjusted10) AS ProjectedValue10, SUM(ProjectionAdjusted11) AS ProjectedValue11, SUM(ProjectionAdjusted12) AS ProjectedValue12,

			SUM(InitialBudgetDollars01) AS InitialBudgetDollars01, SUM(InitialBudgetDollars02) AS InitialBudgetDollars02, SUM(InitialBudgetDollars03) AS InitialBudgetDollars03, 
			SUM(InitialBudgetDollars04) AS InitialBudgetDollars04, SUM(InitialBudgetDollars05) AS InitialBudgetDollars05, SUM(InitialBudgetDollars06) AS InitialBudgetDollars06, 
			SUM(InitialBudgetDollars07) AS InitialBudgetDollars07, SUM(InitialBudgetDollars08) AS InitialBudgetDollars08, SUM(InitialBudgetDollars09) AS InitialBudgetDollars09, 
			SUM(InitialBudgetDollars10) AS InitialBudgetDollars10, SUM(InitialBudgetDollars11) AS InitialBudgetDollars11, SUM(InitialBudgetDollars12) AS InitialBudgetDollars12, 
			SUM(TargetDollarsAdjusted01) AS TargetValueDollars01, SUM(TargetDollarsAdjusted02) AS TargetValueDollars02, SUM(TargetDollarsAdjusted03) AS TargetValueDollars03, 
			SUM(TargetDollarsAdjusted04) AS TargetValueDollars04, SUM(TargetDollarsAdjusted05) AS TargetValueDollars05, SUM(TargetDollarsAdjusted06) AS TargetValueDollars06, 
			SUM(TargetDollarsAdjusted07) AS TargetValueDollars07, SUM(TargetDollarsAdjusted08) AS TargetValueDollars08, SUM(TargetDollarsAdjusted09) AS TargetValueDollars09, 
			SUM(TargetDollarsAdjusted10) AS TargetValueDollars10, SUM(TargetDollarsAdjusted11) AS TargetValueDollars11, SUM(TargetDollarsAdjusted12) AS TargetValueDollars12,
			SUM(BudgetDollarsAdjusted01) AS ManagerValueDollars01, SUM(BudgetDollarsAdjusted02) AS ManagerValueDollars02, SUM(BudgetDollarsAdjusted03) AS ManagerValueDollars03, 
			SUM(BudgetDollarsAdjusted04) AS ManagerValueDollars04, SUM(BudgetDollarsAdjusted05) AS ManagerValueDollars05, SUM(BudgetDollarsAdjusted06) AS ManagerValueDollars06, 
			SUM(BudgetDollarsAdjusted07) AS ManagerValueDollars07, SUM(BudgetDollarsAdjusted08) AS ManagerValueDollars08, SUM(BudgetDollarsAdjusted09) AS ManagerValueDollars09, 
			SUM(BudgetDollarsAdjusted10) AS ManagerValueDollars10, SUM(BudgetDollarsAdjusted11) AS ManagerValueDollars11, SUM(BudgetDollarsAdjusted12) AS ManagerValueDollars12,
			SUM(ProjectionDollarsAdjusted01) AS ProjectedValueDollars01, SUM(ProjectionDollarsAdjusted02) AS ProjectedValueDollars02, SUM(ProjectionDollarsAdjusted03) AS ProjectedValueDollars03, 
			SUM(ProjectionDollarsAdjusted04) AS ProjectedValueDollars04, SUM(ProjectionDollarsAdjusted05) AS ProjectedValueDollars05, SUM(ProjectionDollarsAdjusted06) AS ProjectedValueDollars06, 
			SUM(ProjectionDollarsAdjusted07) AS ProjectedValueDollars07, SUM(ProjectionDollarsAdjusted08) AS ProjectedValueDollars08, SUM(ProjectionDollarsAdjusted09) AS ProjectedValueDollars09, 
			SUM(ProjectionDollarsAdjusted10) AS ProjectedValueDollars10, SUM(ProjectionDollarsAdjusted11) AS ProjectedValueDollars11, SUM(ProjectionDollarsAdjusted12) AS ProjectedValueDollars12
	INTO #charges
	FROM fp.ChargeVolume cv 
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = cv.DepartmentID
		INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = cv.EntityGroupConfigID
			AND cc.DepartmentID = cv.DepartmentID
			AND cc.PatientClassID = cv.PatientClassID
			AND cc.ChargeCodeID = cv.ChargeCodeID
	WHERE cv.BudgetConfigID  = @BudgetConfigID
		AND 1 = 1
		-- Only checking units because there are never going to be cases where Dollars aren't 0 but units are 0
		AND (
			cv.InitialBudgetTotal != 0 OR
			cv.TargetAdjustedTotal != 0 OR
			cv.BudgetAdjustedTotal != 0 OR
			cv.ProjectionAdjustedTotal != 0
		)
	GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, 
		cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, cc.AccountID, cc.RVUWeight

	SELECT
		cv.BudgetConfigID,
		cv.EntityGroupConfigID,
		cv.EntityID,
		cv.DepartmentID,
		cv.ServiceLineID,
		cv.PatientClassID,
		cv.AgeCohortID,
		cv.MedicalSurgicalID,
		cv.ChargeCodeID,
		cv.AccountID,
		cv.RVUWeight,
		MonthSortOrder,
		m.FiscalMonthID,
		InitialBudgetValue, 
		TargetValue, 
		ManagerValue, 
		ProjectedValue, 
		InitialBudgetDollars, 
		TargetDollars, 
		ManagerDollars, 
		ProjectedDollars
	INTO #chargesPivoted
	FROM #charges cv
	CROSS APPLY (
		VALUES
			(01, InitialBudget01, TargetValue01, ManagerValue01, ProjectedValue01, InitialBudgetDollars01, TargetValueDollars01, ManagerValueDollars01, ProjectedValueDollars01),
			(02, InitialBudget02, TargetValue02, ManagerValue02, ProjectedValue02, InitialBudgetDollars02, TargetValueDollars02, ManagerValueDollars02, ProjectedValueDollars02),
			(03, InitialBudget03, TargetValue03, ManagerValue03, ProjectedValue03, InitialBudgetDollars03, TargetValueDollars03, ManagerValueDollars03, ProjectedValueDollars03),
			(04, InitialBudget04, TargetValue04, ManagerValue04, ProjectedValue04, InitialBudgetDollars04, TargetValueDollars04, ManagerValueDollars04, ProjectedValueDollars04),
			(05, InitialBudget05, TargetValue05, ManagerValue05, ProjectedValue05, InitialBudgetDollars05, TargetValueDollars05, ManagerValueDollars05, ProjectedValueDollars05),
			(06, InitialBudget06, TargetValue06, ManagerValue06, ProjectedValue06, InitialBudgetDollars06, TargetValueDollars06, ManagerValueDollars06, ProjectedValueDollars06),
			(07, InitialBudget07, TargetValue07, ManagerValue07, ProjectedValue07, InitialBudgetDollars07, TargetValueDollars07, ManagerValueDollars07, ProjectedValueDollars07),
			(08, InitialBudget08, TargetValue08, ManagerValue08, ProjectedValue08, InitialBudgetDollars08, TargetValueDollars08, ManagerValueDollars08, ProjectedValueDollars08),
			(09, InitialBudget09, TargetValue09, ManagerValue09, ProjectedValue09, InitialBudgetDollars09, TargetValueDollars09, ManagerValueDollars09, ProjectedValueDollars09),
			(10, InitialBudget10, TargetValue10, ManagerValue10, ProjectedValue10, InitialBudgetDollars10, TargetValueDollars10, ManagerValueDollars10, ProjectedValueDollars10),
			(11, InitialBudget11, TargetValue11, ManagerValue11, ProjectedValue11, InitialBudgetDollars11, TargetValueDollars11, ManagerValueDollars11, ProjectedValueDollars11),
			(12, InitialBudget12, TargetValue12, ManagerValue12, ProjectedValue12, InitialBudgetDollars12, TargetValueDollars12, ManagerValueDollars12, ProjectedValueDollars12)		
	) AS CrossApplied (MonthSortOrder, InitialBudgetValue, TargetValue, ManagerValue, ProjectedValue, InitialBudgetDollars, TargetDollars, ManagerDollars, ProjectedDollars)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder

	INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,
		AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue,
		Value, ManagerValue)
	SELECT
		BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,	AgeCohortID, MedicalSurgicalID, 
		FiscalMonthID, 
		@FiscalYearID AS FiscalYearID,	
		RVUWeight, 
		145 AS UnitTypeID, 
		2 AS TimeClassID, 
		InitialBudgetValue,
		TargetValue, 
		ManagerValue
	FROM #chargesPivoted
	WHERE InitialBudgetValue != 0
		OR TargetValue != 0
		OR ManagerValue != 0

	INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,
		AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue,
		Value, ManagerValue)
	SELECT
		BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,	AgeCohortID, MedicalSurgicalID, 
		FiscalMonthID, 
		@FiscalYearID AS FiscalYearID,	
		RVUWeight, 
		34 AS UnitTypeID, 
		2 AS TimeClassID, 
		InitialBudgetDollars,
		TargetDollars, 
		ManagerDollars
	FROM #chargesPivoted
	WHERE InitialBudgetDollars != 0
		OR TargetDollars != 0
		OR ManagerDollars != 0

	INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,
		AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue,
		Value, ManagerValue)
	SELECT
		BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,	AgeCohortID, MedicalSurgicalID, 
		FiscalMonthID, 
		@ProjectedFiscalYearID AS FiscalYearID,
		RVUWeight, 
		145 AS UnitTypeID, 
		12 AS TimeClassID, 
		0 AS OriginalValue,
		ProjectedValue, 
		ProjectedValue
	FROM #chargesPivoted
	WHERE ProjectedValue != 0

	INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,
		AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue,
		Value, ManagerValue)
	SELECT
		BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,	AgeCohortID, MedicalSurgicalID, 
		FiscalMonthID, 
		@ProjectedFiscalYearID AS FiscalYearID,	
		RVUWeight, 
		34 AS UnitTypeID, 
		12 AS TimeClassID, 
		0 AS OriginalValue,
		ProjectedDollars, 
		ProjectedDollars
	FROM #chargesPivoted
	WHERE ProjectedDollars != 0

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		 BudgetConfigID,
		 EntityID,     
		 DepartmentID,   
		 AccountID,    
		 PatientClassID, 
		 ChargeCodeID,
		 ServiceLineID,
		 AgeCohortID,
		 MedicalSurgicalID,
		 UnitTypeID,   
		 TimeClassID,    
		 FiscalMonthID,  
		 FiscalYearID   
	)
              
	-- Get all of the departments in that could be affected. We need to get this list to eliminate
	-- the null check in the join in the with statement.
	SELECT DISTINCT DepartmentID INTO #departments 
	FROM (
		SELECT DISTINCT DepartmentID FROM #SRC
		UNION ALL
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality
	) data            

	;WITH TGT AS 
	  (
		SELECT BudgetConfigID, EntityID, FRS.DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight, UnitTypeID,
			  TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue 
		FROM fp.FactReportChargeToStatisticsCrosswalk FRS
			INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	  )
      MERGE TGT AS target
      USING #SRC AS source
        ON (
              target.BudgetConfigID = source.BudgetConfigID
            AND target.EntityID     = source.EntityID
            AND target.DepartmentID   = source.DepartmentID
            AND target.AccountID    = source.AccountID
            AND target.PatientClassID = source.PatientClassID
            AND target.ChargeCodeID   = source.ChargeCodeID
            AND target.ServiceLineID  = source.ServiceLineID
            AND target.AgeCohortID    = source.AgeCohortID
            AND target.MedicalSurgicalID  = source.MedicalSurgicalID
            AND target.UnitTypeID   = source.UnitTypeID
            AND target.TimeClassID    = source.TimeClassID
            AND target.FiscalMonthID  = source.FiscalMonthID
            AND target.FiscalYearID   = source.FiscalYearID

            )
      WHEN MATCHED AND  (target.OriginalValue <> source.OriginalValue
          OR target.Value <> source.Value
          OR target.ManagerValue <> source.ManagerValue
          OR target.RVUWeight <> source.RVUWeight)
        THEN
          UPDATE SET
          target.OriginalValue = ISNULL(source.OriginalValue, 0),
          target.Value = ISNULL(source.Value, 0),
          target.ManagerValue = ISNULL(source.ManagerValue, 0),
          target.RVUWeight = ISNULL(source.RVUWeight, 0)
      WHEN NOT MATCHED BY TARGET
        THEN
          INSERT (
               BudgetConfigID
              ,EntityID
              ,DepartmentID
              ,AccountID
              ,PatientClassID
              ,ChargeCodeID
              ,ServiceLineID
              ,AgeCohortID
              ,MedicalSurgicalID
              ,RVUWeight
              ,UnitTypeID
              ,TimeClassID
              ,FiscalMonthID
              ,FiscalYearID
              ,OriginalValue
              ,Value
              ,ManagerValue
            )
          VALUES (
            source. BudgetConfigID
            ,source.EntityID
            ,source.DepartmentID
            ,source.AccountID
            ,source.PatientClassID
            ,source.ChargeCodeID
            ,source.ServiceLineID
            ,source.AgeCohortID
            ,source.MedicalSurgicalID
            ,ISNULL(source.RVUWeight, 0)
            ,source.UnitTypeID
            ,source.TimeClassID
            ,source.FiscalMonthID
            ,source.FiscalYearID
            ,ISNULL(source.OriginalValue, 0)
            ,ISNULL(source.Value, 0)
            ,ISNULL(source.ManagerValue, 0)
            )
      WHEN NOT MATCHED BY Source
        THEN
          DELETE;
          
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	-------------------------------------------------------------------------------------------------------
  
	-- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments
	-- We can't rely on the existing departments because of the check for the padded rows.
	IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
  
		TRUNCATE TABLE #departments;
  
		INSERT INTO #departments (DepartmentID)
		SELECT DepartmentID
		FROM [fw].[DimDepartment] dept
  
	END

	-- Get all records that were adjusted
	SELECT DISTINCT 
		fcv.BudgetConfigID,
		fcv.EntityID,
		fcv.DepartmentID,
		fcv.ChargeCodeID,
		fcv.ServiceLineID,
		fcv.AgeCohortID,
		fcv.MedicalSurgicalID,
		fcv.PatientClassID,
		fcv.UnitTypeID,
		chg.TimeClassID,
		chg.FiscalMonthID
	INTO #adjustedRecords
	FROM [fp].[ChargeVolumeChangeHistory] chg
		INNER JOIN [fp].[ChargeVolume] fcv ON chg.ChargeVolumeID = fcv.ChargeVolumeID
		INNER JOIN [fp].[DepartmentChargeVolumeAdjustment] adj ON chg.AdjustmentGUID = adj.AdjustmentGUID
		INNER JOIN #departments ft on ft.DepartmentID = fcv.DepartmentID
		INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = fcv.EntityGroupConfigID
			AND cc.DepartmentID = fcv.DepartmentID
			AND cc.PatientClassID = fcv.PatientClassID
			AND cc.ChargeCodeID = fcv.ChargeCodeID  
			AND fcv.EntityGroupConfigID = cc.EntityGroupConfigID
	WHERE chg.BudgetConfigID = @BudgetConfigID

	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	SELECT 
		src.BudgetConfigID,
		src.EntityID,
		src.DepartmentID,
		src.ChargeCodeID,
		src.ServiceLineID,
		src.AgeCohortID,
		src.MedicalSurgicalID,
		src.PatientClassID,
		145 AS UnitTypeID,
		2 AS TimeClassID,
		src.FiscalMonthID,
		@FiscalYearID AS FiscalYearID,
		src.InitialBudgetValue AS OriginalValue,
		src.TargetValue AS Value,
		src.ManagerValue
	INTO #tempUnpivoted
	FROM #adjustedRecords adj
		INNER JOIN #chargesPivoted src ON 
				adj.BudgetConfigID = src.BudgetConfigID
			AND adj.EntityID = src.EntityID
			AND adj.DepartmentID = src.DepartmentID
			AND adj.PatientClassID = src.PatientClassID
			AND adj.ChargeCodeID = src.ChargeCodeID
			AND adj.ServiceLineID = src.ServiceLineID
			AND adj.AgeCohortID = src.AgeCohortID
			AND adj.MedicalSurgicalID = src.MedicalSurgicalID
			AND adj.FiscalMonthID = src.FiscalMonthID
	WHERE src.BudgetConfigID = @BudgetConfigID
	AND (src.InitialBudgetValue = 0 OR src.TargetValue = 0 OR src.ManagerValue = 0)

	INSERT INTO #tempUnpivoted (BudgetConfigID,	EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID,
		MedicalSurgicalID, PatientClassID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue,
		Value, ManagerValue)
	SELECT 
		src.BudgetConfigID,
		src.EntityID,
		src.DepartmentID,
		src.ChargeCodeID,
		src.ServiceLineID,
		src.AgeCohortID,
		src.MedicalSurgicalID,
		src.PatientClassID,
		34 AS UnitTypeID,
		2 AS TimeClassID,
		src.FiscalMonthID,
		@FiscalYearID AS FiscalYearID,
		src.InitialBudgetDollars,
		src.TargetDollars,
		src.ManagerDollars
	FROM #adjustedRecords adj
		INNER JOIN #chargesPivoted src ON 
				adj.BudgetConfigID = src.BudgetConfigID
			AND adj.EntityID = src.EntityID
			AND adj.DepartmentID = src.DepartmentID
			AND adj.PatientClassID = src.PatientClassID
			AND adj.ChargeCodeID = src.ChargeCodeID
			AND adj.ServiceLineID = src.ServiceLineID
			AND adj.AgeCohortID = src.AgeCohortID
			AND adj.MedicalSurgicalID = src.MedicalSurgicalID
			AND adj.FiscalMonthID = src.FiscalMonthID
	WHERE src.BudgetConfigID = @BudgetConfigID
	AND (src.InitialBudgetDollars = 0 OR src.TargetDollars = 0 OR src.ManagerDollars = 0)

	INSERT INTO #tempUnpivoted (BudgetConfigID,	EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID,
		MedicalSurgicalID, PatientClassID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue,
		Value, ManagerValue)
	SELECT 
		src.BudgetConfigID,
		src.EntityID,
		src.DepartmentID,
		src.ChargeCodeID,
		src.ServiceLineID,
		src.AgeCohortID,
		src.MedicalSurgicalID,
		src.PatientClassID,
		145 AS UnitTypeID,
		12 AS TimeClassID,
		src.FiscalMonthID,
		@ProjectedFiscalYearID AS FiscalYearID,
		0 AS OriginalValue,
		src.ProjectedValue,
		src.ProjectedValue
	FROM #adjustedRecords adj
		INNER JOIN #chargesPivoted src ON 
				adj.BudgetConfigID = src.BudgetConfigID
			AND adj.EntityID = src.EntityID
			AND adj.DepartmentID = src.DepartmentID
			AND adj.PatientClassID = src.PatientClassID
			AND adj.ChargeCodeID = src.ChargeCodeID
			AND adj.ServiceLineID = src.ServiceLineID
			AND adj.AgeCohortID = src.AgeCohortID
			AND adj.MedicalSurgicalID = src.MedicalSurgicalID
			AND adj.FiscalMonthID = src.FiscalMonthID
	WHERE src.BudgetConfigID = @BudgetConfigID
		AND src.ProjectedValue = 0

	INSERT INTO #tempUnpivoted (BudgetConfigID,	EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID,
		MedicalSurgicalID, PatientClassID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue,
		Value, ManagerValue)
	SELECT 
		src.BudgetConfigID,
		src.EntityID,
		src.DepartmentID,
		src.ChargeCodeID,
		src.ServiceLineID,
		src.AgeCohortID,
		src.MedicalSurgicalID,
		src.PatientClassID,
		34 AS UnitTypeID,
		12 AS TimeClassID,
		src.FiscalMonthID,
		@ProjectedFiscalYearID AS FiscalYearID,
		0 AS OriginalValue,
		src.ProjectedDollars,
		src.ProjectedDollars
	FROM #adjustedRecords adj
		INNER JOIN #chargesPivoted src ON 
				adj.BudgetConfigID = src.BudgetConfigID
			AND adj.EntityID = src.EntityID
			AND adj.DepartmentID = src.DepartmentID
			AND adj.PatientClassID = src.PatientClassID
			AND adj.ChargeCodeID = src.ChargeCodeID
			AND adj.ServiceLineID = src.ServiceLineID
			AND adj.AgeCohortID = src.AgeCohortID
			AND adj.MedicalSurgicalID = src.MedicalSurgicalID
			AND adj.FiscalMonthID = src.FiscalMonthID
	WHERE src.BudgetConfigID = @BudgetConfigID
		AND src.ProjectedDollars = 0

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		target.BudgetConfigID,
		target.EntityID,
		target.DepartmentID,
		target.ChargeCodeID,
		target.ServiceLineID,
		target.AgeCohortID,
		target.MedicalSurgicalID,
		target.PatientClassID,
		target.UnitTypeID,
		target.TimeClassID,
		target.FiscalMonthID,
		target.FiscalYearID,
		target.OriginalValue,
		target.Value,
		target.ManagerValue
	INTO #dataToUpdate
	FROM [fp].[FactReportChargeToStatisticsCrosswalk] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID
			AND target.EntityID = source.EntityID
			AND target.DepartmentID = source.DepartmentID
			AND target.PatientClassID = source.PatientClassID
			AND target.ChargeCodeID   = source.ChargeCodeID
			AND target.ServiceLineID  = source.ServiceLineID
			AND target.AgeCohortID    = source.AgeCohortID
			AND target.MedicalSurgicalID  = source.MedicalSurgicalID
			AND target.UnitTypeID = source.UnitTypeID
			AND target.TimeClassID = source.TimeClassID
			AND target.FiscalMonthID = source.FiscalMonthID
			AND target.FiscalYearID = source.FiscalYearID
	WHERE source.BudgetConfigID = @BudgetConfigID
	AND (target.OriginalValue != source.OriginalValue OR target.Value != source.Value OR target.ManagerValue != source.ManagerValue)  

	-- Update the records
	UPDATE source
	SET source.OriginalValue = ISNULL(target.OriginalValue, 0), 
		source.Value =       ISNULL(target.Value, 0),
		source.ManagerValue =  ISNULL(target.ManagerValue, 0)
	FROM [fp].[FactReportChargeToStatisticsCrosswalk] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID
			AND target.EntityID = source.EntityID
			AND target.DepartmentID = source.DepartmentID
			AND target.PatientClassID = source.PatientClassID
			AND target.ChargeCodeID   = source.ChargeCodeID
			AND target.ServiceLineID  = source.ServiceLineID
			AND target.AgeCohortID    = source.AgeCohortID
			AND target.MedicalSurgicalID  = source.MedicalSurgicalID
			AND target.UnitTypeID = source.UnitTypeID
			AND target.TimeClassID = source.TimeClassID
			AND target.FiscalMonthID = source.FiscalMonthID
			AND target.FiscalYearID = source.FiscalYearID
            
END
GO


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

-- fp.ProcReportFactChargeToStatisticsCrosswalkHistoryBackup
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author      WI          Description
** 1    2020-05-08  LR          JAZZ-20     Initial
** 2    2020-13-08  MY			JAZZ-4079	Adding feature flag to short circuit the proc
** 3    2020-13-08  MY			JAZZ-4098	Performance tuning
** 4    2020-01-02  MY			JAZZ-14421  Remove old FF call that is no longer needed
** 5    2021-11-10  BW			JAZZ-1358   Add dept to the filter when untargeted, to remove orphans 
** 6    2021-11-16  MD			JAZZ-27519  Update charge data pull based on IsChargeDollarsRemoved on budget config
** 7    2022-09-01  JB			JAZZ-32095	Remove Payor and PayorGroupID from joins.
** 8	2023-03-15  MY			JAZZ-51265	1Plan RefreshChargeToStatCrosswalkDataSource fails more often than not due to bad query plan
** 9	2023-03-21	MY			JAZZ-49993	Update reporting to support new data model
** 10	2023-04-13	BW			JAZZ-51383	Remove IsDollarsRemovedFromCharges
*************************************************************/
 CREATE   PROCEDURE [fp].[procReportFactChargeToStatisticsCrosswalkHistoryBackup] (
  @BudgetConfigID INT,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)
 AS
 BEGIN

  exec [dbo].[procSysDropTempTable] '#SRC'
  exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
  exec [dbo].[procSysDropTempTable] '#departments'

  --only the active config is supported currently
  IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

  SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
  
  IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
  BEGIN
	 INSERT INTO #SourceDimensionality (DepartmentID) 
	 SELECT DISTINCT DepartmentID FROM fp.FactReportChargeToStatisticsCrosswalkHistory 
	 WHERE BudgetConfigID = @BudgetConfigID
  END

  CREATE TABLE #SRC (
    BudgetConfigID INT,
    EntityGroupConfigID INT,
    EntityID INT,
    DepartmentID INT,
    AccountID INT,
    PatientClassID INT,
    ChargeCodeID INT,
    ServiceLineID INT,
    AgeCohortID INT,
    MedicalSurgicalID INT,
    RVUWeight DECIMAL(12, 4),
    UnitTypeID SMALLINT,
    TimeClassID TINYINT,
    FiscalMonthID TINYINT,
    FiscalYearID SMALLINT,
    Value DECIMAL(19, 8)
  )

	INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID,  
		AccountID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight,
		PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
	SELECT VW.BudgetConfigID, VW.EntityGroupConfigID, EntityID, VW.DepartmentID,  
		cc.AccountID, VW.ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, cc.RVUWeight,
		VW.PatientClassID, UnitTypeID, TimeClassID, VW.FiscalYearID, FiscalMonthID, Value
	FROM [fp].viewFactChargeToStatisticsCrosswalkHistory_Unpivoted_source VW
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = VW.BudgetConfigID
		INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID=bc.BudgetConfigGUID
		INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID
		AND cc.DepartmentID = VW.DepartmentID
		AND cc.PatientClassID = VW.PatientClassID
		AND cc.ChargeCodeID = VW.ChargeCodeID
		AND cc.EntityGroupConfigID = VW.EntityGroupConfigID
	WHERE VW.BudgetConfigID  = @BudgetConfigID
	AND Value != 0

	INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID,  
		AccountID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight,
		PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
	SELECT VW.BudgetConfigID, VW.EntityGroupConfigID, EntityID, VW.DepartmentID,  
	cc.AccountID, VW.ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, cc.RVUWeight,
	VW.PatientClassID, 34 as UnitTypeID, TimeClassID, VW.FiscalYearID, FiscalMonthID, Value
	FROM [fp].viewFactChargeDollarsToStatisticsCrosswalkHistory_Unpivoted_source VW
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = VW.BudgetConfigID
		INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID=bc.BudgetConfigGUID
		INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID
		AND cc.DepartmentID = VW.DepartmentID
		AND cc.PatientClassID = VW.PatientClassID
		AND cc.ChargeCodeID = VW.ChargeCodeID
		AND cc.EntityGroupConfigID = VW.EntityGroupConfigID
	WHERE VW.BudgetConfigID  = @BudgetConfigID
	AND Value != 0

  CREATE CLUSTERED INDEX inx_src ON #SRC (
    BudgetConfigID,
    EntityGroupConfigID,
    EntityID,
    DepartmentID,
    AccountID,
    ChargeCodeID,
    ServiceLineID,
    AgeCohortID,
    MedicalSurgicalID,
    PatientClassID,
    UnitTypeID,
    TimeClassID,
    FiscalYearID,
    FiscalMonthID
  )

  -- Get all of the departments in that could be affected. We need to get this list to eliminate
  -- the null check in the join in the with statement.
  SELECT DISTINCT DepartmentID INTO #departments 
  FROM (
    SELECT DISTINCT DepartmentID FROM #SRC
    UNION ALL
    SELECT DISTINCT DepartmentID FROM #SourceDimensionality
  ) data      

  ;WITH TGT AS 
  (
    SELECT BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID,  AccountID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight,
      PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value 
    FROM fp.FactReportChargeToStatisticsCrosswalkHistory FRS
        INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
    WHERE FRS.BudgetConfigID  = @BudgetConfigID
  )
      MERGE TGT AS target
      USING #SRC AS source
        ON (
            target.BudgetConfigID = source.BudgetConfigID
            AND target.EntityGroupConfigID = source.EntityGroupConfigID
            AND target.EntityID = source.EntityID
            AND target.DepartmentID = source.DepartmentID
            AND target.AccountID = source.AccountID
            AND target.ChargeCodeID = source.ChargeCodeID
            AND target.ServiceLineID = source.ServiceLineID
            AND target.AgeCohortID = source.AgeCohortID
            AND target.MedicalSurgicalID = source.MedicalSurgicalID
            AND target.PatientClassID = source.PatientClassID
            AND target.UnitTypeID = source.UnitTypeID
            AND target.TimeClassID = source.TimeClassID
            AND target.FiscalYearID = source.FiscalYearID
            AND target.FiscalMonthID = source.FiscalMonthID)
      WHEN MATCHED AND (target.Value <> source.Value OR target.RVUWeight <> source.RVUWeight)
        THEN
          UPDATE SET
          target.Value = source.Value,
          target.RVUWeight = source.RVUWeight
      WHEN NOT MATCHED BY TARGET
        THEN
          INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID,
            AgeCohortID, MedicalSurgicalID, RVUWeight, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
          VALUES (
             source.BudgetConfigID
            ,source.EntityGroupConfigID
            ,source.EntityID
            ,source.DepartmentID
            ,source.AccountID
            ,source.PatientClassID
            ,source.ChargeCodeID
            ,source.ServiceLineID
            ,source.AgeCohortID
            ,source.MedicalSurgicalID
            ,source.RVUWeight
            ,source.UnitTypeID
            ,source.TimeClassID
            ,source.FiscalYearID
            ,source.FiscalMonthID
            ,source.Value
            )
      WHEN NOT MATCHED BY Source
        THEN
          DELETE;
END
GO


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

-- fp.ProcReportFactEncounterBackup
CREATE PROCEDURE fp.ProcReportFactEncounterBackup (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI       	Description
	** 1    2021-07-23   NN        JAZZ-21  	Create proc
	** 2	2020-13-08	 MY		   JAZZ-4079	Adding feature flag to short circuit the proc
	** 3	2020-01-02	 MY        JAZZ-14421	Remove old FF call that is no longer needed
	** 4    2021-11-10   BW        JAZZ-1358	Add dept to the filter when untargeted, to remove orphans 
	*************************************************************/
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#departments'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM [fp].[ServiceLineEncounter] 
		WHERE BudgetConfigID = @BudgetConfigID
	END
	
	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		ServiceLineID INT,
		ServiceLineRollupID INT,
		PatientClassID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		PayorID INT,
		PayorGroupID INT,
		MSDRGID INT,
		CPTID INT,
		ProviderID INT,
		PhysicianSpecialtyID INT,
		UnitTypeID SMALLINT,
		TimeClassID TINYINT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		OriginalValue DECIMAL(19, 8),
		Value DECIMAL(19, 8),
		ManagerValue DECIMAL(19, 8)
	)

	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
		BEGIN
		INSERT INTO #SRC (BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID,
		PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue)
		SELECT BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID,
		PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value,	ManagerValue 
		FROM [fp].[viewFactEncounter_Unpivoted_source] VW
			INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
		WHERE VW.BudgetConfigID  = @BudgetConfigID
		 AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0)
	END ELSE BEGIN
		INSERT INTO #SRC (BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID,
		PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue)
		SELECT BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID,
		PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue 
		FROM [fp].[viewFactEncounter_Unpivoted_source] VW
		WHERE VW.BudgetConfigID  = @BudgetConfigID
		 AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0)
	END

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		BudgetConfigID	
		,EntityID			
		,DepartmentID		
		,ServiceLineID
		,ServiceLineRollupID
		,PatientClassID
		,AgeCohortID
		,MedicalSurgicalID
		,PayorID
		,PayorGroupID
		,MSDRGID
		,CPTID
		,ProviderID
		,PhysicianSpecialtyID
		,UnitTypeID		
		,TimeClassID		
		,FiscalMonthID	
		,FiscalYearID		
	)
						
	-- Get all of the departments in that could be affected. We need to get this list to eliminate
	-- the null check in the join in the with statement.
	SELECT DISTINCT DepartmentID INTO #departments 
	FROM (
		SELECT DISTINCT DepartmentID FROM #SRC
		UNION ALL
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality
	) data						

	;WITH TGT AS 
	(
		SELECT BudgetConfigID, EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, 
		PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value,	ManagerValue 
		FROM [fp].[FactReportEncounter] FRE
				INNER JOIN #departments ft on ft.DepartmentID = FRE.DepartmentID
		WHERE FRE.BudgetConfigID  = @BudgetConfigID
	)
			MERGE TGT AS target
			USING #SRC AS source
				ON (
							target.BudgetConfigID	   = source.BudgetConfigID
						AND target.EntityID			   = source.EntityID
						AND target.DepartmentID		   = source.DepartmentID
						AND target.ServiceLineID	   = source.ServiceLineID
						AND target.ServiceLineRollupID = source.ServiceLineRollupID
						AND target.PatientClassID	   = source.PatientClassID
						AND target.AgeCohortID		   = source.AgeCohortID
						AND target.MedicalSurgicalID   = source.MedicalSurgicalID
						AND target.PayorID			   = source.PayorID
						AND target.PayorGroupID		   = source.PayorGroupID
						AND target.MSDRGID			   = source.MSDRGID
						AND target.CPTID			   = source.CPTID
						AND target.ProviderID		   = source.ProviderID
						AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID
						AND target.UnitTypeID		   = source.UnitTypeID
						AND target.TimeClassID		   = source.TimeClassID
						AND target.FiscalMonthID	   = source.FiscalMonthID
						AND target.FiscalYearID		   = source.FiscalYearID

						)
			WHEN MATCHED AND	(target.OriginalValue <> source.OriginalValue
					OR target.Value <> source.Value
					OR target.ManagerValue <> source.ManagerValue)
				THEN
					UPDATE SET
					target.OriginalValue = ISNULL(source.OriginalValue, 0),
					target.Value = ISNULL(source.Value, 0),
					target.ManagerValue = ISNULL(source.ManagerValue, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
							 BudgetConfigID
							,EntityID
							,DepartmentID
							,ServiceLineID
							,ServiceLineRollupID
							,PatientClassID
							,AgeCohortID
							,MedicalSurgicalID
							,PayorID
							,PayorGroupID
							,MSDRGID
							,CPTID
							,ProviderID
							,PhysicianSpecialtyID
							,UnitTypeID
							,TimeClassID
							,FiscalMonthID
							,FiscalYearID
							,OriginalValue
							,Value
							,ManagerValue
						)
					VALUES (
						 source.BudgetConfigID
						,source.EntityID
						,source.DepartmentID
						,source.ServiceLineID
						,source.ServiceLineRollupID
						,source.PatientClassID
						,source.AgeCohortID
						,source.MedicalSurgicalID
						,source.PayorID
						,source.PayorGroupID
						,source.MSDRGID
						,source.CPTID
						,source.ProviderID
						,source.PhysicianSpecialtyID
						,source.UnitTypeID
						,source.TimeClassID
						,source.FiscalMonthID
						,source.FiscalYearID
						,ISNULL(source.OriginalValue, 0)
						,ISNULL(source.Value, 0)
						,ISNULL(source.ManagerValue, 0)
						)
			WHEN NOT MATCHED BY Source
				THEN
					DELETE;
					
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	-------------------------------------------------------------------------------------------------------
	
	-- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments
	-- We can't rely on the existing departments because of the check for the padded rows.
	IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
	
		TRUNCATE TABLE #departments;
	
		INSERT INTO #departments (DepartmentID)
		SELECT DepartmentID
		FROM [fw].[DimDepartment] dept
	
	END

	-- Get all records that were adjusted
	SELECT DISTINCT chg.ServiceLineEncounterID
	INTO #adjustedRecords
	FROM [fp].[ServiceLineEncounterChangeHistory] chg
		INNER JOIN [fp].[ServiceLineEncounter] fse ON chg.ServiceLineEncounterID = fse.ServiceLineEncounterID
		INNER JOIN [fp].[ServiceLineEncounterAdjustment] adj ON chg.AdjustmentGUID = adj.AdjustmentGUID
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN #departments ft on ft.DepartmentID = fse.DepartmentID
	WHERE bc.BudgetConfigID = @BudgetConfigID

	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	SELECT src.ServiceLineEncounterID, src.BudgetConfigID, src.EntityID, src.DepartmentID, src.ServiceLineID, src.ServiceLineRollupID, src.PatientClassID,
			src.AgeCohortID, src.MedicalSurgicalID, src.PayorID, src.PayorGroupID, src.MSDRGID, src.CPTID, src.ProviderID, src.PhysicianSpecialtyID, src.UnitTypeID,
			src.TimeClassID, src.FiscalMonthID, src.FiscalYearID, src.OriginalValue, src.Value, src.ManagerValue
	INTO #tempUnpivoted
	FROM #adjustedRecords adj
		INNER JOIN [fp].[viewFactEncounter_Unpivoted_source] src ON src.ServiceLineEncounterID = adj.ServiceLineEncounterID
	WHERE src.BudgetConfigID = @BudgetConfigID
		AND (src.OriginalValue = 0 OR src.Value = 0 OR src.ManagerValue = 0)

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT target.ServiceLineEncounterID, target.BudgetConfigID, target.EntityID, target.DepartmentID, target.ServiceLineID, target.ServiceLineRollupID, target.PatientClassID,
			target.AgeCohortID, target.MedicalSurgicalID, target.PayorID, target.PayorGroupID, target.MSDRGID, target.CPTID, target.ProviderID, target.PhysicianSpecialtyID, 
			target.UnitTypeID, target.TimeClassID, target.FiscalMonthID, target.FiscalYearID, target.OriginalValue, target.Value, target.ManagerValue
	INTO #dataToUpdate
	FROM [fp].[FactReportEncounter] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID = source.EntityID
						AND target.DepartmentID = source.DepartmentID
						AND target.ServiceLineID = source.ServiceLineID
						AND target.ServiceLineRollupID = source.ServiceLineRollupID
						AND target.PatientClassID = source.PatientClassID
						AND target.AgeCohortID = source.AgeCohortID
						AND target.MedicalSurgicalID = source.MedicalSurgicalID
						AND target.PayorGroupID = source.PayorGroupID
						AND target.PayorID = source.PayorID
						AND target.MSDRGID = source.MSDRGID
						AND target.CPTID = source.CPTID
						AND target.ProviderID = source.ProviderID
						AND target.PhysicianSpecialtyID = source.PhysicianSpecialtyID
						AND target.TimeClassID = source.TimeClassID
						AND target.FiscalMonthID = source.FiscalMonthID
						AND target.FiscalYearID = source.FiscalYearID
	WHERE source.BudgetConfigID = @BudgetConfigID
		AND (target.OriginalValue != source.OriginalValue OR target.Value != source.Value OR target.ManagerValue != source.ManagerValue)	

	-- Update the records
	UPDATE source
	SET source.OriginalValue = 		  ISNULL(target.OriginalValue, 0), 
		source.Value = 		  ISNULL(target.Value, 0),
		source.ManagerValue = ISNULL(target.ManagerValue, 0)
	FROM [fp].[FactReportEncounter] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID = source.EntityID
						AND target.DepartmentID = source.DepartmentID
						AND target.ServiceLineID = source.ServiceLineID
						AND target.ServiceLineRollupID = source.ServiceLineRollupID
						AND target.PatientClassID = source.PatientClassID
						AND target.AgeCohortID = source.AgeCohortID
						AND target.MedicalSurgicalID = source.MedicalSurgicalID
						AND target.PayorGroupID = source.PayorGroupID
						AND target.PayorID = source.PayorID
						AND target.MSDRGID = source.MSDRGID
						AND target.CPTID = source.CPTID
						AND target.ProviderID = source.ProviderID
						AND target.PhysicianSpecialtyID = source.PhysicianSpecialtyID
						AND target.UnitTypeID = source.UnitTypeID
						AND target.TimeClassID = source.TimeClassID
						AND target.FiscalMonthID = source.FiscalMonthID
						AND target.FiscalYearID = source.FiscalYearID
						
END
GO


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

-- fp.ProcReportFactEncounterHistoryBackup
CREATE   PROCEDURE fp.ProcReportFactEncounterHistoryBackup (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI       	Description
	** 1    2021-07-23   NN        JAZZ-21  	Create proc
	** 2	2020-13-08	 MY		   JAZZ-4079	Adding feature flag to short circuit the proc
	** 3	2020-01-02	 MY        JAZZ-14421	Remove old FF call that is no longer needed
	** 4    2021-11-10   BW        JAZZ-1358	Add dept to the filter when untargeted, to remove orphans 
	** 5    2023-05-19   BY        JAZZ-55153	Update to restructure
	*************************************************************/
	
	exec [dbo].[procSysDropTempTable] '#SRC'
	exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
	exec [dbo].[procSysDropTempTable] '#departments'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM [fp].[ServiceLineEncounter]
		WHERE BudgetConfigID = @BudgetConfigID
	END

	CREATE TABLE #SRC (
		ServiceLineEncounterID INT,
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT,
		DepartmentID INT,
		ServiceLineID INT,
		ServiceLineRollupID INT,
		PatientClassID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		PayorID INT,
		PayorGroupID INT,
		MSDRGID INT,
		CPTID INT,
		ProviderID INT,
		PhysicianSpecialtyID INT,
		UnitTypeID SMALLINT,
		TimeClassID TINYINT,
		FiscalYearID SMALLINT,
		FiscalMonthID TINYINT,
		Value DECIMAL(19, 8)
	)

	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #SRC (ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, 
			AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
		SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, 
			AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value
		FROM [fp].viewFactEncounterHistory_Unpivoted_source VW
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
		WHERE VW.BudgetConfigID  = @BudgetConfigID
			AND Value != 0
	END ELSE BEGIN
		INSERT INTO #SRC (ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, 
			AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
		SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, 
			AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value
		FROM [fp].viewFactEncounterHistory_Unpivoted_source VW
		WHERE VW.BudgetConfigID  = @BudgetConfigID
			AND Value != 0
	END

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		ServiceLineEncounterID,
		BudgetConfigID,
		EntityGroupConfigID,
		EntityID,
		DepartmentID,
		ServiceLineID,
		ServiceLineRollupID, 
		PatientClassID, 
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		UnitTypeID,
		TimeClassID,
		FiscalYearID,
		FiscalMonthID
	)

	-- Get all of the departments in that could be affected. We need to get this list to eliminate
	-- the null check in the join in the with statement.
	SELECT DISTINCT DepartmentID INTO #departments 
	FROM (
		SELECT DISTINCT DepartmentID FROM #SRC
		UNION ALL
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality
	) data			

	;WITH TGT AS 
	(
		SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, 
		MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, Value 
		FROM [fp].[FactReportEncounterHistory] FRE
				INNER JOIN #departments ft on ft.DepartmentID = FRE.DepartmentID
		WHERE FRE.BudgetConfigID  = @BudgetConfigID
	)

			MERGE TGT AS target
			USING #SRC AS source
				ON (
						target.ServiceLineEncounterID	= source.ServiceLineEncounterID
						AND target.BudgetConfigID		= source.BudgetConfigID
						AND target.EntityGroupConfigID	= source.EntityGroupConfigID
						AND target.EntityID				= source.EntityID
						AND target.DepartmentID			= source.DepartmentID
						AND target.ServiceLineID	   	= source.ServiceLineID
						AND target.ServiceLineRollupID 	= source.ServiceLineRollupID
						AND target.PatientClassID	   	= source.PatientClassID
						AND target.AgeCohortID		   	= source.AgeCohortID
						AND target.MedicalSurgicalID   	= source.MedicalSurgicalID
						AND target.PayorID			   	= source.PayorID
						AND target.PayorGroupID		   	= source.PayorGroupID
						AND target.MSDRGID			   	= source.MSDRGID
						AND target.CPTID			   	= source.CPTID
						AND target.ProviderID		   	= source.ProviderID
						AND target.PhysicianSpecialtyID	= source.PhysicianSpecialtyID
						AND target.UnitTypeID			= source.UnitTypeID
						AND target.TimeClassID			= source.TimeClassID
						AND target.FiscalYearID			= source.FiscalYearID
						AND target.FiscalMonthID		= source.FiscalMonthID)


			WHEN MATCHED AND target.Value <> source.Value
				THEN
					UPDATE SET
					target.Value = source.Value
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, 
						MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
					VALUES (
						source.ServiceLineEncounterID
						,source.BudgetConfigID
						,source.EntityGroupConfigID
						,source.EntityID
						,source.DepartmentID
						,source.ServiceLineID
						,source.ServiceLineRollupID
						,source.PatientClassID
						,source.AgeCohortID
						,source.MedicalSurgicalID
						,source.PayorID
						,source.PayorGroupID
						,source.MSDRGID
						,source.CPTID
						,source.ProviderID
						,source.PhysicianSpecialtyID
						,source.UnitTypeID
						,source.TimeClassID
						,source.FiscalYearID
						,source.FiscalMonthID
						,source.Value
						)
			WHEN NOT MATCHED BY Source
				THEN
					DELETE;
	END
GO


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

-- fp.ProcReportFactGeneralLedgerHistoryBackup
CREATE     PROCEDURE [fp].[ProcReportFactGeneralLedgerHistoryBackup] (
@BudgetConfigID INT,
@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)
WITH RECOMPILE
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2018-12-24   IP        B-21543     Added temp table to index source as well
** 2    2018-12-25   IP        B-21543     Optimized refreshment of tables (refactored joining to @SourceDimensionality)
** 3    2019-01-09   GF        B-21715     Optimize full config refresh case
** 4    2019-01-11   GF        B-21715     Optimize targeted refresh case
** 5    2019-05-02   GF        			   Remove special handling of all case to make concurrency work
** 6    2019-07-22   MY        			   Performance updates
** 7    2021-11-10   BW        JAZZ-1358   Add dept to the filter when untargeted, to remove orphans 
** 8    2023-08-11   BK        JAZZ-58752  Update for new gl data structure
** 9	2024-04-11	 DM			JAZZ-70189	Budget Config used for Report comparison is processed as well
*************************************************************/

exec [dbo].[procSysDropTempTable] '#SRC'
exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
exec [dbo].[procSysDropTempTable] '#departments'

--only the active config is supported currently
IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) 

IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
BEGIN
	INSERT INTO #SourceDimensionality (DepartmentID) 
	SELECT DISTINCT DepartmentID FROM fp.GeneralLedger 
	WHERE BudgetConfigID = @BudgetConfigID
END

CREATE TABLE #SRC(
	 GeneralLedgerID INT
	,BudgetConfigID INT
	,EntityGroupConfigID INT
	,EntityID INT
	,DepartmentID INT
	,AccountID INT
	,FinancialReportingID INT
	,APEModelSectionID INT
	,VariabilityID INT
	,UnitTypeID TINYINT
	,TimeClassID TINYINT
	,FiscalYearID SMALLINT
	,FiscalMonthID TINYINT
	,Value DECIMAL(19, 8)
)

IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
BEGIN
	INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID,
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID,
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value  
	FROM [fp].[viewFactGeneralLedgerHistory_Unpivoted_source] VW
	INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
	WHERE VW.BudgetConfigID  = @BudgetConfigID
		AND Value != 0
END ELSE BEGIN
	INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID,
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value)
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID,
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value 
	FROM [fp].[viewFactGeneralLedgerHistory_Unpivoted_source] VW
	WHERE VW.BudgetConfigID  = @BudgetConfigID
		AND Value != 0
END

CREATE CLUSTERED INDEX inx_src ON #SRC (
					GeneralLedgerID
					,BudgetConfigID
					,EntityGroupConfigID
					,EntityID
					,DepartmentID
					,AccountID
					,FinancialReportingID
					,APEModelSectionID
					,VariabilityID
					,UnitTypeID
					,TimeClassID
					,FiscalYearID
					,FiscalMonthID)

-- Get all of the departments in that could be affected. We need to get this list to eliminate
-- the null check in the join in the with statement.
SELECT DISTINCT DepartmentID INTO #departments 
FROM (
	SELECT DISTINCT DepartmentID FROM #SRC
	UNION ALL
	SELECT DISTINCT DepartmentID FROM #SourceDimensionality
) data		

;WITH TGT AS 
(
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID,
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value 
	FROM fp.FactReportGeneralLedgerHistory FRS
		INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
	WHERE FRS.BudgetConfigID  = @BudgetConfigID
)
		MERGE TGT AS target
		USING #SRC AS source
			ON (
						target.GeneralLedgerID = source.GeneralLedgerID
					AND target.BudgetConfigID = source.BudgetConfigID
					AND target.EntityGroupConfigID = source.EntityGroupConfigID
					AND target.EntityID = source.EntityID
					AND target.DepartmentID = source.DepartmentID
					AND target.AccountID = source.AccountID
					AND target.FinancialReportingID = source.FinancialReportingID
					AND target.APEModelSectionID = source.APEModelSectionID
					AND target.VariabilityID = source.VariabilityID
					AND target.UnitTypeID = source.UnitTypeID
					AND target.TimeClassID = source.TimeClassID
					AND target.FiscalYearID = source.FiscalYearID
					AND target.FiscalMonthID = source.FiscalMonthID 
					)
		WHEN MATCHED AND target.Value <> source.Value
			THEN
				UPDATE
				SET 
				target.Value = source.Value
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					GeneralLedgerID
					,BudgetConfigID
					,EntityGroupConfigID
					,EntityID
					,DepartmentID
					,AccountID
					,FinancialReportingID
					,APEModelSectionID
					,VariabilityID
					,UnitTypeID
					,TimeClassID
					,FiscalYearID
					,FiscalMonthID
					,Value
					)
				VALUES (
					source.GeneralLedgerID
					,source.BudgetConfigID
					,source.EntityGroupConfigID
					,source.EntityID
					,source.DepartmentID
					,source.AccountID
					,source.FinancialReportingID
					,source.APEModelSectionID
					,source.VariabilityID
					,source.UnitTypeID
					,source.TimeClassID
					,source.FiscalYearID
					,source.FiscalMonthID
					,source.Value
					)
		WHEN NOT MATCHED BY Source
			THEN
				DELETE;		
END
GO


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

-- fp.ProcReportFactStaffingHistoryBackup
CREATE   PROCEDURE [fp].[ProcReportFactStaffingHistoryBackup] (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)
WITH RECOMPILE
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2018-12-24   IP        B-21543     Added temp table to index source as well
** 2    2019-01-09   GF        B-21715     Optimize full config refresh case
** 3    2019-01-11   GF        B-21715     Optimize targeted refresh case
** 4    2019-05-02   GF        			   Remove special handling of all case to make concurrency work
** 6    2019-07-22   MY        			   Performance updates to reports
** 7    2019-11-13   MD        B-24632     Add EmployeeID to staffing sampling
** 6    2020-02-18   MY        JAZZ-15375  Roll-up data above Provider for Report
** 9	2021-11-30	 SD		   JAZZ-30301  add provider dimensions to Staffing reporting data sources
** 10	2024-07-04	 DM		   JAZZ-70314  Budget Config used for Report comparison is processed as well
*************************************************************/
exec [dbo].[procSysDropTempTable] '#SRC'
exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
exec [dbo].[procSysDropTempTable] '#departments'

--only the active config is supported currently
IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

CREATE TABLE #SRC (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT,
	DepartmentID INT,
	JobCodeID INT,
	PayCodeGroupID INT,
	ProductiveClassID INT,
	VariabilityID INT,
	UnitTypeID SMALLINT,
	TimeClassID TINYINT,
	FiscalYearID SMALLINT,
	FiscalMonthID TINYINT,
	Value DECIMAL(19, 8),
	EmployeeID INT,
	ProviderID INT,
	ProviderLineItemID INT,
	ProviderTypeID INT,
	ProviderSpecialtyID INT
)

IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
BEGIN
	INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID,	ProductiveClassID,
		VariabilityID, UnitTypeID, TimeClassID,	FiscalYearID, FiscalMonthID, Value, EmployeeID, ProviderID, ProviderLineItemID,
		ProviderTypeID, ProviderSpecialtyID)
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID,	ProductiveClassID,
		VariabilityID, UnitTypeID, TimeClassID,	FiscalYearID, FiscalMonthID, SUM(Value), EmployeeID, ProviderID, ProviderLineItemID,
		ProviderTypeID, ProviderSpecialtyID
	FROM [fp].viewFactStaffingHistory_Unpivoted_source VW
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
	WHERE VW.BudgetConfigID  = @BudgetConfigID
		AND Value != 0
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID,	ProductiveClassID,
		VariabilityID, UnitTypeID, TimeClassID,	FiscalYearID, FiscalMonthID, EmployeeID, ProviderID, ProviderLineItemID,
		ProviderTypeID, ProviderSpecialtyID
END ELSE BEGIN
	INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID,	ProductiveClassID,
		VariabilityID, UnitTypeID, TimeClassID,	FiscalYearID, FiscalMonthID, Value, EmployeeID, ProviderID, ProviderLineItemID,
		ProviderTypeID, ProviderSpecialtyID)
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID,	ProductiveClassID,
		VariabilityID, UnitTypeID, TimeClassID,	FiscalYearID, FiscalMonthID, SUM(Value), EmployeeID, ProviderID, ProviderLineItemID,
		ProviderTypeID, ProviderSpecialtyID
	FROM [fp].viewFactStaffingHistory_Unpivoted_source VW
	WHERE VW.BudgetConfigID  = @BudgetConfigID
		AND Value != 0
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID,	ProductiveClassID,
		VariabilityID, UnitTypeID, TimeClassID,	FiscalYearID, FiscalMonthID, EmployeeID, ProviderID, ProviderLineItemID,
		ProviderTypeID, ProviderSpecialtyID
END

CREATE CLUSTERED INDEX inx_src ON #SRC (
	BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	DepartmentID,
	JobCodeID,
	PayCodeGroupID,
	ProductiveClassID,
	VariabilityID,
	UnitTypeID,
	TimeClassID,
	FiscalYearID,
	FiscalMonthID,
	EmployeeID, 
	ProviderID, 
	ProviderLineItemID,
	ProviderTypeID, 
	ProviderSpecialtyID
)

-- Get all of the departments in that could be affected. We need to get this list to eliminate
-- the null check in the join in the with statement.
SELECT DISTINCT DepartmentID INTO #departments 
FROM (
	SELECT DISTINCT DepartmentID FROM #SRC
	UNION ALL
	SELECT DISTINCT DepartmentID FROM #SourceDimensionality
) data	

;WITH TGT AS 
(
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, JobCodeID, PayCodeGroupID,	ProductiveClassID,
		VariabilityID, UnitTypeID, TimeClassID,	FiscalYearID, FiscalMonthID, Value, EmployeeID, ProviderID, ProviderLineItemID,
		ProviderTypeID, ProviderSpecialtyID
	FROM fp.FactReportStaffingHistory FRS
		INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
	WHERE FRS.BudgetConfigID  = @BudgetConfigID
)

		MERGE TGT AS target
		USING #SRC AS source
			ON (	
				    target.BudgetConfigID=source.BudgetConfigID
				and target.EntityGroupConfigID=source.EntityGroupConfigID
				and target.EntityID=source.EntityID
				and target.DepartmentID=source.DepartmentID
				and target.JobCodeID=source.JobCodeID
				and target.PayCodeGroupID=source.PayCodeGroupID
				and target.ProductiveClassID=source.ProductiveClassID
				and target.VariabilityID=source.VariabilityID
				and target.UnitTypeID=source.UnitTypeID
				and target.TimeClassID=source.TimeClassID
				and target.FiscalYearID=source.FiscalYearID
				and target.FiscalMonthID=source.FiscalMonthID
				and target.EmployeeID=source.EmployeeID
				AND target.ProviderID= source.ProviderID
	            AND target.ProviderLineItemID= source.ProviderLineItemID
				AND target.ProviderTypeID= source.ProviderTypeID
				AND target.ProviderSpecialtyID= source.ProviderSpecialtyID
				)

		WHEN MATCHED AND target.Value <> source.Value
			THEN
				UPDATE SET
				target.Value = source.Value
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					 BudgetConfigID
					,EntityGroupConfigID
					,EntityID
					,DepartmentID
					,JobCodeID
					,PayCodeGroupID
					,ProductiveClassID
					,VariabilityID
					,UnitTypeID
					,TimeClassID
					,FiscalYearID
					,FiscalMonthID
					,Value
					,EmployeeID
					,ProviderID
					,ProviderLineItemID
					,ProviderTypeID
					,ProviderSpecialtyID
					)
				VALUES (
					 source.BudgetConfigID
					,source.EntityGroupConfigID
					,source.EntityID
					,source.DepartmentID
					,source.JobCodeID
					,source.PayCodeGroupID
					,source.ProductiveClassID
					,source.VariabilityID
					,source.UnitTypeID
					,source.TimeClassID
					,source.FiscalYearID
					,source.FiscalMonthID
					,source.Value
					,source.EmployeeID
					,source.ProviderID
					,source.ProviderLineItemID
					,source.ProviderTypeID
					,source.ProviderSpecialtyID
					)					
		WHEN NOT MATCHED BY Source
			THEN
				DELETE;
END
GO


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

-- fp.ProcReportFactStatisticsHistoryBackup
CREATE PROCEDURE [fp].[ProcReportFactStatisticsHistoryBackup] (
@BudgetConfigID INT,
@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)
WITH RECOMPILE
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2018-12-24   IP        B-21543     Added temp table to index source as well
** 2    2019-01-09   GF        B-21715     Optimize full config refresh case
** 3    2019-01-11   GF        B-21715     Optimize targeted refresh case
** 4    2019-05-02   GF        			   Remove special handling of all case to make concurrency work
** 5    2019-07-22   MY        			   Performance updates
** 6    2020-02-18   MY        JAZZ-15375  Roll-up data above Provider for Report
** 7    2021-05-10   MD        JAZZ-15686  Add Provider dimensions to Stats data sources 
** 8    2021-11-10   BW        JAZZ-1358   Add dept to the filter when untargeted, to remove orphans 
** 9    2024-07-16   YR        JAZZ-70315  Budget Config used for Report comparison is processed as well 
*************************************************************/
exec [dbo].[procSysDropTempTable] '#SRC'
exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
exec [dbo].[procSysDropTempTable] '#departments'

--only the active config is supported currently
IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
BEGIN
	INSERT INTO #SourceDimensionality (DepartmentID) 
	SELECT DISTINCT DepartmentID FROM fp.FactStatistics 
	WHERE BudgetConfigID = @BudgetConfigID
END

CREATE TABLE #SRC (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT,
	DepartmentID INT,
	AccountID INT,
	FinancialReportingID INT,
	PayorID INT,
	PatientClassID INT,
	UnitTypeID SMALLINT,
	TimeClassID TINYINT,
	FiscalYearID SMALLINT,
	FiscalMonthID TINYINT,
	ProviderID INT,
	ProviderTypeID INT,
	ProviderSpecialtyID INT,
	ProviderLineItemID INT,
	Value DECIMAL(19, 8)
)

IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
BEGIN
	INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID,
		PatientClassID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value)
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID,
		PatientClassID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SUM(Value)
	FROM [fp].viewFactStatisticsHistory_Unpivoted_source VW
	INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
	WHERE VW.BudgetConfigID  = @BudgetConfigID
		AND Value != 0
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID,
		PatientClassID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID
END ELSE BEGIN
	INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID,
		PatientClassID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value)
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID,
		PatientClassID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SUM(Value)
	FROM [fp].viewFactStatisticsHistory_Unpivoted_source VW
	WHERE VW.BudgetConfigID  = @BudgetConfigID
		AND Value != 0
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID,
		PatientClassID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID
END

CREATE CLUSTERED INDEX inx_src ON #SRC (
	BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	DepartmentID,
	AccountID,
	FinancialReportingID,
	PayorID,
	PatientClassID,
	UnitTypeID,
	TimeClassID,
	FiscalYearID,
	FiscalMonthID,
	ProviderID,
	ProviderTypeID,
	ProviderSpecialtyID,
	ProviderLineItemID
) WITH (DATA_COMPRESSION = PAGE)

-- Get all of the departments in that could be affected. We need to get this list to eliminate
-- the null check in the join in the with statement.
SELECT DISTINCT DepartmentID INTO #departments 
FROM (
	SELECT DISTINCT DepartmentID FROM #SRC
	UNION ALL
	SELECT DISTINCT DepartmentID FROM #SourceDimensionality
) data			

;WITH TGT AS 
(
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, PayorID,
		PatientClassID,	UnitTypeID,	TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value 
	FROM fp.FactReportStatisticsHistory FRS
			INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
	WHERE FRS.BudgetConfigID  = @BudgetConfigID
)

		MERGE TGT AS target
		USING #SRC AS source
			ON (
						target.BudgetConfigID			= source.BudgetConfigID
					AND target.EntityGroupConfigID		= source.EntityGroupConfigID
					AND target.EntityID					= source.EntityID
					AND target.DepartmentID				= source.DepartmentID
					AND target.AccountID				= source.AccountID
					AND target.FinancialReportingID		= source.FinancialReportingID
					AND target.PayorID					= source.PayorID
					AND target.PatientClassID			= source.PatientClassID
					AND target.UnitTypeID				= source.UnitTypeID
					AND target.TimeClassID				= source.TimeClassID
					AND target.FiscalYearID				= source.FiscalYearID
					AND target.FiscalMonthID			= source.FiscalMonthID
					AND target.ProviderID				= source.ProviderID
					AND target.ProviderTypeID			= source.ProviderTypeID
					AND target.ProviderSpecialtyID		= source.ProviderSpecialtyID
					AND target.ProviderLineItemID		= source.ProviderLineItemID)
		WHEN MATCHED AND target.Value <> source.Value
			THEN
				UPDATE SET
				target.Value = source.Value
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, 
					PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, 
					ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value)
				VALUES (
					 source.BudgetConfigID
					,source.EntityGroupConfigID
					,source.EntityID
					,source.DepartmentID
					,source.AccountID
					,source.FinancialReportingID
					,source.PayorID
					,source.PatientClassID
					,source.UnitTypeID
					,source.TimeClassID
					,source.FiscalYearID
					,source.FiscalMonthID
					,source.ProviderID
					,source.ProviderTypeID
					,source.ProviderSpecialtyID
					,source.ProviderLineItemID
					,source.Value
					)
		WHEN NOT MATCHED BY Source
			THEN
				DELETE;
END
GO


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

-- fp.ProviderCompensationAdjustment_SEL_LIST
CREATE   PROCEDURE [fp].[ProviderCompensationAdjustment_SEL_LIST]
    @budgetGUID UNIQUEIDENTIFIER,
    @start INT,
    @end INT,
    @search VARCHAR(MAX),
    @filter VARCHAR(MAX),
    @userGUID UNIQUEIDENTIFIER,
    @isDataSecured BIT,
    @dateTimeFormat VARCHAR(30),
    @userTimeZone VARCHAR(50)
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2021-02-02  OP  	 JAZZ-14151		Created SP
 ** 2	 2021-10-13	 VZ		 JAZZ-40848		Added Add Provider Adjustments
 ** 3    2024-02-22  MY      JAZZ-67143		Filters acting unexpectedly post-adjustment - Issue #2
 *************************************************************/
BEGIN

    -- Contains all DepartmnetID with correspond EntityID that are allowed for current user
    CREATE TABLE #departmentsSecurity (
        DepartmentID INT NULL,
        EntityID INT NULL
    )
        
    -- Adjustments that passes security check
    CREATE TABLE #securedAdjustments (
        AdjustmentGUID UNIQUEIDENTIFIER
    )
    
    DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]()
    DECLARE @pageSize INT = @end - @start;

    SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
    SET @filter = LOWER(NULLIF(@filter, ''))

    -- Select all possible to display adjustments
    SELECT    AdjustmentGUID
            ,GroupingHierarchyJSON                    
            ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
            ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID
			,AdjustmentType
			,GroupingGUID
    INTO    #adjustments
    FROM    [fp].[StaffingAdjustment] AS slea WITH (NOLOCK)    
    WHERE    slea.AdjustmentType IN (0, 2, 1, 4, 5, 6, 7, 8, 3, 10, 11, 12, 13, 14, 15) -- Supported Adjustment types for Staffing Provider Adjustments
        AND slea.BudgetConfigGUID = @budgetGUID

    IF @isDataSecured = 1
    BEGIN
        -- Get all departments that are allowed for current user
        INSERT INTO #departmentsSecurity
        EXEC fp.DepartmentsSecurity_SEL 
			@userGUID = @userGUID,
			@pageName = 'Staffing'

        -- Creating index for faster selects
        CREATE CLUSTERED    INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

        -- Select adjustments that have no Department/Entity on filters, but have DepartmentID
        -- on grouping hierarchy level
        SELECT    AdjustmentGUID
                ,ahd.ID AS DepartmentID
        INTO    #adjustmentGroupingHierarchyDepartments
        FROM (
                SELECT    adj.AdjustmentGUID
                        ,adj.GroupingHierarchyJSON
                FROM    #adjustments AS adj
                        -- Ignore departments that have DepartmentID and EntityID
                WHERE    adj.EntityID IS NULL
                        AND adj.DepartmentID IS NULL) AS slea
                OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd
        GROUP BY AdjustmentGUID
                ,ahd.ID

        -- Select adjustments that don't have DepartmentID on grouping hierarchy level
        -- but have EntityID on grouping hierarchy level
        SELECT    adj.AdjustmentGUID,
                ahe.ID AS EntityID
        INTO    #adjustmentGroupingHierarchyEntities
        FROM    #adjustments AS adj
                JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID
                                                                        AND adhd.DepartmentID IS NULL
                OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
        GROUP BY adj.AdjustmentGUID    
                ,ahe.ID
        
        INSERT INTO    #securedAdjustments
        SELECT    res.AdjustmentGUID
        FROM    (
            -- Adjustmnets that passes Department security by DepartmentID
            SELECT    slea.AdjustmentGUID
            FROM    #adjustments AS slea
                    JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID
            GROUP BY slea.AdjustmentGUID 

            UNION ALL

            -- Adjustmnets that passes Department security by EntityID
            SELECT    slea.AdjustmentGUID        
            FROM    #adjustments AS slea
                    JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
            WHERE    slea.DepartmentID IS NULL
            GROUP BY slea.AdjustmentGUID

            UNION ALL

            -- Insert adjustments that have allowed DepartmentID on their grouping hierarchy
            SELECT    aghd.AdjustmentGUID        
            FROM    #adjustmentGroupingHierarchyDepartments AS aghd
                    JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID
            WHERE    dshd.DepartmentID IS NOT NULL
            GROUP BY aghd.AdjustmentGUID

            UNION ALL

            -- Insert adjustments that have allowed EntityID on their grouping hierarchy
            SELECT    aghe.AdjustmentGUID        
            FROM    #adjustmentGroupingHierarchyEntities AS aghe
                    JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
            GROUP BY aghe.AdjustmentGUID

            UNION ALL

            -- Insert all adjustments that have no connection to department or entity
            SELECT    adj.AdjustmentGUID
            FROM    #adjustments AS adj
                    JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID
                    JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID
            WHERE    adj.DepartmentID IS NULL
                    AND adj.EntityID IS NULL
                    AND aghd.DepartmentID IS NULL
                    AND aghe.EntityID IS NULL
					AND adj.AdjustmentType <> 15 -- Add provider adjustment, that has no grouping hierarchy, but has security
            GROUP BY adj.AdjustmentGUID

			UNION ALL

			SELECT adj.AdjustmentGUID
			FROM #adjustments AS adj
					JOIN fp.ProvCompAddProviderAdjustment AS pcapa ON adj.AdjustmentGUID = pcapa.AdjustmentGUID
					JOIN #departmentsSecurity AS ds ON ds.DepartmentID = pcapa.DepartmentID
			GROUP BY adj.AdjustmentGUID
        ) AS res

		-- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2)
		-- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the 
		-- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine.
		-- Essentially what we are doing here is using the child adjustments to find if they fall in security.
		-- In the event we have a child, populate the parent adjustment in the list.
		-- Find all the GroupingGuid's for any child adjustments that fall into security.
		
		SELECT DISTINCT adj.GroupingGUID
		INTO #groupingAdjustments
		FROM #securedAdjustments secured
			INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID
		WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments.

		-- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment.
		INSERT INTO #securedAdjustments
		SELECT adj.AdjustmentGUID
		FROM #adjustments adj
			INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID
			LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID
		WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments
			AND secured.AdjustmentGUID IS NULL

    END
    ELSE 
        BEGIN

            -- In case there security is not applied just insert all adjustments
            INSERT INTO #securedAdjustments
            SELECT    AdjustmentGUID
            FROM    #adjustments

        END
     
    CREATE CLUSTERED    INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID)

    -- Select import adjustments that are allowed by security
    -- with UnitTypeID
    SELECT    iadj.AdjustmentGuid, 
            iadj.UnitTypeID,
            iadj.DepartmentID
    INTO    #importAdjustments
    FROM    fp.StaffingAdjustmentImport AS iadj WITH (NOLOCK)
            JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID
			LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID
	WHERE ds.DepartmentID IS NOT NULL OR @isDataSecured = 0
    GROUP BY iadj.AdjustmentGuid,
            iadj.UnitTypeID,
            iadj.DepartmentID
    
    -- Creating indexes for faster selection
    CREATE CLUSTERED    INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID)

    SELECT res.TotalRowsCount
        ,res.AdjustmentGUID
        ,res.BudgetConfigGUID
        ,res.AdjustmentType
        ,res.[Value]
        ,res.AdjustmentFilterJSON
        ,res.GroupingHierarchyJSON
        ,res.AdjustedProperty
        ,res.Comment
        ,res.AuthorGUID
        ,res.AuthorFullName
        ,res.LastModifiedDateUtc
        ,res.DateCreatedUtc
        ,res.GroupingGUID
        ,res.TimeClassID
        ,res.BudgetPhaseID
        ,res.ClassificationGroupID
        ,res.ClassificationCategoryID
		,res.JobCode
		,res.JobCodeCount
		,res.DepartmentCode
		,res.DepartmentCount
        ,res.UnitTypeID
        ,res.ImportUnitTypeIDs
		,res.AddProviderFirstName
		,res.AddProviderLastName
		,res.AddProviderType
		,res.IsRecordDeleted
    FROM (
        -- Selecting total rows count, for paging to work correctly
        SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount,
               *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                  ,slea.AdjustmentGUID
                  ,slea.BudgetConfigGUID
                  ,slea.AdjustmentType
                  ,slea.[Value]
                  ,slea.AdjustmentFilterJSON
                  ,slea.GroupingHierarchyJSON
                  ,slea.AdjustedProperty
                  ,ISNULL(ag.[Description], slea.Comment) AS Comment
                  ,slea.AuthorGUID
                  ,slea.AuthorFullName
                  ,slea.LastModifiedDateUtc
                  ,slea.DateCreatedUtc
                  ,slea.GroupingGUID
                  ,slea.TimeClassID
                  ,slea.BudgetPhaseID
                  ,slea.ClassificationGroupID
                  ,slea.ClassificationCategoryID
                  ,slea.UnitTypeID
				  ,NULL AS JobCode
				  ,NULL AS JobCodeCount
				  ,NULL AS DepartmentCode
				  ,NULL AS DepartmentCount
                  ,sai.ImportUnitTypeIDs
				  ,NULL AS AddProviderFirstName
				  ,NULL AS AddProviderLastName
				  ,NULL AS AddProviderType
				  ,slea.IsRecordDeleted
            FROM    fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
                    LEFT JOIN (
                        SELECT    p.AdjustmentGUID, 
                                ImportUnitTypeIDs =
                                TRIM(STUFF(
                                    (SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5))
                                    FROM    #importAdjustments AS p2
                                            LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = p2.DepartmentID
                                    WHERE    (ds.DepartmentID IS NOT NULL
                                                OR @isDataSecured = 0)
                                            AND p2.AdjustmentGUID = p.AdjustmentGUID
                                    GROUP BY p2.AdjustmentGUID, 
                                            p2.UnitTypeID
                                    FOR XML PATH(N''))
                                , 1, 0, N''))
                        FROM    #importAdjustments AS p
                        GROUP BY p.AdjustmentGUID
                    ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID
                    LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID 
                    LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
                                                                    AND slea.ClassificationCategoryID = acc.CategoryID
                    LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
                    LEFT JOIN (
                        SELECT    nsa.GroupingGUID
                        FROM    fp.StaffingAdjustment as nsa WITH (NOLOCK)
                        WHERE    nsa.AdjustmentType IN (12, 13, 14)
                                AND nsa.BudgetConfigGUID = @budgetGUID
                        GROUP BY nsa.GroupingGUID
                    ) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
            WHERE    (slea.AdjustmentType <> 4 
                        OR sai.ImportUnitTypeIDs <> '')
					AND slea.SubsectionID = 4 -- Provider
                    AND (ra.GroupingGUID IS NULL
                        OR slea.AdjustmentType IN (12, 13, 14))
                    AND slea.AdjustmentType <> 6 AND slea.AdjustmentType <> 7 AND slea.AdjustmentType <> 15
                    AND (@search IS NULL 
                        OR (
                                LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                                OR LOWER(ISNULL(ag.[Description], slea.Comment)) LIKE @search ESCAPE '\'
                                OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR ISNULL(acc.[Name], acg.[Name]) LIKE @search ESCAPE '\'
                                OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
                                OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
                                OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1
                            )
                        )
                    AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
                            SELECT    [value]
                            FROM    STRING_SPLIT(@filter, ' ' )
                            )
                        )
			-- Add Provider adjustment
			UNION ALL
			
			SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
					,slea.AdjustmentGUID
					,slea.BudgetConfigGUID
					,slea.AdjustmentType
					,slea.[Value]
					,slea.AdjustmentFilterJSON
					,slea.GroupingHierarchyJSON
					,slea.AdjustedProperty
					,aps.Comment
					,slea.AuthorGUID
					,slea.AuthorFullName
					,slea.LastModifiedDateUtc
					,slea.DateCreatedUtc
					,slea.GroupingGUID
					,slea.TimeClassID
					,2 AS BudgetPhaseID
					,aps.ClassificationGroupID
					,aps.ClassificationCategoryID
					,NULL AS UnitTypeID
					,NULL AS JobCode
					,NULL AS JobCodeCount
					,NULL AS DepartmentCode
					,NULL AS DepartmentCount
					,NULL AS ImportUnitTypeIDs
					,de.NameFirst AS AddProviderFirstName
					,de.NameLast AS AddProviderLastName
					,aps.EmployeeType AS AddProviderType
					,slea.IsRecordDeleted
			FROM fp.StaffingAdjustment AS slea WITH (NOLOCK)
					JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
					JOIN fp.StatisticAddProviderSummary AS aps ON aps.StaffingAdjustmentGUID = slea.AdjustmentGUID
					JOIN fw.DimEmployee AS de ON de.EmployeeID = aps.EmployeeID
					LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = aps.ClassificationGroupID
					LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acc.GroupID = acg.GroupID AND aps.ClassificationCategoryID = acc.CategoryID
			WHERE slea.AdjustmentType = 15 -- add provider adjustments
					AND (@search IS NULL
							OR (
								LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
								OR LOWER(aps.Comment) LIKE @search ESCAPE '\'
								OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR acc.[Name] LIKE @search ESCAPE '\'
								OR acg.[Name] LIKE @search ESCAPE '\'
								OR de.NameFull LIKE @search ESCAPE '\'
								)
						)
					AND (@filter IS NULL OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, 2) IN ( SELECT [value] FROM STRING_SPLIT(@filter, ' ')))
				  ) AS res_inner
             WHERE res_inner.RowNumber = 1) AS res
    ORDER BY res.DateCreatedUtc DESC
        OFFSET @start ROWS
        FETCH NEXT @pageSize ROWS ONLY
		option (recompile)		 --!!!
		;

END
GO


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

-- fp.ResetFactStaffingTables
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1	2018-10-04  IP      B-20922		Added using source dimensionality
** 2 	2022-08-09  JB  	JAZZ-23177	Remove commented union for clean up purposes
*************************************************************/
CREATE PROCEDURE [fp].[ResetFactStaffingTables]
	@EntityGroupConfigID INT,
	@UnitTypeIds dbo.SqlInt32ListTableType READONLY,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

   SET NOCOUNT ON

	CREATE TABLE #FilteringTable (
	DepartmentID INT
	,INDEX ix_1 NONCLUSTERED (DepartmentID)
	)

	INSERT INTO #FilteringTable (DepartmentID)
	SELECT DepartmentID
	FROM @SourceDimensionality

	DECLARE @isFilterPresent INT = (SELECT COUNT(*) FROM #FilteringTable)

	IF (@isFilterPresent=0) BEGIN
	UPDATE tbl
	    SET
	        tbl.AdjustedValue01 = fs.InitialBudget01, tbl.AdjustedValue02 = fs.InitialBudget02, tbl.AdjustedValue03 = fs.InitialBudget03, tbl.AdjustedValue04 = fs.InitialBudget04,	tbl.AdjustedValue05 = fs.InitialBudget05, tbl.AdjustedValue06 = fs.InitialBudget06, tbl.AdjustedValue07 = fs.InitialBudget07, tbl.AdjustedValue08 = fs.InitialBudget08,	tbl.AdjustedValue09 = fs.InitialBudget09, tbl.AdjustedValue10 = fs.InitialBudget10, tbl.AdjustedValue11 = fs.InitialBudget11, tbl.AdjustedValue12 = fs.InitialBudget12,
	        tbl.FlexedValue01 = fs.InitialBudget01, tbl.FlexedValue02 = fs.InitialBudget02, tbl.FlexedValue03 = fs.InitialBudget03, tbl.FlexedValue04 = fs.InitialBudget04, tbl.FlexedValue05 = fs.InitialBudget05, tbl.FlexedValue06 = fs.InitialBudget06, tbl.FlexedValue07 = fs.InitialBudget07, tbl.FlexedValue08 = fs.InitialBudget08, tbl.FlexedValue09 = fs.InitialBudget09, tbl.FlexedValue10 = fs.InitialBudget10, tbl.FlexedValue11 = fs.InitialBudget11, tbl.FlexedValue12 = fs.InitialBudget12,
	        tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000,
	        tbl.LockType = 0,
	        tbl.LockFlag = 0
	    FROM [fp].[FactStaffingBudget] tbl
	    INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID
		 INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID
	    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
	        
			
		-- reset the data in the projection table
	 	UPDATE tbl
	    SET
	        tbl.AdjustedValue01 = fs.InitialProjection01, tbl.AdjustedValue02 = fs.InitialProjection02, tbl.AdjustedValue03 = fs.InitialProjection03, tbl.AdjustedValue04 = fs.InitialProjection04,	tbl.AdjustedValue05 = fs.InitialProjection05, tbl.AdjustedValue06 = fs.InitialProjection06, tbl.AdjustedValue07 = fs.InitialProjection07, tbl.AdjustedValue08 = fs.InitialProjection08,	tbl.AdjustedValue09 = fs.InitialProjection09, tbl.AdjustedValue10 = fs.InitialProjection10, tbl.AdjustedValue11 = fs.InitialProjection11, tbl.AdjustedValue12 = fs.InitialProjection12,
	        tbl.FlexedValue01 = fs.InitialProjection01, tbl.FlexedValue02 = fs.InitialProjection02, tbl.FlexedValue03 = fs.InitialProjection03, tbl.FlexedValue04 = fs.InitialProjection04, tbl.FlexedValue05 = fs.InitialProjection05, tbl.FlexedValue06 = fs.InitialProjection06, tbl.FlexedValue07 = fs.InitialProjection07, tbl.FlexedValue08 = fs.InitialProjection08, tbl.FlexedValue09 = fs.InitialProjection09, tbl.FlexedValue10 = fs.InitialProjection10, tbl.FlexedValue11 = fs.InitialProjection11, tbl.FlexedValue12 = fs.InitialProjection12,
	        tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000,
	        tbl.LockType = 0,
	        tbl.LockFlag = 0
	    FROM [fp].[FactStaffingProjection] tbl
	    INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID
		 INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID
	    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID

	END ELSE BEGIN
		-- reset the data in the budget table
		UPDATE tbl
	    SET
	        tbl.AdjustedValue01 = fs.InitialBudget01, tbl.AdjustedValue02 = fs.InitialBudget02, tbl.AdjustedValue03 = fs.InitialBudget03, tbl.AdjustedValue04 = fs.InitialBudget04,	tbl.AdjustedValue05 = fs.InitialBudget05, tbl.AdjustedValue06 = fs.InitialBudget06, tbl.AdjustedValue07 = fs.InitialBudget07, tbl.AdjustedValue08 = fs.InitialBudget08,	tbl.AdjustedValue09 = fs.InitialBudget09, tbl.AdjustedValue10 = fs.InitialBudget10, tbl.AdjustedValue11 = fs.InitialBudget11, tbl.AdjustedValue12 = fs.InitialBudget12,
	        tbl.FlexedValue01 = fs.InitialBudget01, tbl.FlexedValue02 = fs.InitialBudget02, tbl.FlexedValue03 = fs.InitialBudget03, tbl.FlexedValue04 = fs.InitialBudget04, tbl.FlexedValue05 = fs.InitialBudget05, tbl.FlexedValue06 = fs.InitialBudget06, tbl.FlexedValue07 = fs.InitialBudget07, tbl.FlexedValue08 = fs.InitialBudget08, tbl.FlexedValue09 = fs.InitialBudget09, tbl.FlexedValue10 = fs.InitialBudget10, tbl.FlexedValue11 = fs.InitialBudget11, tbl.FlexedValue12 = fs.InitialBudget12,
	        tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000,
	        tbl.LockType = 0,
	        tbl.LockFlag = 0
	    FROM [fp].[FactStaffingBudget] tbl
	    INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID
		INNER JOIN #FilteringTable ft ON ft.DepartmentID = fs.DepartmentID
		INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID
	    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
	        
			
		-- reset the data in the projection table
	 	UPDATE tbl
	    SET
	        tbl.AdjustedValue01 = fs.InitialProjection01, tbl.AdjustedValue02 = fs.InitialProjection02, tbl.AdjustedValue03 = fs.InitialProjection03, tbl.AdjustedValue04 = fs.InitialProjection04,	tbl.AdjustedValue05 = fs.InitialProjection05, tbl.AdjustedValue06 = fs.InitialProjection06, tbl.AdjustedValue07 = fs.InitialProjection07, tbl.AdjustedValue08 = fs.InitialProjection08,	tbl.AdjustedValue09 = fs.InitialProjection09, tbl.AdjustedValue10 = fs.InitialProjection10, tbl.AdjustedValue11 = fs.InitialProjection11, tbl.AdjustedValue12 = fs.InitialProjection12,
	        tbl.FlexedValue01 = fs.InitialProjection01, tbl.FlexedValue02 = fs.InitialProjection02, tbl.FlexedValue03 = fs.InitialProjection03, tbl.FlexedValue04 = fs.InitialProjection04, tbl.FlexedValue05 = fs.InitialProjection05, tbl.FlexedValue06 = fs.InitialProjection06, tbl.FlexedValue07 = fs.InitialProjection07, tbl.FlexedValue08 = fs.InitialProjection08, tbl.FlexedValue09 = fs.InitialProjection09, tbl.FlexedValue10 = fs.InitialProjection10, tbl.FlexedValue11 = fs.InitialProjection11, tbl.FlexedValue12 = fs.InitialProjection12,
	        tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000,
	        tbl.LockType = 0,
	        tbl.LockFlag = 0
	    FROM [fp].[FactStaffingProjection] tbl
	    INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID
		INNER JOIN #FilteringTable ft ON ft.DepartmentID = fs.DepartmentID 
		INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID
	    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
	END	 
END
GO


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

-- fp.ResetFactStatisticsTables
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1	2018-10-04  IP      B-20922		Added using source dimensionality
** 2	2020-14-12  MY      JAZZ-11324  Added rate reset
** 3 	2022-08-09  JB  	JAZZ-23177	Commented out union in #FilteringTable
** 4 	2022-10-04	JB		JAZZ-43489	Remove FlexedValue references
*************************************************************/
 CREATE PROCEDURE [fp].[ResetFactStatisticsTables]
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
 	CREATE TABLE #FilteringTable (
	DepartmentID INT
	,INDEX ix_1 NONCLUSTERED (DepartmentID)
	)

	INSERT INTO #FilteringTable (DepartmentID)
	SELECT DepartmentID
	FROM @SourceDimensionality
	
/* -- This was commented out in ResetFactStaffingTables so we commented it out here as well. -JB/BK 08/09/2022 @mtw
	UNION

	SELECT d.DepartmentID
	FROM fw.DimDepartment d
	INNER JOIN @SourceDimensionality sd 
		ON sd.EntityID = d.EntityID
	WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID 
	
	*/
 	
	DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable)

	IF (@isFilterPresent=0) 
	INSERT INTO #FilteringTable (DepartmentID) VALUES (NULL)


	UPDATE tbl
    SET
        tbl.AdjustedValue01 = fgl.InitialBudget01, tbl.AdjustedValue02 = fgl.InitialBudget02, tbl.AdjustedValue03 = fgl.InitialBudget03, tbl.AdjustedValue04 = fgl.InitialBudget04,	tbl.AdjustedValue05 = fgl.InitialBudget05, tbl.AdjustedValue06 = fgl.InitialBudget06, tbl.AdjustedValue07 = fgl.InitialBudget07, tbl.AdjustedValue08 = fgl.InitialBudget08,	tbl.AdjustedValue09 = fgl.InitialBudget09, tbl.AdjustedValue10 = fgl.InitialBudget10, tbl.AdjustedValue11 = fgl.InitialBudget11, tbl.AdjustedValue12 = fgl.InitialBudget12,
		tbl.RateAdjustedValue01 = fgl.InitialBudgetRate01, tbl.RateAdjustedValue02 = fgl.InitialBudgetRate02, tbl.RateAdjustedValue03 = fgl.InitialBudgetRate03, tbl.RateAdjustedValue04 = fgl.InitialBudgetRate04,	tbl.RateAdjustedValue05 = fgl.InitialBudgetRate05, tbl.RateAdjustedValue06 = fgl.InitialBudgetRate06, tbl.RateAdjustedValue07 = fgl.InitialBudgetRate07, tbl.RateAdjustedValue08 = fgl.InitialBudgetRate08,	tbl.RateAdjustedValue09 = fgl.InitialBudgetRate09, tbl.RateAdjustedValue10 = fgl.InitialBudgetRate10, tbl.RateAdjustedValue11 = fgl.InitialBudgetRate11, tbl.RateAdjustedValue12 = fgl.InitialBudgetRate12,        
        tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactStatisticsBudget] tbl
    INNER JOIN [fp].[FactStatistics] fgl ON tbl.StatisticsID = fgl.StatisticsID
	INNER JOIN #FilteringTable ft on (ft.DepartmentID = fgl.DepartmentID or @isFilterPresent = 0)
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
        
 	UPDATE tbl
    SET
        tbl.AdjustedValue01 = fgl.InitialProjection01, tbl.AdjustedValue02 = fgl.InitialProjection02, tbl.AdjustedValue03 = fgl.InitialProjection03, tbl.AdjustedValue04 = fgl.InitialProjection04,	tbl.AdjustedValue05 = fgl.InitialProjection05, tbl.AdjustedValue06 = fgl.InitialProjection06, tbl.AdjustedValue07 = fgl.InitialProjection07, tbl.AdjustedValue08 = fgl.InitialProjection08,	tbl.AdjustedValue09 = fgl.InitialProjection09, tbl.AdjustedValue10 = fgl.InitialProjection10, tbl.AdjustedValue11 = fgl.InitialProjection11, tbl.AdjustedValue12 = fgl.InitialProjection12,
        tbl.RateAdjustedValue01 = fgl.InitialProjectionRate01, tbl.RateAdjustedValue02 = fgl.InitialProjectionRate02, tbl.RateAdjustedValue03 = fgl.InitialProjectionRate03, tbl.RateAdjustedValue04 = fgl.InitialProjectionRate04,	tbl.RateAdjustedValue05 = fgl.InitialProjectionRate05, tbl.RateAdjustedValue06 = fgl.InitialProjectionRate06, tbl.RateAdjustedValue07 = fgl.InitialProjectionRate07, tbl.RateAdjustedValue08 = fgl.InitialProjectionRate08,	tbl.RateAdjustedValue09 = fgl.InitialProjectionRate09, tbl.RateAdjustedValue10 = fgl.InitialProjectionRate10, tbl.RateAdjustedValue11 = fgl.InitialProjectionRate11, tbl.RateAdjustedValue12 = fgl.InitialProjectionRate12,
        tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactStatisticsProjection] tbl
    INNER JOIN [fp].[FactStatistics] fgl ON tbl.StatisticsID = fgl.StatisticsID
	INNER JOIN #FilteringTable ft on (ft.DepartmentID = fgl.DepartmentID or @isFilterPresent = 0)
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
 
 END
GO


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

-- fp.ResetServiceLineTables
/**************************************************************
** Change History
**************************************************************
** CID  Date		    Author	WI			    Description
** 1	 2022-09-19		BK		JAZZ-42503		Add ProviderID to targeting
** 2	 2023-02-24		BW		JAZZ-48306		Updated for new data model, use [fp].[ServiceLineEncounter]
** 3	 2023-05-24		MY		JAZZ-55524		Included Target in the reset
*************************************************************/
CREATE   PROCEDURE [fp].[ResetServiceLineTables]
	 @EntityGroupConfigID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
 AS
 BEGIN
 
	IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable;
	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable;
 	
	CREATE TABLE #FilteringTable (
	DepartmentID INT
	,INDEX ix_1 NONCLUSTERED (DepartmentID)
	)

	INSERT INTO #FilteringTable (DepartmentID)
	SELECT DepartmentID
	FROM @SourceDimensionality sd WHERE sd.DepartmentID IS NOT NULL

	UNION

	SELECT d.DepartmentID
	FROM fw.DimDepartment d
	INNER JOIN @SourceDimensionality sd 
		ON sd.EntityID = d.EntityID
	WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID 

	-- table to use to populate Entity and ServiceLines that correspond to the departments passed in
	-- DepartmentID on fp.FactServiceLineEncounter DOES NOT correspond to DepartmentID on the other fp tables, it is for security purposes only
	CREATE TABLE #filterTable (EntityID INT, ServiceLineID INT, ProviderID INT)
	
	DECLARE @BudgetConfigID SMALLINT
	SELECT @BudgetConfigID = BudgetConfigID FROM fp.BudgetConfig a INNER JOIN fp.EntityGroupConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE b.EntityGroupConfigID = @EntityGroupConfigID

	-- use mapping table to populate filter table
	INSERT INTO #filterTable (EntityID, ServiceLineID, ProviderID)
	SELECT DISTINCT EntityID, ServiceLineID, map.ProviderID 
	FROM fp.ServiceLineEncounterChargeVolumeMapping map
	INNER JOIN #FilteringTable ft on map.DepartmentID = ft.DepartmentID
	WHERE map.BudgetConfigID = @BudgetConfigID

	IF EXISTS(SELECT 1 FROM #filterTable WHERE EntityID IS NULL) OR NOT EXISTS (SELECT 1 FROM #filterTable)
	BEGIN
		INSERT INTO #filterTable (EntityID, ServiceLineID, ProviderID)
		SELECT DISTINCT EntityID, ServiceLineID, ProviderID
		FROM fp.ServiceLineEncounter
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END

	UPDATE sle
    SET
		sle.TargetAdjusted01 = sle.InitialBudget01, 
		sle.TargetAdjusted02 = sle.InitialBudget02, 
		sle.TargetAdjusted03 = sle.InitialBudget03, 
		sle.TargetAdjusted04 = sle.InitialBudget04,	
		sle.TargetAdjusted05 = sle.InitialBudget05, 
		sle.TargetAdjusted06 = sle.InitialBudget06, 
		sle.TargetAdjusted07 = sle.InitialBudget07, 
		sle.TargetAdjusted08 = sle.InitialBudget08,	
		sle.TargetAdjusted09 = sle.InitialBudget09, 
		sle.TargetAdjusted10 = sle.InitialBudget10, 
		sle.TargetAdjusted11 = sle.InitialBudget11, 
		sle.TargetAdjusted12 = sle.InitialBudget12,
        sle.TargetLockType = 0,
        sle.TargetLockFlag = 0,
        sle.BudgetAdjusted01 = sle.InitialBudget01, 
		sle.BudgetAdjusted02 = sle.InitialBudget02, 
		sle.BudgetAdjusted03 = sle.InitialBudget03, 
		sle.BudgetAdjusted04 = sle.InitialBudget04,	
		sle.BudgetAdjusted05 = sle.InitialBudget05, 
		sle.BudgetAdjusted06 = sle.InitialBudget06, 
		sle.BudgetAdjusted07 = sle.InitialBudget07, 
		sle.BudgetAdjusted08 = sle.InitialBudget08,	
		sle.BudgetAdjusted09 = sle.InitialBudget09, 
		sle.BudgetAdjusted10 = sle.InitialBudget10, 
		sle.BudgetAdjusted11 = sle.InitialBudget11, 
		sle.BudgetAdjusted12 = sle.InitialBudget12,
        sle.BudgetLockType = 0,
        sle.BudgetLockFlag = 0,
		sle.ProjectionAdjusted01 = sle.InitialProjection01, 
		sle.ProjectionAdjusted02 = sle.InitialProjection02,
		sle.ProjectionAdjusted03 = sle.InitialProjection03, 
		sle.ProjectionAdjusted04 = sle.InitialProjection04,	
		sle.ProjectionAdjusted05 = sle.InitialProjection05, 
		sle.ProjectionAdjusted06 = sle.InitialProjection06, 
		sle.ProjectionAdjusted07 = sle.InitialProjection07, 
		sle.ProjectionAdjusted08 = sle.InitialProjection08,	
		sle.ProjectionAdjusted09 = sle.InitialProjection09, 
		sle.ProjectionAdjusted10 = sle.InitialProjection10, 
		sle.ProjectionAdjusted11 = sle.InitialProjection11, 
		sle.ProjectionAdjusted12 = sle.InitialProjection12,
        sle.ProjectionLockType = 0,
        sle.ProjectionLockFlag = 0
    FROM [fp].[ServiceLineEncounter] sle
	INNER JOIN #filterTable ft on ft.EntityID = sle.EntityID AND ft.ServiceLineID = sle.ServiceLineID AND ft.ProviderID = sle.ProviderID
    WHERE sle.EntityGroupConfigID = @EntityGroupConfigID
 
 END
GO


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

-- fp.ServiceLineEncounterAdjustment_SEL_LIST
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2020-06-03  LR  	 JAZZ-134		Now including deleted items to be displayed in the activity pane
 ** 2    2020-07-01  OP  	 JAZZ-635		Added AP Entity Config roles support
 ** 3 	 2020-08-20  OP  	 JAZZ-4123		Fixed import comment
 ** 4	 2022-09-02	 AO		 JAZZ-42931		Fixed search by Adjustment Type
 ** 5	 2022-01-06	 NT		 JAZZ-45457		Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card
 ** 6    2024-02-22  MY      JAZZ-67143		Filters acting unexpectedly post-adjustment - Issue #2
 *************************************************************/
CREATE   PROCEDURE [fp].[ServiceLineEncounterAdjustment_SEL_LIST]
	@budgetGUID UNIQUEIDENTIFIER,
	@start INT,
	@end INT,
	@search VARCHAR(MAX),
	@filter VARCHAR(MAX),
	@userGUID UNIQUEIDENTIFIER,
	@isDataSecured BIT,
	@dateTimeFormat VARCHAR(30),
	@userTimeZone VARCHAR(50)
AS 

BEGIN

	CREATE TABLE #departmentsSecurity (
		DepartmentID INT NULL,
		EntityID INT NULL
	)	

	CREATE TABLE #securedAdjustments (
		AdjustmentGUID UNIQUEIDENTIFIER
	)

	DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]()
	DECLARE @pageSize INT = @end - @start;

	SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
	SET @filter = LOWER(NULLIF(@filter, ''))

	SELECT		AdjustmentGUID
				,GroupingHierarchyJSON					
				,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
				,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID
				,AdjustmentType
				,GroupingGUID
	INTO	#adjustments
	FROM	fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK)	
	WHERE	slea.AdjustmentType IN (0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15) -- Supported Adjustment types for SLE Adjustments
		AND slea.BudgetConfigGUID = @budgetGUID

	IF @isDataSecured = 1
	BEGIN
		INSERT INTO #departmentsSecurity
		EXEC fp.DepartmentsSecurity_SEL 
			@userGUID = @userGUID,
			@pageName = 'Encounters'

		CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

		SELECT	AdjustmentGUID
				,ahd.ID AS DepartmentID
		INTO	#adjustmentGroupingHierarchyDepartments
		FROM (
				SELECT	adj.AdjustmentGUID
						,adj.GroupingHierarchyJSON
				FROM	#adjustments AS adj
				WHERE	adj.EntityID IS NULL
						AND adj.DepartmentID IS NULL) AS slea
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd
		GROUP BY AdjustmentGUID
				,ahd.ID

		SELECT	adj.AdjustmentGUID,
				ahe.ID AS EntityID
		INTO	#adjustmentGroupingHierarchyEntities
		FROM	#adjustments AS adj
				JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID
																		AND adhd.DepartmentID IS NULL
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
		GROUP BY adj.AdjustmentGUID	
				,ahe.ID
		
		INSERT INTO	#securedAdjustments
		SELECT	res.AdjustmentGUID
		FROM	(
			SELECT	slea.AdjustmentGUID
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID
			GROUP BY slea.AdjustmentGUID 

			UNION ALL

			SELECT	slea.AdjustmentGUID		
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
			WHERE	slea.DepartmentID IS NULL
			GROUP BY slea.AdjustmentGUID

			UNION ALL

			SELECT	aghd.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyDepartments AS aghd
					JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID
			WHERE	dshd.DepartmentID IS NOT NULL
			GROUP BY aghd.AdjustmentGUID

			UNION ALL

			SELECT	aghe.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyEntities AS aghe
					JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
			GROUP BY aghe.AdjustmentGUID

			UNION ALL

			SELECT	adj.AdjustmentGUID
			FROM	#adjustments AS adj
					JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID
					JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID
			WHERE	adj.DepartmentID IS NULL
					AND adj.EntityID IS NULL
					AND aghd.DepartmentID IS NULL
					AND aghe.EntityID IS NULL
					AND adj.AdjustmentType <> 15 -- Add provider adjustment, that has no grouping hierarchy, but has security
			GROUP BY adj.AdjustmentGUID

			UNION ALL
			
			SELECT	adj.AdjustmentGUID
			FROM	#adjustments AS adj
					JOIN fp.ServiceLineEncounterAddProviderAdjustment AS sleapa ON adj.AdjustmentGUID = sleapa.AdjustmentGUID
					JOIN #departmentsSecurity AS ds ON ds.DepartmentID = sleapa.DepartmentID
			GROUP BY adj.AdjustmentGUID
		) AS res

		-- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2)
		-- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the 
		-- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine.
		-- Essentially what we are doing here is using the child adjustments to find if they fall in security.
		-- In the event we have a child, populate the parent adjustment in the list.
		-- Find all the GroupingGuid's for any child adjustments that fall into security.
		
		SELECT DISTINCT adj.GroupingGUID
		INTO #groupingAdjustments
		FROM #securedAdjustments secured
			INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID
		WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments.

		-- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment.
		INSERT INTO #securedAdjustments
		SELECT adj.AdjustmentGUID
		FROM #adjustments adj
			INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID
			LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID
		WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments
			AND secured.AdjustmentGUID IS NULL

	END
	ELSE 
		BEGIN

			INSERT INTO #securedAdjustments
			SELECT	AdjustmentGUID
			FROM	#adjustments

		END
	
	CREATE CLUSTERED	INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID)

	SELECT	iadj.AdjustmentGuid, 
			iadj.EntityID
	INTO	#importAdjustments
	FROM	fp.ServiceLineEncounterAdjustmentImport AS iadj
			JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID
	GROUP BY iadj.AdjustmentGuid,
			iadj.EntityID
	
	CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, EntityID)

	SELECT res.TotalRowsCount
		,res.AdjustmentGUID
		,res.BudgetConfigGUID
		,res.AdjustmentType
		,res.[Value]
		,res.AdjustmentFilterJSON
		,res.GroupingHierarchyJSON
		,res.AdjustedProperty
		,res.Comment
		,res.AuthorGUID
		,res.AuthorFullName
		,res.LastModifiedDateUtc
		,res.DateCreatedUtc
		,res.GroupingGUID
		,res.TimeClassID
		,res.BudgetPhaseID
		,res.ClassificationGroupID
		,res.ClassificationCategoryID
		,res.UnitTypeID
		,res.ImportUnitTypeIDs
		,res.AddProviderFirstName
		,res.AddProviderLastName
		,res.AddProviderType		
		,res.IsRecordDeleted
		,res.IsErrored
	FROM (
		SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount,
			   *
		FROM (
			SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
				  ,slea.AdjustmentGUID
				  ,slea.BudgetConfigGUID
				  ,slea.AdjustmentType
				  ,slea.[Value]
				  ,slea.AdjustmentFilterJSON
				  ,slea.GroupingHierarchyJSON
				  ,slea.AdjustedProperty
				  ,ISNULL(ag.Description, slea.Comment) AS Comment
				  ,slea.AuthorGUID
				  ,slea.AuthorFullName
				  ,slea.LastModifiedDateUtc
				  ,slea.DateCreatedUtc
				  ,slea.GroupingGUID
				  ,slea.TimeClassID
				  ,slea.BudgetPhaseID
				  ,slea.ClassificationGroupID
				  ,slea.ClassificationCategoryID
				  ,CAST(140 AS TINYINT) AS UnitTypeID
				  ,sai.ImportUnitTypeIDs
				  ,NULL AS AddProviderFirstName
				  ,NULL AS AddProviderLastName
				  ,NULL AS AddProviderType
				  ,slea.IsRecordDeleted
				  ,slea.IsErrored
			FROM	fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK)
					JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID	
					LEFT JOIN (
						SELECT	p.AdjustmentGUID, 
								ImportUnitTypeIDs = '140'
						FROM	#importAdjustments AS p
								LEFT JOIN #departmentsSecurity AS ds ON ds.EntityID = p.EntityID
						GROUP BY p.AdjustmentGUID
					) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID				
					LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
					LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
																	AND slea.ClassificationCategoryID = acc.CategoryID
					LEFT JOIN fp.AdjustmentGrouping AS ag ON ag.GroupingGUID = slea.GroupingGUID
					LEFT JOIN (
						SELECT	nsa.GroupingGUID
						FROM	fp.ServiceLineEncounterAdjustment as nsa WITH (NOLOCK)
						WHERE	nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types
								AND nsa.BudgetConfigGUID = @budgetGUID
						GROUP BY nsa.GroupingGUID
					) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
			WHERE	(slea.AdjustmentType <> 4 
                        OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment
					AND (ra.GroupingGUID IS NULL
                        OR slea.AdjustmentType IN (12, 13, 14))
					AND slea.AdjustmentType <> 15 -- add provider adjustments
					AND (@search IS NULL 
						OR (
								LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
								OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\'
								OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR acc.[Name] LIKE @search ESCAPE '\'
								OR acg.[Name] LIKE @search ESCAPE '\'
								OR ('encounters' LIKE @search ESCAPE '\') -- because no other Measures are supported for ServiceLineEncounterAdjustment
								OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
							)
						)
					AND (@filter IS NULL
						OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
							SELECT	[value]
							FROM	STRING_SPLIT(@filter, ' ' )
							)
						)

			-- Add Provider adjustments
			UNION ALL			

			SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUTC DESC) AS RowNumber
				  ,slea.AdjustmentGUID
				  ,slea.BudgetConfigGUID
				  ,slea.AdjustmentType
				  ,slea.[Value]
				  ,slea.AdjustmentFilterJSON
				  ,slea.GroupingHierarchyJSON
				  ,slea.AdjustedProperty
				  ,aps.Comment
				  ,slea.AuthorGUID
				  ,slea.AuthorFullName
				  ,slea.LastModifiedDateUtc
				  ,slea.DateCreatedUTC
				  ,slea.GroupingGUID
				  ,slea.TimeClassID
				  ,slea.BudgetPhaseID
				  ,aps.ClassificationGroupID
				  ,aps.ClassificationCategoryID
				  ,NULL AS UnitTypeID
				  ,NULL AS ImportUnitTypeIDs
				  ,de.NameFirst AS AddProviderFirstName
				  ,de.NameLast AS AddProviderLastName
				  ,aps.EmployeeType AS AddProviderType				  
				  ,slea.IsRecordDeleted
				  ,slea.IsErrored
			FROM	fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK)			
					JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
					JOIN fp.AddProviderSummary AS aps ON aps.SLEncounterAdjustmentGUID = slea.AdjustmentGUID
					JOIN fw.DimEmployee AS de ON de.EmployeeID = aps.EmployeeID
					LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = aps.ClassificationGroupID
					LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acc.GroupID = acg.GroupID
																	AND aps.ClassificationCategoryID = acc.CategoryID
			WHERE	slea.AdjustmentType = 15 -- add provider adjustments
					AND (@search IS NULL 
						OR (
								LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
								OR LOWER(aps.Comment) LIKE @search ESCAPE '\'
								OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR acc.[Name] LIKE @search ESCAPE '\'
								OR acg.[Name] LIKE @search ESCAPE '\'
								OR de.NameFull LIKE @search ESCAPE '\'
							)
						)
					AND (@filter IS NULL
						OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
							SELECT	[value]
							FROM	STRING_SPLIT(@filter, ' ' )
							)
						)
			) AS res_inner
		WHERE res_inner.RowNumber = 1 ) AS res
	ORDER BY res.DateCreatedUtc DESC
	OFFSET @start ROWS
	FETCH NEXT @pageSize ROWS ONLY;
END
GO


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

-- fp.StaffingAdjustment_SEL_LIST
CREATE   PROCEDURE [fp].[StaffingAdjustment_SEL_LIST]
    @budgetGUID UNIQUEIDENTIFIER,
    @start INT,
    @end INT,
    @search VARCHAR(MAX),
    @filter VARCHAR(MAX),
    @userGUID UNIQUEIDENTIFIER,
    @isDataSecured BIT,
    @dateTimeFormat VARCHAR(30),
    @userTimeZone VARCHAR(50)
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2020-06-03  LR  	 JAZZ-134		Now including deleted items to be displayed in the activity pane
 ** 2	 2020-06-22  OP		 JAZZ-380		Added mix adjustment type
 ** 3	 2020-07-01  OP  	 JAZZ-635		Added AP Entity Config roles support
 ** 4 	 2020-08-20  OP  	 JAZZ-4123		Fixed import comment
 ** 5	 2020-11-03  OP		 JAZZ-7301		Fixed FTE block performance
 ** 6	 2021-01-12  OP		 JAZZ-5417		Removed JobCodeName from query - it wasn't used anywhere in app
 ** 7    2021-03-03  MD		 JAZZ-15738		Joined onto fp.StaffingManagerAdjustmentData to pull adjustments by time class
 ** 8    2021-03-18  OP		 JAZZ-16325		Filtered adjustments by Staff sub-section
 ** 9    2022-02-02  NT		 JAZZ-31672		Add filter & search logic when getting Employee Adjustments
 ** 10	 2022-06-30  AO		 JAZZ-37651 	Hide restricted Manager Adjustment cards for local user
 ** 11	 2023-01-06	 NT		 JAZZ-45457		Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card
 ** 12	 2023-01-06	 NT		 JAZZ-45457		Fix the sequence the new IsErrored field in the last unionized SQL as it is bombing #ntw
 ** 13   2023-07-03  DM		 JAZZ-54979		Display new My Budgets ManagerSet adjustments
 ** 14	 2023-08-31  DM		 JAZZ-58746		Staffing Import adjsutment are handled to show fte unit type when variable is edited
 ** 15   2024-02-22  MY      JAZZ-67143		Filters acting unexpectedly post-adjustment - Issue #2
 *************************************************************/
BEGIN

    -- Contains all DepartmnetID with correspond EntityID that are allowed for current user
    CREATE TABLE #departmentsSecurity (
        DepartmentID INT NULL,
        EntityID INT NULL
    )
        
    -- Adjustments that passes security check
    CREATE TABLE #securedAdjustments (
        AdjustmentGUID UNIQUEIDENTIFIER
    )
    
    DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]()
    DECLARE @pageSize INT = @end - @start;

    SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
    SET @filter = LOWER(NULLIF(@filter, ''))

    -- Select all possible to display adjustments
    SELECT    AdjustmentGUID
            ,GroupingHierarchyJSON                    
            ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
            ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID
			,AdjustmentType
			,GroupingGUID
    INTO    #adjustments
    FROM    [fp].[StaffingAdjustment] AS slea WITH (NOLOCK)    
    WHERE    slea.AdjustmentType IN (0, 2, 1, 4, 5, 6, 7, 8, 3, 10, 11, 12, 13, 14, 17, 20) -- Supported Adjustment types for Staffing Adjustments
        AND slea.BudgetConfigGUID = @budgetGUID

    IF @isDataSecured = 1
    BEGIN
        -- Get all departments that are allowed for current user
        INSERT INTO #departmentsSecurity
        EXEC fp.DepartmentsSecurity_SEL 
			@userGUID = @userGUID,
			@pageName = 'Staffing'

        -- Creating index for faster selects
        CREATE CLUSTERED    INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

        -- Select adjustments that have no Department/Entity on filters, but have DepartmentID
        -- on grouping hierarchy level
        SELECT    AdjustmentGUID
                ,ahd.ID AS DepartmentID
        INTO    #adjustmentGroupingHierarchyDepartments
        FROM (
                SELECT    adj.AdjustmentGUID
                        ,adj.GroupingHierarchyJSON
                FROM    #adjustments AS adj
                        -- Ignore departments that have DepartmentID and EntityID
                WHERE    adj.EntityID IS NULL
                        AND adj.DepartmentID IS NULL) AS slea
                OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd
        GROUP BY AdjustmentGUID
                ,ahd.ID

        -- Select adjustments that don't have DepartmentID on grouping hierarchy level
        -- but have EntityID on grouping hierarchy level
        SELECT    adj.AdjustmentGUID,
                ahe.ID AS EntityID
        INTO    #adjustmentGroupingHierarchyEntities
        FROM    #adjustments AS adj
                JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID
                                                                        AND adhd.DepartmentID IS NULL
               OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
        GROUP BY adj.AdjustmentGUID    
                ,ahe.ID
        
        INSERT INTO    #securedAdjustments
        SELECT    res.AdjustmentGUID
        FROM    (
            -- Adjustmnets that passes Department security by DepartmentID
            SELECT    slea.AdjustmentGUID
            FROM    #adjustments AS slea
                    JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID
            GROUP BY slea.AdjustmentGUID 

            UNION ALL

            -- Adjustmnets that passes Department security by EntityID
            SELECT    slea.AdjustmentGUID        
            FROM    #adjustments AS slea
                    JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
            WHERE    slea.DepartmentID IS NULL
            GROUP BY slea.AdjustmentGUID

            UNION ALL

            -- Insert adjustments that have allowed DepartmentID on their grouping hierarchy
            SELECT    aghd.AdjustmentGUID        
            FROM    #adjustmentGroupingHierarchyDepartments AS aghd
                    JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID
            WHERE    dshd.DepartmentID IS NOT NULL
            GROUP BY aghd.AdjustmentGUID

            UNION ALL

            -- Insert adjustments that have allowed EntityID on their grouping hierarchy
            SELECT    aghe.AdjustmentGUID        
            FROM    #adjustmentGroupingHierarchyEntities AS aghe
                    JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
            GROUP BY aghe.AdjustmentGUID

            UNION ALL

            -- Insert all adjustments that have no connection to department or entity
            SELECT    adj.AdjustmentGUID
            FROM    #adjustments AS adj
                    JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID
                    JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID
            WHERE    adj.DepartmentID IS NULL
                    AND adj.EntityID IS NULL
                    AND aghd.DepartmentID IS NULL
                    AND aghe.EntityID IS NULL
            GROUP BY adj.AdjustmentGUID
        ) AS res

		-- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2)
		-- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the 
		-- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine.
		-- Essentially what we are doing here is using the child adjustments to find if they fall in security.
		-- In the event we have a child, populate the parent adjustment in the list.
		-- Find all the GroupingGuid's for any child adjustments that fall into security.
		
		SELECT DISTINCT adj.GroupingGUID
		INTO #groupingAdjustments
		FROM #securedAdjustments secured
			INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID
		WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments.

		-- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment.
		INSERT INTO #securedAdjustments
		SELECT adj.AdjustmentGUID
		FROM #adjustments adj
			INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID
			LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID
		WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments
			AND secured.AdjustmentGUID IS NULL

    END
    ELSE 
        BEGIN

            -- In case there security is not applied just insert all adjustments
            INSERT INTO #securedAdjustments
            SELECT    AdjustmentGUID
            FROM    #adjustments

        END
     
    CREATE CLUSTERED    INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID)

    -- Select import adjustments that are allowed by security
    -- with UnitTypeID
    SELECT    iadj.AdjustmentGuid, 
            iadj.UnitTypeID,
			iadj.OriginalUnitTypeID,
            iadj.DepartmentID
    INTO    #importAdjustments
    FROM    fp.StaffingAdjustmentImport AS iadj
            JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID
    GROUP BY iadj.AdjustmentGuid,
            iadj.UnitTypeID,
			iadj.OriginalUnitTypeID,
            iadj.DepartmentID
    
    -- Creating indexes for faster selection
    CREATE CLUSTERED    INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID)

    SELECT res.TotalRowsCount
        ,res.AdjustmentGUID
        ,res.BudgetConfigGUID
        ,res.AdjustmentType
        ,res.[Value]
        ,res.AdjustmentFilterJSON
        ,res.GroupingHierarchyJSON
        ,res.AdjustedProperty
        ,res.Comment
        ,res.AuthorGUID
        ,res.AuthorFullName
        ,res.LastModifiedDateUtc
        ,res.DateCreatedUtc
        ,res.GroupingGUID
        ,res.TimeClassID
        ,res.BudgetPhaseID
        ,res.ClassificationGroupID
        ,res.ClassificationCategoryID
        ,res.JobCodeName
        ,res.JobCodeCount
        ,res.DepartmentName
        ,res.DepartmentCount
        ,res.UnitTypeID
        ,res.ImportUnitTypeIDs
		,res.IsRecordDeleted
		,res.EmployeeName
		,res.IsErrored
    FROM (
        -- Selecting total rows count, for paging to work correctly
        SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount,
               *
        FROM (
            -- ROW_NUMBER calcutes result query row numbers using the given condition
            -- Here, it calculated row numbers for each unique AdjustmentGUID
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                  ,slea.AdjustmentGUID
                  ,slea.BudgetConfigGUID
                  ,slea.AdjustmentType
                  ,slea.[Value]
                  ,slea.AdjustmentFilterJSON
                  ,slea.GroupingHierarchyJSON
                  ,slea.AdjustedProperty
                  ,ISNULL(ag.[Description], slea.Comment) AS Comment
                  ,slea.AuthorGUID
                  ,slea.AuthorFullName
                  ,slea.LastModifiedDateUtc
                  ,slea.DateCreatedUtc
                  ,slea.GroupingGUID
                  ,slea.TimeClassID
                  ,slea.BudgetPhaseID
                  ,slea.ClassificationGroupID
                  ,slea.ClassificationCategoryID
                  ,slea.UnitTypeID
                  ,NULL AS JobCodeName
                  ,NULL AS JobCodeCount
                  ,NULL AS DepartmentName
                  ,NULL AS DepartmentCount
                  ,sai.ImportUnitTypeIDs
				  ,slea.IsRecordDeleted
				  ,NULL AS EmployeeName
				  ,slea.IsErrored
            FROM    fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID                        
                    -- Getting the row of the import UnitTypeIDs
                    -- Adjustment can have multiple UnitTypeIDs in scope of one import, 
                    -- so not to multiply all the data just to get all the types,
                    -- they are concated into one string, with space separator.
                    -- Backend logic should parse this string

                    LEFT JOIN (
                        SELECT    p.AdjustmentGUID, 
                                ImportUnitTypeIDs =
                                -- According to this source: https://sqlperformance.com/2014/08/t-sql-queries/sql-server-grouped-concatenation,
                                -- STUFF FOR XML PATH is the best way to do this
                                TRIM(STUFF(
                                    (SELECT N' ' + CAST(ISNULL(p2.OriginalUnitTypeID, p2.UnitTypeID) AS VARCHAR(5))
                                    FROM    #importAdjustments AS p2
                                            LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = p2.DepartmentID
                                    WHERE    (ds.DepartmentID IS NOT NULL
                                                OR @isDataSecured = 0)
                                            AND p2.AdjustmentGUID = p.AdjustmentGUID
                                    GROUP BY p2.AdjustmentGUID, 
                                            p2.UnitTypeID,
											p2.OriginalUnitTypeID
                                    FOR XML PATH(N''))
                                , 1, 0, N''))
                        FROM    #importAdjustments AS p
                        GROUP BY p.AdjustmentGUID
                    ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID
                    LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID 
                    LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
                                                                    AND slea.ClassificationCategoryID = acc.CategoryID
                    LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
                    -- Selecting all the adjustments that should not be displayed
                    -- This adjustment are currently no supported, and this code will be removed in future
                    LEFT JOIN (
                        SELECT    nsa.GroupingGUID
                        FROM    fp.StaffingAdjustment as nsa WITH (NOLOCK)
                        WHERE    nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types
                                AND nsa.BudgetConfigGUID = @budgetGUID
                        GROUP BY nsa.GroupingGUID
                    ) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
            WHERE    (slea.AdjustmentType <> 4 
                        -- ImportUnitTypeIDs contains list of the all unit from adjustments for departments that are allowed
                        -- In case AdjustmentType is 4 (Import), and the ImportUnitTypeIDs contains no IDs,
                        -- Then all adjustments that was imported are for the departments that are not allowed
                        OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment
					AND slea.SubsectionID = 3 -- Staffing-Stuff
                    -- Restrict currently not allowed departments
                    AND (ra.GroupingGUID IS NULL
                        OR slea.AdjustmentType IN (12, 13, 14))
                    -- Ignore FTE adjustments in this select
                    AND slea.AdjustmentType <> 6 AND slea.AdjustmentType <> 7 AND slea.AdjustmentType <> 17 AND slea.AdjustmentType <> 20
                    -- Apply search, if needed
                    AND (@search IS NULL 
                        OR (
                                LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                                OR LOWER(ISNULL(ag.[Description], slea.Comment)) LIKE @search ESCAPE '\'
                                OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR ISNULL(acc.[Name], acg.[Name]) LIKE @search ESCAPE '\'
                                OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
                                OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
                                OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1
                            )
                        )
                    -- Apply filter, if needed
                    AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
                            SELECT    [value]
                            FROM    STRING_SPLIT(@filter, ' ' )
                            )
                        )

            UNION ALL
            
            -- FTE Adjustments were moved into UNION block
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.GroupingGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                  ,slea.GroupingGUID AS AdjustmentGUID
                  ,@budgetGUID AS BudgetConfigGUID
                  ,slea.AdjustmentType
                  ,fte.FTEAmount AS [Value]
 ,slea.AdjustmentFilterJSON
                  ,slea.GroupingHierarchyJSON
                  ,'' AS AdjustedProperty
                  ,CASE WHEN FTECount = 1
                        THEN fte.FTEComment
                        ELSE ''
                    END AS Comment
                  ,slea.AuthorGUID
                  ,slea.AuthorFullName
                  ,slea.LastModifiedDateUtc
                  ,slea.DateCreatedUtc
                  ,slea.GroupingGUID
                  ,slea.TimeClassID
				  ,slea.BudgetPhaseID
                  ,slea.ClassificationGroupID
                  ,slea.ClassificationCategoryID
                  ,NULL AS UnitTypeID
                  ,fte.JobCodeName
                  ,fte.JobCodeCount
                  ,fte.DepartmentName
                  ,fte.DepartmentCount
                  ,NULL AS ImportUnitTypeIDs
				  ,slea.IsRecordDeleted
				  ,NULL AS EmployeeName
				  ,slea.IsErrored
            FROM    (
						SELECT 
							slea_inner.GroupingGUID AS AdjustmentGUID
							,slea_inner.AdjustmentType
							,MIN(slea_inner.AdjustmentFilterJSON) AS AdjustmentFilterJSON
							,slea_inner.GroupingHierarchyJSON
							,slea_inner.AuthorGUID
							,slea_inner.AuthorFullName
							,MAX(slea_inner.LastModifiedDateUtc) AS LastModifiedDateUtc	
							,slea_inner.DateCreatedUtc
							,slea_inner.GroupingGUID
							,slea_inner.TimeClassID
							,slea_inner.BudgetPhaseID
							,slea_inner.ClassificationGroupID
							,slea_inner.ClassificationCategoryID
							,slea_inner.IsRecordDeleted
							,slea_inner.IsErrored
						FROM	fp.StaffingAdjustment AS slea_inner WITH (NOLOCK)
								JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea_inner.AdjustmentGUID
						WHERE	AdjustmentType = 6
								AND slea_inner.SubsectionID = 3 -- Staffing-Stuff
						GROUP BY
							slea_inner.GroupingGUID
							,slea_inner.AdjustmentType
							,slea_inner.GroupingHierarchyJSON
							,slea_inner.AuthorGUID
							,slea_inner.AuthorFullName
							,slea_inner.DateCreatedUtc
							,slea_inner.GroupingGUID
							,slea_inner.TimeClassID
							,slea_inner.BudgetPhaseID
							,slea_inner.ClassificationGroupID
							,slea_inner.ClassificationCategoryID
							,slea_inner.IsRecordDeleted
						   ,slea_inner.IsErrored
						) AS slea
                    JOIN ( 
                        SELECT 
                              MIN(dept.[Name]) AS DepartmentName
                              ,MIN(jc.[Name]) AS JobCodeName
                              ,OBJ.GroupingGUID
                              ,COUNT(OBJ.GroupingGUID) AS JobCodeCount
                              ,COUNT(OBJ.GroupingGUID) AS DepartmentCount
                              ,COUNT(OBJ.GroupingGUID) AS FTECount
                              ,CAST(SUM(OBJ.FTEAmount) AS DECIMAL(19,4)) AS FTEAmount
                              ,MAX(OBJ.Comment) AS FTEComment
                        FROM  fp.FTERequest AS OBJ WITH (NOLOCK)
                              JOIN fw.DimJobCode AS jc WITH (NOLOCK) ON jc.JobCodeID = OBJ.JobCodeID
                              JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID
						GROUP BY 
							OBJ.GroupingGUID
                    ) AS fte ON fte.GroupingGUID = slea.GroupingGUID
            WHERE  (@search IS NULL 
                        OR (
                                LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(fp.GetAdjustmentValue(fte.FTEAmount, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                                OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                                OR (fte.FTECount = 1 
                                    AND LOWER(fte.FTEComment) LIKE @search ESCAPE '\')
                                OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                                OR (fte.FTECount = 1 
                                    AND LOWER(fte.DepartmentName) LIKE @search ESCAPE '\')
                                OR (fte.FTECount = 1
                                    AND LOWER(fte.JobCodeName) LIKE @search ESCAPE '\')
                            )
                        )
                    AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
        SELECT    [value]
                            FROM    STRING_SPLIT(@filter, ' ' )
                            )
                        )
                      
              UNION ALL
            
              -- Manager Adjustments 
			  -- JAZZ-15738 - Partition by smad.TimeClassID as well
              SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, smad.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                   ,slea.AdjustmentGUID
                   ,slea.BudgetConfigGUID
                   ,slea.AdjustmentType
                   ,NULL AS [Value]
                   ,slea.AdjustmentFilterJSON
                   ,slea.GroupingHierarchyJSON
                   ,slea.AdjustedProperty
                   ,NULL AS Comment
                   ,slea.AuthorGUID
                   ,slea.AuthorFullName
                   ,slea.LastModifiedDateUtc
                   ,slea.DateCreatedUtc
                   ,slea.GroupingGUID
				   ,smad.TimeClassID
                   ,slea.BudgetPhaseID
                   ,slea.ClassificationGroupID
                   ,slea.ClassificationCategoryID
                   ,slea.UnitTypeId
                   ,adjComment.JobCodeName
                   ,adjComment.JobCodeCount
                   ,adjComment.DepartmentName
                   ,adjComment.DepartmentCount
                   ,NULL AS ImportUnitTypeIDs
				   ,slea.IsRecordDeleted
				   ,NULL AS EmployeeName
				   ,slea.IsErrored
            FROM    fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
					--JAZZ-15738
					LEFT JOIN fp.StaffingManagerAdjustmentData smad on slea.AdjustmentGUID = smad.AdjustmentGUID
                    LEFT JOIN (
                            SELECT
                                OBJ.AdjustmentGUID
                                ,dept.Name AS DepartmentName
                                ,NULL AS JobCodeName
                                ,COUNT(dept.DepartmentID) AS DepartmentCount
									  ,COUNT(DISTINCT job.JobCodeID) AS JobCodeCount
                            FROM fp.StaffingManagerAdjustmentComment AS OBJ WITH (NOLOCK)
                                JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID
                                LEFT JOIN fw.DimJobCode AS job WITH (NOLOCK) ON job.JobCodeID = OBJ.JobCodeID
								LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID 
							WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL
                            GROUP BY OBJ.AdjustmentGUID, dept.Name
                    ) AS adjComment ON adjComment.AdjustmentGUID = slea.AdjustmentGUID
                    LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
                    LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID
                                                                                        AND slea.ClassificationCategoryID = acc.CategoryID
              WHERE    slea.AdjustmentType = 7
				AND slea.SubsectionID = 3 -- Staffing-Stuff
                AND (@search IS NULL
                  OR (
                             LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                             OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                             OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                             OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                             OR acc.[Name] LIKE @search ESCAPE '\'
                             OR acg.[Name] LIKE @search ESCAPE '\'
                             OR 'my budgets' LIKE @search ESCAPE '\'
                             OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\'
                         )
                  )
                  AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, smad.TimeClassID, slea.BudgetPhaseID) IN (
                            SELECT    [value]
                            FROM    STRING_SPLIT(@filter, ' ' )
                            )
                        )
				  AND adjComment.DepartmentName IS NOT NULL	
						   
              UNION ALL
            
              -- ManagerSet (new My Budgets) Adjustments 
              SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, adjComment.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                   ,slea.AdjustmentGUID
                   ,slea.BudgetConfigGUID
                   ,slea.AdjustmentType
                   ,NULL AS [Value]
                   ,slea.AdjustmentFilterJSON
                   ,slea.GroupingHierarchyJSON
                   ,slea.AdjustedProperty
                   ,NULL AS Comment
                   ,slea.AuthorGUID
                   ,slea.AuthorFullName
                   ,slea.LastModifiedDateUtc
                   ,slea.DateCreatedUtc
                   ,slea.GroupingGUID
				   	   ,adjComment.TimeClassID
                   ,slea.BudgetPhaseID
                   ,slea.ClassificationGroupID
                   ,slea.ClassificationCategoryID
                   ,slea.UnitTypeId
                   ,adjComment.JobCodeName
                   ,adjComment.JobCodeCount
                   ,adjComment.DepartmentName
                   ,adjComment.DepartmentCount
                   ,NULL AS ImportUnitTypeIDs
				   ,slea.IsRecordDeleted
				   ,NULL AS EmployeeName
				   ,slea.IsErrored
            FROM    fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
                    LEFT JOIN (
                            SELECT
                                OBJ.AdjustmentID
                                ,dept.Name AS DepartmentName
									  ,NULL AS JobCodeName
                                ,STRING_AGG(CAST(job.Name AS NVARCHAR(MAX)), ';') AS JobCodeNames
                                ,STRING_AGG(CAST(OBJ.Comment AS NVARCHAR(MAX)), ';') AS Comments
                                ,COUNT(dept.DepartmentID) AS DepartmentCount
									  ,COUNT(DISTINCT job.JobCodeID) AS JobCodeCount
									  ,OBJ.TimeClassID
                            FROM fp.StaffingManagerSetAdjustmentComment AS OBJ WITH (NOLOCK)
                                JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID
                                LEFT JOIN fw.DimJobCode AS job WITH (NOLOCK) ON job.JobCodeID = OBJ.JobCodeID
								LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID 
							WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL
                            GROUP BY OBJ.AdjustmentID, dept.Name, OBJ.TimeClassID
                    ) AS adjComment ON adjComment.AdjustmentID = slea.AdjustmentID
                    LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
                    LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID
                                                                                        AND slea.ClassificationCategoryID = acc.CategoryID
              WHERE    slea.AdjustmentType = 20
				AND slea.SubsectionID = 3 
                AND (@search IS NULL
                  OR (
                             LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                             OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                             OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                             OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                             OR acc.[Name] LIKE @search ESCAPE '\'
                             OR acg.[Name] LIKE @search ESCAPE '\'
								  OR adjComment.JobCodeNames LIKE @search ESCAPE '\'
								  OR adjComment.Comments LIKE @search ESCAPE '\'
                             OR 'my budgets' LIKE @search ESCAPE '\'
                             OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\'
                         )
                  )
                  AND (@filter IS NULL
                        OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, adjComment.TimeClassID, slea.BudgetPhaseID) IN (
                            SELECT    [value]
                            FROM    STRING_SPLIT(@filter, ' ' )
                            )
                        )
				  AND adjComment.DepartmentName IS NOT NULL
						
			UNION ALL
            
              -- NPE Add Employee Adjustments 
              SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, smad.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
                   ,slea.AdjustmentGUID
                   ,slea.BudgetConfigGUID
                   ,slea.AdjustmentType
                   ,NULL AS [Value]
                   ,slea.AdjustmentFilterJSON
                   ,slea.GroupingHierarchyJSON
                   ,slea.AdjustedProperty
                   ,ebne.Comment AS Comment
                   ,slea.AuthorGUID
                   ,slea.AuthorFullName
                   ,slea.LastModifiedDateUtc
                   ,slea.DateCreatedUtc
                   ,slea.GroupingGUID
				   ,smad.TimeClassID
                   ,slea.BudgetPhaseID
                   ,slea.ClassificationGroupID
                   ,slea.ClassificationCategoryID
                   ,slea.UnitTypeId
                   ,job.Name AS JobCodeName
                   ,NULL AS JobCodeCount
                   ,dept.Name AS DepartmentName
                   ,NULL AS DepartmentCount
                   ,NULL AS ImportUnitTypeIDs
				   ,slea.IsRecordDeleted
				   ,emp.NameLast + ', ' + emp.NameFirst AS EmployeeName
				   ,slea.IsErrored
            FROM    fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
					LEFT JOIN fp.StaffingManagerAdjustmentData smad on slea.AdjustmentGUID = smad.AdjustmentGUID
                    JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = smad.DepartmentID
                    LEFT JOIN fw.DimJobCode AS job WITH (NOLOCK) ON job.JobCodeID = smad.JobCodeID
					LEFT JOIN fp.EmployeeBudgetingNewEmployee AS ebne WITH (NOLOCK) ON smad.EmployeeID = ebne.EmployeeID
					LEFT JOIN fw.DimEmployee AS emp WITH (NOLOCK) ON smad.EmployeeID = emp.EmployeeID
                    LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
                    LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID
                                                                                        AND slea.ClassificationCategoryID = acc.CategoryID
            WHERE    slea.AdjustmentType = 17
				AND slea.SubsectionID = 3 -- Staffing-Stuff
			   -- Apply search, if needed
             AND (@search IS NULL 
                    OR (
                            LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
                            OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
                            OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
                            OR LOWER(ebne.Comment) LIKE @search ESCAPE '\'
                            OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                            OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
                            OR ISNULL(acc.[Name], acg.[Name]) LIKE @search ESCAPE '\'
                            OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
                            OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
                            
                        )
                    )
             -- Apply filter, if needed       
				AND (@filter IS NULL
					OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, smad.TimeClassID, slea.BudgetPhaseID) IN (
						SELECT [value]
						FROM STRING_SPLIT(@filter, ' ' )
					)
					)
			-- GROUP BY slea.AdjustmentGUID, smad.TimeClassID, slea.BudgetPhaseID

                  ) AS res_inner
                  -- Selecting only unique adjustments
             WHERE res_inner.RowNumber = 1) AS res
    ORDER BY res.DateCreatedUtc DESC
        OFFSET @start ROWS
        FETCH NEXT @pageSize ROWS ONLY
		option (recompile)		 --!!!
		;

END;
GO


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

-- fp.StatisticsAddProviderRateCalculations
CREATE   PROCEDURE [fp].[StatisticsAddProviderRateCalculations]
	@BudgetConfigID INT,
	@MonthsLoaded TINYINT,
    @SelectedProviders [dbo].[SqlInt32ListTableType] READONLY,
	@DepartmentIds [dbo].[SqlInt32ListTableType] READONLY
 AS
 BEGIN
   
	SELECT	[value] AS ProviderID
	INTO	#BenchProviders
	FROM	@SelectedProviders

	SELECT	[value] AS DepartmentID
	INTO	#DepartmentSecurity
	FROM	@DepartmentIds

	SELECT	dsa.DriverAccountID,
			dsa.DependentAccountID,
			[dependent].Units / driver.Units AS Rate
	FROM (
	SELECT	fs.AccountID,
		case @Monthsloaded
				when 1 then SUM(fsh.ActualYTDValue01+fsh.PriorYearActualValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 2 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 3 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 4 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 5 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 6 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 7 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 8 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 9 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 10 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 11 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.PriorYearActualValue12)
				else SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.ActualYTDValue12)
		end AS Units
	FROM	fp.FactStatistics AS fs
			JOIN fp.FactStatisticsHistory AS fsh ON fsh.StatisticsID = fs.StatisticsID
			JOIN #BenchProviders AS p ON p.ProviderID = fs.ProviderID
			JOIN #DepartmentSecurity AS ds ON ds.DepartmentID = fs.DepartmentID
	WHERE	fs.BudgetConfigID = @BudgetConfigID
			AND SubsectionID = 1
			AND UnitTypeID = 140
	GROUP BY fs.AccountID ) as driver
	JOIN fp.DependentStatisticsAccount AS dsa ON dsa.DriverAccountID = driver.AccountID
	JOIN (			
		SELECT	fs.AccountID,
		case @Monthsloaded
				when 1 then SUM(fsh.ActualYTDValue01+fsh.PriorYearActualValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 2 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 3 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 4 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 5 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 6 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 7 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 8 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 9 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 10 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12)
				when 11 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.PriorYearActualValue12)
				else SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.ActualYTDValue12)
		end AS Units
	FROM	fp.FactStatistics AS fs
			JOIN fp.FactStatisticsHistory AS fsh ON fsh.StatisticsID = fs.StatisticsID
			JOIN #BenchProviders AS p ON p.ProviderID = fs.ProviderID
			JOIN #DepartmentSecurity AS ds ON ds.DepartmentID = fs.DepartmentID
	WHERE	fs.BudgetConfigID = @BudgetConfigID
			AND SubsectionID = 2
			AND UnitTypeID = 140
	GROUP BY fs.AccountID
		) as [dependent] ON [dependent].AccountID = dsa.DependentAccountID
	WHERE	dsa.BudgetConfigID = @BudgetConfigID
		AND driver.Units <> 0
		AND [dependent].Units <> 0
END
GO


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

-- fp.procABBFlexRecalcFTEs
/* ************************************************************************************************************************
** Author: Nathan LeRoy
** Create Date: 2015-12-15
** Description: Recalc payroll FTEs based on hours recalc
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	Workitem	Description
**	1		12/16/15	NL					changed to update instead of insert
**	2		03/25/16	NL					payroll pivoting fix
** 	3		02/27/17	NL					fixing arithmetic overflow error
**	4		03/25/17	NL					updating to use entity config
**  5       07/29/18	MY					update to use new structure
**  6       11/01/18	AI					added source dimensionality filter
**	7		02/06/18	BK		B-21763 	Exclude designated Productive Classes from FTE calc
**	8		04/04/19	NL					Adding budget phase filter
**	9		04/15/19	MY					Adding return data so that adjustments can be re-applied
**  10		07/30/19	NL		D-08399		changing FTE calc to use working hours instead of existing ratio
**	10		04/08/21	MY		JAZZ-17545	Cleaning up targeting and making proc more readable/Updated the proc to not update too much
**	11		10/31/23	MY		JAZZ-61705	Support PAF for the new data model - Staffing
**	12		07/02/24	DM		JAZZ-72920	Removed dependency for PercentAdjustmentFactor
*************************************************************************************************************************/
CREATE     PROC [fp].[procABBFlexRecalcFTEs]
    @EntityGroupConfigID INT,
    @FiscalYearID SMALLINT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS

	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#flexHours') IS NOT NULL DROP TABLE #flexHours
	IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs
	CREATE TABLE #basisIDs (StaffingID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		where d.EntityGroupConfigID = @EntityGroupConfigID
	END
	
	SELECT base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		base.TargetAdjustedHours01, 
		base.TargetAdjustedHours02, 
		base.TargetAdjustedHours03, 
		base.TargetAdjustedHours04, 
		base.TargetAdjustedHours05, 
		base.TargetAdjustedHours06, 
		base.TargetAdjustedHours07, 
		base.TargetAdjustedHours08, 
		base.TargetAdjustedHours09, 
		base.TargetAdjustedHours10, 
		base.TargetAdjustedHours11, 
		base.TargetAdjustedHours12,
																	    
		base.BudgetAdjustedHours01, 
		base.BudgetAdjustedHours02,
		base.BudgetAdjustedHours03, 
		base.BudgetAdjustedHours04, 
		base.BudgetAdjustedHours05, 
		base.BudgetAdjustedHours06, 
		base.BudgetAdjustedHours07, 
		base.BudgetAdjustedHours08, 
		base.BudgetAdjustedHours09, 
		base.BudgetAdjustedHours10, 
		base.BudgetAdjustedHours11, 
		base.BudgetAdjustedHours12
	INTO #flexHours
    FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID
    WHERE base.VariabilityID = 2
        AND base.EntityGroupConfigID = @EntityGroupConfigID

	UPDATE fs
	SET
	  fs.TargetAdjustedFTEs01 = COALESCE((flexHours.TargetAdjustedHours01 / NULLIF(wh.Month01, 0)), 0),
	  fs.TargetAdjustedFTEs02 = COALESCE((flexHours.TargetAdjustedHours02 / NULLIF(wh.Month02, 0)), 0),
	  fs.TargetAdjustedFTEs03 = COALESCE((flexHours.TargetAdjustedHours03 / NULLIF(wh.Month03, 0)), 0),
	  fs.TargetAdjustedFTEs04 = COALESCE((flexHours.TargetAdjustedHours04 / NULLIF(wh.Month04, 0)), 0),
	  fs.TargetAdjustedFTEs05 = COALESCE((flexHours.TargetAdjustedHours05 / NULLIF(wh.Month05, 0)), 0),
	  fs.TargetAdjustedFTEs06 = COALESCE((flexHours.TargetAdjustedHours06 / NULLIF(wh.Month06, 0)), 0),
	  fs.TargetAdjustedFTEs07 = COALESCE((flexHours.TargetAdjustedHours07 / NULLIF(wh.Month07, 0)), 0),
	  fs.TargetAdjustedFTEs08 = COALESCE((flexHours.TargetAdjustedHours08 / NULLIF(wh.Month08, 0)), 0),
	  fs.TargetAdjustedFTEs09 = COALESCE((flexHours.TargetAdjustedHours09 / NULLIF(wh.Month09, 0)), 0),
	  fs.TargetAdjustedFTEs10 = COALESCE((flexHours.TargetAdjustedHours10 / NULLIF(wh.Month10, 0)), 0),
	  fs.TargetAdjustedFTEs11 = COALESCE((flexHours.TargetAdjustedHours11 / NULLIF(wh.Month11, 0)), 0),
	  fs.TargetAdjustedFTEs12 = COALESCE((flexHours.TargetAdjustedHours12 / NULLIF(wh.Month12, 0)), 0),

	  fs.BudgetAdjustedFTEs01 = COALESCE((flexHours.BudgetAdjustedHours01 / NULLIF(wh.Month01, 0)), 0),
	  fs.BudgetAdjustedFTEs02 = COALESCE((flexHours.BudgetAdjustedHours02 / NULLIF(wh.Month02, 0)), 0),
	  fs.BudgetAdjustedFTEs03 = COALESCE((flexHours.BudgetAdjustedHours03 / NULLIF(wh.Month03, 0)), 0),
	  fs.BudgetAdjustedFTEs04 = COALESCE((flexHours.BudgetAdjustedHours04 / NULLIF(wh.Month04, 0)), 0),
	  fs.BudgetAdjustedFTEs05 = COALESCE((flexHours.BudgetAdjustedHours05 / NULLIF(wh.Month05, 0)), 0),
	  fs.BudgetAdjustedFTEs06 = COALESCE((flexHours.BudgetAdjustedHours06 / NULLIF(wh.Month06, 0)), 0),
	  fs.BudgetAdjustedFTEs07 = COALESCE((flexHours.BudgetAdjustedHours07 / NULLIF(wh.Month07, 0)), 0),
	  fs.BudgetAdjustedFTEs08 = COALESCE((flexHours.BudgetAdjustedHours08 / NULLIF(wh.Month08, 0)), 0),
	  fs.BudgetAdjustedFTEs09 = COALESCE((flexHours.BudgetAdjustedHours09 / NULLIF(wh.Month09, 0)), 0),
	  fs.BudgetAdjustedFTEs10 = COALESCE((flexHours.BudgetAdjustedHours10 / NULLIF(wh.Month10, 0)), 0),
	  fs.BudgetAdjustedFTEs11 = COALESCE((flexHours.BudgetAdjustedHours11 / NULLIF(wh.Month11, 0)), 0),
	  fs.BudgetAdjustedFTEs12 = COALESCE((flexHours.BudgetAdjustedHours12 / NULLIF(wh.Month12, 0)), 0)
	OUTPUT 
	    INSERTED.StaffingID
	INTO
	    #basisIDs (StaffingID) 
	FROM [fp].[Staffing] fs
		INNER JOIN #FilterByDepartment s ON s.DepartmentID = fs.DepartmentID	
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
		INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID
		INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID 
		LEFT JOIN #flexHours flexHours
	       ON flexHours.DepartmentID = fs.DepartmentID
	            AND flexHours.EntityID = fs.EntityID
	            AND flexHours.JobCodeID = fs.JobCodeID
	            AND flexHours.PayCodeGroupID = fs.PayCodeGroupID
	            AND flexHours.EntityGroupConfigID = fs.EntityGroupConfigID
	            AND flexHours.VariabilityID = fs.VariabilityID	
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
	  AND fs.VariabilityID = 2
	  AND exc.PayCodeGroupID IS NULL
	  AND fs.FlexingTypeID = 7 -- Patient Activity
	  
	-- Return the data back so we can re-apply any percent adjustments and refresh the change history
	SELECT StaffingID, m.FiscalMonthID, CAST(2 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CAST(144 AS TINYINT) AS UnitTypeID, f.Value
	FROM (
		SELECT bdgt.StaffingID, bdgt.TargetAdjustedFTEs01, bdgt.TargetAdjustedFTEs02, bdgt.TargetAdjustedFTEs03, bdgt.TargetAdjustedFTEs04, bdgt.TargetAdjustedFTEs05, bdgt.TargetAdjustedFTEs06, 
								bdgt.TargetAdjustedFTEs07, bdgt.TargetAdjustedFTEs08, bdgt.TargetAdjustedFTEs09, bdgt.TargetAdjustedFTEs10, bdgt.TargetAdjustedFTEs11, bdgt.TargetAdjustedFTEs12
		FROM #basisIDs ids 
			 INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID
	) gl
	UNPIVOT ( Value FOR FiscalMonth IN (TargetAdjustedFTEs01, TargetAdjustedFTEs02, TargetAdjustedFTEs03, TargetAdjustedFTEs04, TargetAdjustedFTEs05, TargetAdjustedFTEs06, TargetAdjustedFTEs07, TargetAdjustedFTEs08, TargetAdjustedFTEs09, TargetAdjustedFTEs10, TargetAdjustedFTEs11, TargetAdjustedFTEs12)) as f
	LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetAdjustedFTEs', 'Month')
	UNION ALL
	SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CAST(144 AS TINYINT) AS UnitTypeID, f.Value
	FROM (
		SELECT bdgt.StaffingID, bdgt.BudgetAdjustedFTEs01, bdgt.BudgetAdjustedFTEs02, bdgt.BudgetAdjustedFTEs03, bdgt.BudgetAdjustedFTEs04, bdgt.BudgetAdjustedFTEs05, bdgt.BudgetAdjustedFTEs06, 
								bdgt.BudgetAdjustedFTEs07, bdgt.BudgetAdjustedFTEs08, bdgt.BudgetAdjustedFTEs09, bdgt.BudgetAdjustedFTEs10, bdgt.BudgetAdjustedFTEs11, bdgt.BudgetAdjustedFTEs12
		FROM #basisIDs ids 
			 INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID
	) gl
	UNPIVOT ( Value FOR FiscalMonth IN (BudgetAdjustedFTEs01, BudgetAdjustedFTEs02, BudgetAdjustedFTEs03, BudgetAdjustedFTEs04, BudgetAdjustedFTEs05, BudgetAdjustedFTEs06, BudgetAdjustedFTEs07, BudgetAdjustedFTEs08, BudgetAdjustedFTEs09, BudgetAdjustedFTEs10, BudgetAdjustedFTEs11, BudgetAdjustedFTEs12)) as f
	LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjustedFTEs', 'Month')
GO


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

-- fp.procABBFlexRecalcFTEs_Initial
CREATE   PROC [fp].[procABBFlexRecalcFTEs_Initial]
    @EntityGroupConfigID INT,
    @FiscalYearID SMALLINT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	2022-07-13  MD      JAZZ-28981		Initial
	** 2	2023-10-31  MY      JAZZ-61705		Support PAF for the new data model - Staffing
	*************************************************************/

	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#flexHours') IS NOT NULL DROP TABLE #flexHours
	IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs
	CREATE TABLE #basisIDs (StaffingID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		WHERE d.EntityGroupConfigID = @EntityGroupConfigID
	   		AND SubsectionID = 3
	   		AND FlexingTypeID = 7 -- Patient Activity
	END
	
	SELECT 
		base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		base.InitialBudgetHours01, base.InitialBudgetHours02, base.InitialBudgetHours03, base.InitialBudgetHours04, 
		base.InitialBudgetHours05, base.InitialBudgetHours06, base.InitialBudgetHours07, base.InitialBudgetHours08, 
		base.InitialBudgetHours09, base.InitialBudgetHours10, base.InitialBudgetHours11, base.InitialBudgetHours12
	INTO #flexHours
    FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID	
    WHERE base.VariabilityID = 2
        AND base.EntityGroupConfigID = @EntityGroupConfigID
	    AND base.SubsectionID = 3

	UPDATE
	  baseFtes
	SET
		InitialBudgetFTEs01 = COALESCE((flexHours.InitialBudgetHours01 / NULLIF(wh.Month01, 0)), 0),
		InitialBudgetFTEs02 = COALESCE((flexHours.InitialBudgetHours02 / NULLIF(wh.Month02, 0)), 0),
		InitialBudgetFTEs03 = COALESCE((flexHours.InitialBudgetHours03 / NULLIF(wh.Month03, 0)), 0),
		InitialBudgetFTEs04 = COALESCE((flexHours.InitialBudgetHours04 / NULLIF(wh.Month04, 0)), 0),
		InitialBudgetFTEs05 = COALESCE((flexHours.InitialBudgetHours05 / NULLIF(wh.Month05, 0)), 0),
		InitialBudgetFTEs06 = COALESCE((flexHours.InitialBudgetHours06 / NULLIF(wh.Month06, 0)), 0),
		InitialBudgetFTEs07 = COALESCE((flexHours.InitialBudgetHours07 / NULLIF(wh.Month07, 0)), 0),
		InitialBudgetFTEs08 = COALESCE((flexHours.InitialBudgetHours08 / NULLIF(wh.Month08, 0)), 0),
		InitialBudgetFTEs09 = COALESCE((flexHours.InitialBudgetHours09 / NULLIF(wh.Month09, 0)), 0),
		InitialBudgetFTEs10 = COALESCE((flexHours.InitialBudgetHours10 / NULLIF(wh.Month10, 0)), 0),
		InitialBudgetFTEs11 = COALESCE((flexHours.InitialBudgetHours11 / NULLIF(wh.Month11, 0)), 0),
		InitialBudgetFTEs12 = COALESCE((flexHours.InitialBudgetHours12 / NULLIF(wh.Month12, 0)), 0)
	OUTPUT 
	    INSERTED.StaffingID
	INTO
	    #basisIDs (StaffingID) 
	FROM [fp].[Staffing] baseFtes
		INNER JOIN #FilterByDepartment s ON s.DepartmentID = baseFtes.DepartmentID	
		INNER JOIN [fw].[DimJobCode] jc on baseFtes.JobCodeID = jc.JobCodeID
		INNER JOIN [fw].[DimDepartment] dept on baseFtes.DepartmentID = dept.DepartmentID
		INNER JOIN [client].[FactWorkingHoursPerMonth] wh 
			on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)		
		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc 
			on baseFtes.PayCodeGroupID = exc.PayCodeGroupID 
		LEFT JOIN #flexHours flexHours
	       ON flexHours.DepartmentID = baseFtes.DepartmentID
	            AND flexHours.EntityID = baseFtes.EntityID
	            AND flexHours.JobCodeID = baseFtes.JobCodeID
	            AND flexHours.PayCodeGroupID = baseFtes.PayCodeGroupID
	            AND flexHours.EntityGroupConfigID = baseFtes.EntityGroupConfigID
	            AND flexHours.VariabilityID = baseFtes.VariabilityID	
	WHERE baseFtes.EntityGroupConfigID = @EntityGroupConfigID
	  AND baseFtes.VariabilityID = 2
	  AND exc.PayCodeGroupID IS NULL
	  AND baseFtes.FlexingTypeID = 7 -- Patient Activity
	  AND baseFtes.SubsectionID = 3

	SELECT StaffingID as BasisID from #basisIDs
GO


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

-- fp.procABBFlexRecalcFTEs_Projection
/**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	Workitem	Description
**	1		07/22/22	MD		JAZZ-38981	Initial
**  2 	    2023-10-31  MY      JAZZ-61705	Support PAF for the new data model - Staffing
**	3		07/02/24	DM		JAZZ-72920	Removed dependency for PercentAdjustmentFactor
*************************************************************************************************************************/
CREATE     PROC [fp].[procABBFlexRecalcFTEs_Projection]
    @EntityGroupConfigID INT,
    @FiscalYearID SMALLINT,
	@MonthsLoaded INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS

	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#flexHours') IS NOT NULL DROP TABLE #flexHours
	IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs
	CREATE TABLE #basisIDs (StaffingID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		where d.EntityGroupConfigID = @EntityGroupConfigID
	END
	
	SELECT 
		base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		base.ProjectionAdjustedHours01, 
		base.ProjectionAdjustedHours02, 
		base.ProjectionAdjustedHours03, 
		base.ProjectionAdjustedHours04, 
		base.ProjectionAdjustedHours05, 
		base.ProjectionAdjustedHours06, 
		base.ProjectionAdjustedHours07, 
		base.ProjectionAdjustedHours08, 
		base.ProjectionAdjustedHours09, 
		base.ProjectionAdjustedHours10,
		base.ProjectionAdjustedHours11, 
		base.ProjectionAdjustedHours12
	INTO #flexHours
    FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID	
    WHERE base.VariabilityID = 2
        AND base.EntityGroupConfigID = @EntityGroupConfigID

	UPDATE fs
	SET
		fs.ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded < 1  THEN COALESCE((flexHours.ProjectionAdjustedHours01 / NULLIF(wh.Month01, 0)), 0) ELSE fs.ProjectionAdjustedFTEs01 END,
		fs.ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded < 2  THEN COALESCE((flexHours.ProjectionAdjustedHours02 / NULLIF(wh.Month02, 0)), 0) ELSE fs.ProjectionAdjustedFTEs02 END,
		fs.ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded < 3  THEN COALESCE((flexHours.ProjectionAdjustedHours03 / NULLIF(wh.Month03, 0)), 0) ELSE fs.ProjectionAdjustedFTEs03 END,
		fs.ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded < 4  THEN COALESCE((flexHours.ProjectionAdjustedHours04 / NULLIF(wh.Month04, 0)), 0) ELSE fs.ProjectionAdjustedFTEs04 END,
		fs.ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded < 5  THEN COALESCE((flexHours.ProjectionAdjustedHours05 / NULLIF(wh.Month05, 0)), 0) ELSE fs.ProjectionAdjustedFTEs05 END,
		fs.ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded < 6  THEN COALESCE((flexHours.ProjectionAdjustedHours06 / NULLIF(wh.Month06, 0)), 0) ELSE fs.ProjectionAdjustedFTEs06 END,
		fs.ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded < 7  THEN COALESCE((flexHours.ProjectionAdjustedHours07 / NULLIF(wh.Month07, 0)), 0) ELSE fs.ProjectionAdjustedFTEs07 END,
		fs.ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded < 8  THEN COALESCE((flexHours.ProjectionAdjustedHours08 / NULLIF(wh.Month08, 0)), 0) ELSE fs.ProjectionAdjustedFTEs08 END,
		fs.ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded < 9  THEN COALESCE((flexHours.ProjectionAdjustedHours09 / NULLIF(wh.Month09, 0)), 0) ELSE fs.ProjectionAdjustedFTEs09 END,
		fs.ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded < 10 THEN COALESCE((flexHours.ProjectionAdjustedHours10 / NULLIF(wh.Month10, 0)), 0) ELSE fs.ProjectionAdjustedFTEs10 END,
		fs.ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded < 11 THEN COALESCE((flexHours.ProjectionAdjustedHours11 / NULLIF(wh.Month11, 0)), 0) ELSE fs.ProjectionAdjustedFTEs11 END,
		fs.ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded < 12 THEN COALESCE((flexHours.ProjectionAdjustedHours12 / NULLIF(wh.Month12, 0)), 0) ELSE fs.ProjectionAdjustedFTEs12 END
	OUTPUT INSERTED.StaffingID
	INTO #basisIDs (StaffingID) 
	FROM [fp].[Staffing] fs
		INNER JOIN #FilterByDepartment s ON s.DepartmentID = fs.DepartmentID	
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
		INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID
		INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID 
		LEFT JOIN #flexHours flexHours
	       ON flexHours.DepartmentID = fs.DepartmentID
	            AND flexHours.EntityID = fs.EntityID
	            AND flexHours.JobCodeID = fs.JobCodeID
	            AND flexHours.PayCodeGroupID = fs.PayCodeGroupID
	            AND flexHours.EntityGroupConfigID = fs.EntityGroupConfigID
	            AND flexHours.VariabilityID = fs.VariabilityID	
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
		AND fs.VariabilityID = 2
		AND exc.PayCodeGroupID IS NULL
		AND fs.FlexingTypeID = 7 -- Patient Activity
	  
	-- Return the data back so we can re-apply any percent adjustments and refresh the change history
	SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(12 AS TINYINT) AS TimeClassID, CAST(144 AS TINYINT) AS UnitTypeID, f.Value
	FROM (
		SELECT 
			proj.StaffingID,
			proj.ProjectionAdjustedFTEs01, proj.ProjectionAdjustedFTEs02, proj.ProjectionAdjustedFTEs03, proj.ProjectionAdjustedFTEs04, 
			proj.ProjectionAdjustedFTEs05, proj.ProjectionAdjustedFTEs06, proj.ProjectionAdjustedFTEs07, proj.ProjectionAdjustedFTEs08, 
			proj.ProjectionAdjustedFTEs09, proj.ProjectionAdjustedFTEs10, proj.ProjectionAdjustedFTEs11, proj.ProjectionAdjustedFTEs12
		FROM #basisIDs ids
			 INNER JOIN [fp].[Staffing] proj ON ids.StaffingID = proj.StaffingID 
	) gl
	UNPIVOT ( Value FOR FiscalMonth IN (ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs02, ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs06, ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs10, ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs12)) as f
	LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjustedFTEs', 'Month')
GO


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

-- fp.procABBFlexRecalcHours
/*************************************************************************************************************************
** Author: Nathan LeRoy
** Create Date: 2015-12-15
** Description: Recalc payroll hours based on dollars flexing
** Last Modified: 2018-11-01
**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI		        Description
**	1		12/16/15	NL				        changed to update instead of insert
**	2		03/25/16	NL				        payroll pivoting fix
**  3		12/07/16	NL				        added variabilityID
**	4		03/25/17	NL				        updating to use entity config
**  5   	07/29/18	MY				        update to use new structure
**  6 	  	11/01/18	AI				        add source dimensionality
**	7		04/04/19	NL				        fixing join on wage rate
**	8		04/15/19	MY				        adding return data so that adjustments can be re-applied
**	9		01/18/21	BW				        removing inner join on UserDefinedTableType [fp].[BudgetRefreshSourceDimensionality]; use temp table instead
**	10		04/08/21	MY		JAZZ-17545		Cleaning up targeting and making proc more readable/Updated the proc to not update too much
**  11		2023-10-31  MY      JAZZ-61705		Support PAF for the new data model - Staffing
**	12		07/02/24	DM		JAZZ-72920		Removed dependency for PercentAdjustmentFactor
*************************************************************************************************************************/
CREATE     PROC [fp].[procABBFlexRecalcHours]
    @EntityGroupConfigID INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs
	IF OBJECT_ID('tempdb..#flexDollars') IS NOT NULL DROP TABLE #flexDollars
	IF OBJECT_ID('tempdb..#origWageRate') IS NOT NULL DROP TABLE #origWageRate

	CREATE TABLE #basisIDs (StaffingID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		where d.EntityGroupConfigID = @EntityGroupConfigID
	END
	
	-- For the purposes of recalculating the hours, we need to pre-adjusted value
	SELECT base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		base.TargetAdjustedDollars01, 
		base.TargetAdjustedDollars02, 
		base.TargetAdjustedDollars03, 
		base.TargetAdjustedDollars04, 
		base.TargetAdjustedDollars05, 
		base.TargetAdjustedDollars06, 
		base.TargetAdjustedDollars07, 
		base.TargetAdjustedDollars08, 
		base.TargetAdjustedDollars09, 
		base.TargetAdjustedDollars10, 
		base.TargetAdjustedDollars11, 
		base.TargetAdjustedDollars12,
																    
		base.BudgetAdjustedDollars01, 
		base.BudgetAdjustedDollars02,
		base.BudgetAdjustedDollars03, 
		base.BudgetAdjustedDollars04, 
		base.BudgetAdjustedDollars05, 
		base.BudgetAdjustedDollars06, 
		base.BudgetAdjustedDollars07, 
		base.BudgetAdjustedDollars08, 
		base.BudgetAdjustedDollars09, 
		base.BudgetAdjustedDollars10, 
		base.BudgetAdjustedDollars11, 
		base.BudgetAdjustedDollars12
	INTO #flexDollars
	FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID
	WHERE base.VariabilityID = 2
	    AND base.EntityGroupConfigID = @EntityGroupConfigID
		
	SELECT base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		wr.TargetAdjusted01, wr.TargetAdjusted02, wr.TargetAdjusted03, wr.TargetAdjusted04, wr.TargetAdjusted05, wr.TargetAdjusted06, 
		wr.TargetAdjusted07, wr.TargetAdjusted08, wr.TargetAdjusted09, wr.TargetAdjusted10, wr.TargetAdjusted11, wr.TargetAdjusted12,
		wr.BudgetAdjusted01, wr.BudgetAdjusted02, wr.BudgetAdjusted03, wr.BudgetAdjusted04, wr.BudgetAdjusted05, wr.BudgetAdjusted06, 
		wr.BudgetAdjusted07, wr.BudgetAdjusted08, wr.BudgetAdjusted09, wr.BudgetAdjusted10, wr.BudgetAdjusted11, wr.BudgetAdjusted12
	INTO #origWageRate
    FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID	
    	INNER JOIN [fp].[StaffingWageRate] wr ON base.StaffingWageRateID = wr.StaffingWageRateID
    WHERE base.VariabilityID = 2
    	AND base.EntityGroupConfigID = @EntityGroupConfigID

	UPDATE
	  hours
	SET
	  hours.TargetAdjustedHours01 = COALESCE(flexDollars.TargetAdjustedDollars01 / NULLIF(origWageRate.TargetAdjusted01, 0), 0),
	  hours.TargetAdjustedHours02 = COALESCE(flexDollars.TargetAdjustedDollars02 / NULLIF(origWageRate.TargetAdjusted02, 0), 0),
	  hours.TargetAdjustedHours03 = COALESCE(flexDollars.TargetAdjustedDollars03 / NULLIF(origWageRate.TargetAdjusted03, 0), 0),
	  hours.TargetAdjustedHours04 = COALESCE(flexDollars.TargetAdjustedDollars04 / NULLIF(origWageRate.TargetAdjusted04, 0), 0),
	  hours.TargetAdjustedHours05 = COALESCE(flexDollars.TargetAdjustedDollars05 / NULLIF(origWageRate.TargetAdjusted05, 0), 0),
	  hours.TargetAdjustedHours06 = COALESCE(flexDollars.TargetAdjustedDollars06 / NULLIF(origWageRate.TargetAdjusted06, 0), 0),
	  hours.TargetAdjustedHours07 = COALESCE(flexDollars.TargetAdjustedDollars07 / NULLIF(origWageRate.TargetAdjusted07, 0), 0),
	  hours.TargetAdjustedHours08 = COALESCE(flexDollars.TargetAdjustedDollars08 / NULLIF(origWageRate.TargetAdjusted08, 0), 0),
	  hours.TargetAdjustedHours09 = COALESCE(flexDollars.TargetAdjustedDollars09 / NULLIF(origWageRate.TargetAdjusted09, 0), 0),
	  hours.TargetAdjustedHours10 = COALESCE(flexDollars.TargetAdjustedDollars10 / NULLIF(origWageRate.TargetAdjusted10, 0), 0),
	  hours.TargetAdjustedHours11 = COALESCE(flexDollars.TargetAdjustedDollars11 / NULLIF(origWageRate.TargetAdjusted11, 0), 0),
	  hours.TargetAdjustedHours12 = COALESCE(flexDollars.TargetAdjustedDollars12 / NULLIF(origWageRate.TargetAdjusted12, 0), 0),
	  hours.BudgetAdjustedHours01 = COALESCE(flexDollars.BudgetAdjustedDollars01 / NULLIF(origWageRate.BudgetAdjusted01, 0), 0),
	  hours.BudgetAdjustedHours02 = COALESCE(flexDollars.BudgetAdjustedDollars02 / NULLIF(origWageRate.BudgetAdjusted02, 0), 0),
	  hours.BudgetAdjustedHours03 = COALESCE(flexDollars.BudgetAdjustedDollars03 / NULLIF(origWageRate.BudgetAdjusted03, 0), 0),
	  hours.BudgetAdjustedHours04 = COALESCE(flexDollars.BudgetAdjustedDollars04 / NULLIF(origWageRate.BudgetAdjusted04, 0), 0),
	  hours.BudgetAdjustedHours05 = COALESCE(flexDollars.BudgetAdjustedDollars05 / NULLIF(origWageRate.BudgetAdjusted05, 0), 0),
	  hours.BudgetAdjustedHours06 = COALESCE(flexDollars.BudgetAdjustedDollars06 / NULLIF(origWageRate.BudgetAdjusted06, 0), 0),
	  hours.BudgetAdjustedHours07 = COALESCE(flexDollars.BudgetAdjustedDollars07 / NULLIF(origWageRate.BudgetAdjusted07, 0), 0),
	  hours.BudgetAdjustedHours08 = COALESCE(flexDollars.BudgetAdjustedDollars08 / NULLIF(origWageRate.BudgetAdjusted08, 0), 0),
	  hours.BudgetAdjustedHours09 = COALESCE(flexDollars.BudgetAdjustedDollars09 / NULLIF(origWageRate.BudgetAdjusted09, 0), 0),
	  hours.BudgetAdjustedHours10 = COALESCE(flexDollars.BudgetAdjustedDollars10 / NULLIF(origWageRate.BudgetAdjusted10, 0), 0),
	  hours.BudgetAdjustedHours11 = COALESCE(flexDollars.BudgetAdjustedDollars11 / NULLIF(origWageRate.BudgetAdjusted11, 0), 0),
	  hours.BudgetAdjustedHours12 = COALESCE(flexDollars.BudgetAdjustedDollars12 / NULLIF(origWageRate.BudgetAdjusted12, 0), 0)
	OUTPUT 
	    INSERTED.StaffingID
	INTO
	    #basisIDs (StaffingID) 
	FROM [fp].[Staffing] hours
		INNER JOIN #FilterByDepartment s ON s.DepartmentID = hours.DepartmentID	
	    LEFT JOIN #flexDollars flexDollars ON flexDollars.DepartmentID = hours.DepartmentID
			AND flexDollars.EntityID = hours.EntityID
			AND flexDollars.JobCodeID = hours.JobCodeID
			AND flexDollars.PayCodeGroupID = hours.PayCodeGroupID
			AND flexDollars.EntityGroupConfigID = hours.EntityGroupConfigID
	    LEFT JOIN #origWageRate origWageRate ON flexDollars.DepartmentID = origWageRate.DepartmentID
			AND flexDollars.EntityID = origWageRate.EntityID
			AND flexDollars.JobCodeID = origWageRate.JobCodeID
			AND flexDollars.PayCodeGroupID = origWageRate.PayCodeGroupID
			AND flexDollars.EntityGroupConfigID = origWageRate.EntityGroupConfigID
	WHERE hours.EntityGroupConfigID = @EntityGroupConfigID
		AND hours.VariabilityID = 2
		AND hours.FlexingTypeID = 7 -- Patient Activity
	  
	-- Return the data back so we can re-apply any percent adjustments and refresh the change history
	SELECT StaffingID, m.FiscalMonthID, cast(2 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID, CAST(51 AS TINYINT) AS UnitTypeID, f.Value
	FROM (
		SELECT bdgt.StaffingID, 
			   bdgt.TargetAdjustedHours01, bdgt.TargetAdjustedHours02, bdgt.TargetAdjustedHours03, bdgt.TargetAdjustedHours04, bdgt.TargetAdjustedHours05, bdgt.TargetAdjustedHours06, 
			   bdgt.TargetAdjustedHours07, bdgt.TargetAdjustedHours08, bdgt.TargetAdjustedHours09, bdgt.TargetAdjustedHours10, bdgt.TargetAdjustedHours11, bdgt.TargetAdjustedHours12
		FROM #basisIDs ids 
			 INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID
	) gl
	UNPIVOT ( Value FOR FiscalMonth IN (TargetAdjustedHours01, TargetAdjustedHours02, TargetAdjustedHours03, TargetAdjustedHours04, TargetAdjustedHours05, TargetAdjustedHours06, 
										TargetAdjustedHours07, TargetAdjustedHours08, TargetAdjustedHours09, TargetAdjustedHours10, TargetAdjustedHours11, TargetAdjustedHours12)) as f
	LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetAdjustedHours', 'Month')
	UNION ALL
	SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CAST(51 AS TINYINT) AS UnitTypeID, f.Value
	FROM (
		SELECT bdgt.StaffingID, 
			   bdgt.BudgetAdjustedHours01, bdgt.BudgetAdjustedHours02, bdgt.BudgetAdjustedHours03, bdgt.BudgetAdjustedHours04, bdgt.BudgetAdjustedHours05, bdgt.BudgetAdjustedHours06, 
			   bdgt.BudgetAdjustedHours07, bdgt.BudgetAdjustedHours08, bdgt.BudgetAdjustedHours09, bdgt.BudgetAdjustedHours10, bdgt.BudgetAdjustedHours11, bdgt.BudgetAdjustedHours12
		FROM #basisIDs ids 
			 INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID
	) gl
	UNPIVOT ( Value FOR FiscalMonth IN (BudgetAdjustedHours01, BudgetAdjustedHours02, BudgetAdjustedHours03, BudgetAdjustedHours04, BudgetAdjustedHours05, BudgetAdjustedHours06, 
										BudgetAdjustedHours07, BudgetAdjustedHours08, BudgetAdjustedHours09, BudgetAdjustedHours10, BudgetAdjustedHours11, BudgetAdjustedHours12)) as f
	LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjustedHours', 'Month');
GO


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

-- fp.procABBFlexRecalcHours_Initial
CREATE   PROC [fp].[procABBFlexRecalcHours_Initial]
    @EntityGroupConfigID INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	2022-07-13  MD      JAZZ-28981		Initial
	** 2	2023-10-31  MY      JAZZ-61705		Support PAF for the new data model - Staffing
	*************************************************************/
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs
	IF OBJECT_ID('tempdb..#flexDollars') IS NOT NULL DROP TABLE #flexDollars
	IF OBJECT_ID('tempdb..#origWageRate') IS NOT NULL DROP TABLE #origWageRate

	CREATE TABLE #basisIDs (StaffingID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		WHERE d.EntityGroupConfigID = @EntityGroupConfigID
			AND SubsectionID = 3
	   		AND FlexingTypeID = 7 -- Patient Activity
	END
	
	SELECT 
		base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		base.InitialBudgetDollars01, base.InitialBudgetDollars02, base.InitialBudgetDollars03, base.InitialBudgetDollars04, 
		base.InitialBudgetDollars05, base.InitialBudgetDollars06, base.InitialBudgetDollars07, base.InitialBudgetDollars08, 
		base.InitialBudgetDollars09, base.InitialBudgetDollars10, base.InitialBudgetDollars11, base.InitialBudgetDollars12
	INTO #flexDollars
	FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID	
	WHERE base.VariabilityID = 2
	    AND base.EntityGroupConfigID = @EntityGroupConfigID
		AND base.SubsectionID = 3

	SELECT 
		base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		wr.InitialBudget01, wr.InitialBudget02, wr.InitialBudget03, wr.InitialBudget04, 
		wr.InitialBudget05, wr.InitialBudget06, wr.InitialBudget07, wr.InitialBudget08, 
		wr.InitialBudget09, wr.InitialBudget10, wr.InitialBudget11, wr.InitialBudget12
	INTO #origWageRate
	FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID	
		 INNER JOIN [fp].[StaffingWageRate] wr ON wr.StaffingWageRateID = base.StaffingWageRateID	
	WHERE base.VariabilityID = 2
    	AND base.EntityGroupConfigID = @EntityGroupConfigID
		AND base.SubsectionID = 3

	UPDATE baseHours
	SET
		InitialBudgetHours01 = COALESCE(flexDollars.InitialBudgetDollars01 / NULLIF(origWageRate.InitialBudget01, 0), 0),
		InitialBudgetHours02 = COALESCE(flexDollars.InitialBudgetDollars02 / NULLIF(origWageRate.InitialBudget02, 0), 0),
		InitialBudgetHours03 = COALESCE(flexDollars.InitialBudgetDollars03 / NULLIF(origWageRate.InitialBudget03, 0), 0),
		InitialBudgetHours04 = COALESCE(flexDollars.InitialBudgetDollars04 / NULLIF(origWageRate.InitialBudget04, 0), 0),
		InitialBudgetHours05 = COALESCE(flexDollars.InitialBudgetDollars05 / NULLIF(origWageRate.InitialBudget05, 0), 0),
		InitialBudgetHours06 = COALESCE(flexDollars.InitialBudgetDollars06 / NULLIF(origWageRate.InitialBudget06, 0), 0),
		InitialBudgetHours07 = COALESCE(flexDollars.InitialBudgetDollars07 / NULLIF(origWageRate.InitialBudget07, 0), 0),
		InitialBudgetHours08 = COALESCE(flexDollars.InitialBudgetDollars08 / NULLIF(origWageRate.InitialBudget08, 0), 0),
		InitialBudgetHours09 = COALESCE(flexDollars.InitialBudgetDollars09 / NULLIF(origWageRate.InitialBudget09, 0), 0),
		InitialBudgetHours10 = COALESCE(flexDollars.InitialBudgetDollars10 / NULLIF(origWageRate.InitialBudget10, 0), 0),
		InitialBudgetHours11 = COALESCE(flexDollars.InitialBudgetDollars11 / NULLIF(origWageRate.InitialBudget11, 0), 0),
		InitialBudgetHours12 = COALESCE(flexDollars.InitialBudgetDollars12 / NULLIF(origWageRate.InitialBudget12, 0), 0)		
	OUTPUT 
	    INSERTED.StaffingID
	INTO
	    #basisIDs (StaffingID) 
	FROM [fp].[Staffing] baseHours
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = baseHours.DepartmentID	
	     LEFT JOIN #flexDollars flexDollars
	     	ON flexDollars.DepartmentID = baseHours.DepartmentID
	            AND flexDollars.EntityID = baseHours.EntityID
	            AND flexDollars.JobCodeID = baseHours.JobCodeID
	            AND flexDollars.PayCodeGroupID = baseHours.PayCodeGroupID
	            AND flexDollars.EntityGroupConfigID = baseHours.EntityGroupConfigID
	     LEFT JOIN #origWageRate origWageRate
	     	ON flexDollars.DepartmentID = origWageRate.DepartmentID
	            AND flexDollars.EntityID = origWageRate.EntityID
	            AND flexDollars.JobCodeID = origWageRate.JobCodeID
	            AND flexDollars.PayCodeGroupID = origWageRate.PayCodeGroupID
	            AND flexDollars.EntityGroupConfigID = origWageRate.EntityGroupConfigID
	WHERE baseHours.EntityGroupConfigID = @EntityGroupConfigID
	  AND baseHours.VariabilityID = 2
	  AND baseHours.FlexingTypeID = 7 -- Patient Activity
	  AND baseHours.SubsectionID = 3

	SELECT StaffingID as BasisID from #basisIDs
GO


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

-- fp.procABBFlexRecalcHours_Projection
/**************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI		        Description
**	1		07/22/22	MD		JAZZ-38981      Initial
**  2		2023-10-31  MY      JAZZ-61705		Support PAF for the new data model - Staffing
**	3		07/02/24	DM		JAZZ-72920		Removed dependency for PercentAdjustmentFactor
*************************************************************************************************************************/
CREATE     PROC [fp].[procABBFlexRecalcHours_Projection]
    @EntityGroupConfigID INT,
	@MonthsLoaded INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs
	IF OBJECT_ID('tempdb..#flexDollars') IS NOT NULL DROP TABLE #flexDollars
	IF OBJECT_ID('tempdb..#origWageRate') IS NOT NULL DROP TABLE #origWageRate

	CREATE TABLE #basisIDs (StaffingID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		where d.EntityGroupConfigID = @EntityGroupConfigID
	END
	
	SELECT 
		base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		base.ProjectionAdjustedDollars01, 
		base.ProjectionAdjustedDollars02, 
		base.ProjectionAdjustedDollars03, 
		base.ProjectionAdjustedDollars04, 
		base.ProjectionAdjustedDollars05, 
		base.ProjectionAdjustedDollars06, 
		base.ProjectionAdjustedDollars07, 
		base.ProjectionAdjustedDollars08, 
		base.ProjectionAdjustedDollars09, 
		base.ProjectionAdjustedDollars10,
		base.ProjectionAdjustedDollars11, 
		base.ProjectionAdjustedDollars12
	INTO #flexDollars
	FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID	
	WHERE base.VariabilityID = 2
	    AND base.EntityGroupConfigID = @EntityGroupConfigID
		
	SELECT 
		base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, 
		wr.ProjectionAdjusted01, wr.ProjectionAdjusted02, wr.ProjectionAdjusted03, wr.ProjectionAdjusted04, 
		wr.ProjectionAdjusted05, wr.ProjectionAdjusted06, wr.ProjectionAdjusted07, wr.ProjectionAdjusted08, 
		wr.ProjectionAdjusted09, wr.ProjectionAdjusted10, wr.ProjectionAdjusted11, wr.ProjectionAdjusted12
	INTO #origWageRate
    FROM [fp].[Staffing] base
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID	
    	INNER JOIN [fp].[StaffingWageRate] wr ON base.StaffingWageRateID = wr.StaffingWageRateID
    WHERE base.EntityGroupConfigID = @EntityGroupConfigID
		AND base.VariabilityID = 2

	UPDATE hours
	SET
		hours.ProjectionAdjustedHours01 = CASE WHEN @MonthsLoaded < 1  THEN COALESCE(flexDollars.ProjectionAdjustedDollars01 / NULLIF(origWageRate.ProjectionAdjusted01, 0), 0) ELSE hours.ProjectionAdjustedHours01 END,
		hours.ProjectionAdjustedHours02 = CASE WHEN @MonthsLoaded < 2  THEN COALESCE(flexDollars.ProjectionAdjustedDollars02 / NULLIF(origWageRate.ProjectionAdjusted02, 0), 0) ELSE hours.ProjectionAdjustedHours02 END,
		hours.ProjectionAdjustedHours03 = CASE WHEN @MonthsLoaded < 3  THEN COALESCE(flexDollars.ProjectionAdjustedDollars03 / NULLIF(origWageRate.ProjectionAdjusted03, 0), 0) ELSE hours.ProjectionAdjustedHours03 END,
		hours.ProjectionAdjustedHours04 = CASE WHEN @MonthsLoaded < 4  THEN COALESCE(flexDollars.ProjectionAdjustedDollars04 / NULLIF(origWageRate.ProjectionAdjusted04, 0), 0) ELSE hours.ProjectionAdjustedHours04 END,
		hours.ProjectionAdjustedHours05 = CASE WHEN @MonthsLoaded < 5  THEN COALESCE(flexDollars.ProjectionAdjustedDollars05 / NULLIF(origWageRate.ProjectionAdjusted05, 0), 0) ELSE hours.ProjectionAdjustedHours05 END,
		hours.ProjectionAdjustedHours06 = CASE WHEN @MonthsLoaded < 6  THEN COALESCE(flexDollars.ProjectionAdjustedDollars06 / NULLIF(origWageRate.ProjectionAdjusted06, 0), 0) ELSE hours.ProjectionAdjustedHours06 END,
		hours.ProjectionAdjustedHours07 = CASE WHEN @MonthsLoaded < 7  THEN COALESCE(flexDollars.ProjectionAdjustedDollars07 / NULLIF(origWageRate.ProjectionAdjusted07, 0), 0) ELSE hours.ProjectionAdjustedHours07 END,
		hours.ProjectionAdjustedHours08 = CASE WHEN @MonthsLoaded < 8  THEN COALESCE(flexDollars.ProjectionAdjustedDollars08 / NULLIF(origWageRate.ProjectionAdjusted08, 0), 0) ELSE hours.ProjectionAdjustedHours08 END,
		hours.ProjectionAdjustedHours09 = CASE WHEN @MonthsLoaded < 9  THEN COALESCE(flexDollars.ProjectionAdjustedDollars09 / NULLIF(origWageRate.ProjectionAdjusted09, 0), 0) ELSE hours.ProjectionAdjustedHours09 END,
		hours.ProjectionAdjustedHours10 = CASE WHEN @MonthsLoaded < 10 THEN COALESCE(flexDollars.ProjectionAdjustedDollars10 / NULLIF(origWageRate.ProjectionAdjusted10, 0), 0) ELSE hours.ProjectionAdjustedHours10 END,
		hours.ProjectionAdjustedHours11 = CASE WHEN @MonthsLoaded < 11 THEN COALESCE(flexDollars.ProjectionAdjustedDollars11 / NULLIF(origWageRate.ProjectionAdjusted11, 0), 0) ELSE hours.ProjectionAdjustedHours11 END,
		hours.ProjectionAdjustedHours12 = CASE WHEN @MonthsLoaded < 12 THEN COALESCE(flexDollars.ProjectionAdjustedDollars12 / NULLIF(origWageRate.ProjectionAdjusted12, 0), 0) ELSE hours.ProjectionAdjustedHours12 END
	OUTPUT 
	    INSERTED.StaffingID
	INTO
	    #basisIDs (StaffingID) 
	FROM [fp].[Staffing] hours
		 INNER JOIN #FilterByDepartment s ON s.DepartmentID = hours.DepartmentID	
	     LEFT JOIN #flexDollars flexDollars
	     	ON flexDollars.DepartmentID = hours.DepartmentID
	            AND flexDollars.EntityID = hours.EntityID
	            AND flexDollars.JobCodeID = hours.JobCodeID
	            AND flexDollars.PayCodeGroupID = hours.PayCodeGroupID
	            AND flexDollars.EntityGroupConfigID = hours.EntityGroupConfigID
	     LEFT JOIN #origWageRate origWageRate
	     	ON flexDollars.DepartmentID = origWageRate.DepartmentID
	            AND flexDollars.EntityID = origWageRate.EntityID
	            AND flexDollars.JobCodeID = origWageRate.JobCodeID
	            AND flexDollars.PayCodeGroupID = origWageRate.PayCodeGroupID
	            AND flexDollars.EntityGroupConfigID = origWageRate.EntityGroupConfigID
	WHERE hours.EntityGroupConfigID = @EntityGroupConfigID
	  AND hours.VariabilityID = 2
	  AND hours.FlexingTypeID = 7 -- Patient Activity
	  
	-- Return the data back so we can re-apply any percent adjustments and refresh the change history
	SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(12 AS TINYINT) AS TimeClassID, CAST(51 AS TINYINT) AS UnitTypeID, f.Value
	FROM (
		SELECT 
			proj.StaffingID,
			proj.ProjectionAdjustedHours01, proj.ProjectionAdjustedHours02, proj.ProjectionAdjustedHours03, proj.ProjectionAdjustedHours04, 
			proj.ProjectionAdjustedHours05, proj.ProjectionAdjustedHours06, proj.ProjectionAdjustedHours07, proj.ProjectionAdjustedHours08, 
			proj.ProjectionAdjustedHours09, proj.ProjectionAdjustedHours10, proj.ProjectionAdjustedHours11, proj.ProjectionAdjustedHours12
		FROM #basisIDs ids 
			 INNER JOIN [fp].[Staffing] proj ON ids.StaffingID = proj.StaffingID 
	) gl
	UNPIVOT ( Value FOR FiscalMonth IN (ProjectionAdjustedHours01, ProjectionAdjustedHours02, ProjectionAdjustedHours03, ProjectionAdjustedHours04, ProjectionAdjustedHours05, ProjectionAdjustedHours06, ProjectionAdjustedHours07, ProjectionAdjustedHours08, ProjectionAdjustedHours09, ProjectionAdjustedHours10, ProjectionAdjustedHours11, ProjectionAdjustedHours12)) as f
	LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjustedHours', 'Month');
GO


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

-- fp.procABBMRFlexPostActions
CREATE PROCEDURE fp.procABBMRFlexPostActions  
	@MRYear int
AS
BEGIN
	PRINT 'Running for FY' + CAST(@MRYear AS VARCHAR(1000))
END
GO


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

-- fp.procAPEngineTaskPreProcessingActions
CREATE PROCEDURE fp.procAPEngineTaskPreProcessingActions
 AS
 BEGIN
	
	SET NOCOUNT ON;			
		
	/******************* PLEASE READ BEFORE UPDATING THIS PROC ******************
	
		When adding to the proc, please do the following:
		  - Create a defect
		  - Create a migration updating this proc with the workaround
		  		- When updating this migration, include the defect number and breif summary	
		  		
	****************************************************************************/
		
	
 END
GO


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

-- fp.procAPIncomeStatementReportTurnOnFTECalculations
create proc [fp].[procAPIncomeStatementReportTurnOnFTECalculations]
as
BEGIN
	if ((select VALUE from [fp].[SystemSetting] WHERE Name = 'Is APE Enabled') = 1) 
	begin
		update frlineitem 
		SET Calculation = '['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 589  and Statement = 'Stats') --Productive Hours
							+ ']/['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours
							+ ']',
			Type = 2
		WHERE FinancialReportingID = 591 and Statement = 'Stats'  -- Stats - FTEs - Productive FTEs

		update frlineitem 
		SET Calculation = '['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 590 and Statement = 'Stats') -- Stats- Hours
							+ ']/['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours
							+ ']',
			Type = 2

		WHERE FinancialReportingID = 592 and Statement = 'Stats' -- Stats - FTEs - Non-Productive FTEs

		update frlineitem 
		SET Calculation = '['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 2591 and Statement = 'Stats') -- Stats - Hours - GL Physician Hours
							+ ']/['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours
							+ ']',
			Type = 2
		WHERE FinancialReportingID = 1 and Statement = 'Stats' --Physician FTEs


		update frlineitem 
		SET Calculation = '['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 2590 and Statement = 'Stats') -- Stats - GL Hours
							+ ']/['
							+ (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours
							+ ']',
			Type = 2
		WHERE FinancialReportingID = 2  and Statement = 'Stats'--Non-Physician Provider FTEs
	end
	ELSE 
		begin
		update frlineitem 
		SET Calculation = '',
			Type = 0
		WHERE FinancialReportingID = 592  and Statement = 'Stats'-- Stats - FTEs - Non-Productive FTEs

		update frlineitem 
		SET Calculation = '',
			Type = 0
		WHERE FinancialReportingID = 591  and Statement = 'Stats' -- Stats - FTEs - Productive FTEs

		update frlineitem 
		SET Calculation = '',
			Type = 0
		WHERE FinancialReportingID = 1  and Statement = 'Stats'--Physician FTEs


		update frlineitem 
		SET Calculation = '',
			Type = 0
		WHERE FinancialReportingID = 2  and Statement = 'Stats'--Non-Physician Provider FTEs
	end
END
GO


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

-- fp.procAPTempTableCleanupTask
CREATE PROCEDURE [fp].[procAPTempTableCleanupTask]   
AS
BEGIN

DECLARE @MyCursor CURSOR;
DECLARE @Name NVARCHAR(MAX);
BEGIN
    SET @MyCursor = CURSOR FOR
    SELECT CONCAT( 'DROP TABLE ','[tmp].[', name, ']') AS TempName FROM sys.tables
    WHERE (name LIKE 'Staffing[_]%' OR name LIKE 'GeneralLedger[_]%')
	AND SCHEMA_ID = SCHEMA_ID('tmp')
	AND create_date <= GETDATE() - 1      

    OPEN @MyCursor 
    FETCH NEXT FROM @MyCursor 
    INTO @Name

    WHILE @@FETCH_STATUS = 0
    BEGIN
	
	
      EXECUTE sp_executesql @Name;
	  
      FETCH NEXT FROM @MyCursor 
      INTO @Name 
    END; 

    CLOSE @MyCursor;
    DEALLOCATE @MyCursor;
END;
END;
GO


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

-- fp.procAddCategoryForSetting
CREATE   PROCEDURE [fp].[procAddCategoryForSetting] 
	@CategoryName NVARCHAR(100),
	@SettingName NVARCHAR(100)
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI            Description
	** 1    10-18-2022   MY        Felt Like it  Initial Creation
	*************************************************************/

	DECLARE @CategoryID INT = (SELECT CategoryID FROM fp.DimCategory WHERE Category = @CategoryName)
	
	DECLARE @SystemSettingID INT = (SELECT SystemSettingID FROM fp.SystemSetting WHERE Name = @SettingName)
	IF @SystemSettingID IS NOT NULL AND NOT EXISTS (SELECT 1 FROM [fp].[SettingCategory] WHERE SystemSettingID = @SystemSettingID AND CategoryID = @CategoryID)
	BEGIN
		INSERT INTO fp.SettingCategory (CategoryID, SystemSettingID) VALUES (@CategoryID, @SystemSettingID)
	END
		
	SET @SystemSettingID = (SELECT SettingID FROM fp.BudgetConfigDefaultSetting WHERE Name = @SettingName)	
	IF @SystemSettingID IS NOT NULL AND NOT EXISTS (SELECT 1 FROM [fp].[SettingCategory] WHERE BudgetConfigDefaultSettingID = @SystemSettingID AND CategoryID = @CategoryID)
	BEGIN
		INSERT INTO fp.SettingCategory (CategoryID, BudgetConfigDefaultSettingID) VALUES (@CategoryID, @SystemSettingID)
	END
	
END
GO


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

-- fp.procAddRosterEmployee
/*************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI			Description
** 1		11/13/17	MY		B-17923		Creates a Dummy Proc for Roster Changes
*************************************************************************************************************************/
CREATE PROCEDURE fp.procAddRosterEmployee
	@DepartmentID INT,
	@JobCodeID INT,
	@FTE DECIMAL(19,4),
	@Salary DECIMAL(19,4),
	@FiscalMonthID INT,
	@FiscalYearID INT,
	@Comment NVARCHAR(MAX)
AS
BEGIN
	-- Enter Any Logic that is needed for after saving a Roster Adjustment
	PRINT ''
END
GO


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

-- fp.procAdjustmentImpactBatchCalculation
CREATE   PROCEDURE [fp].[procAdjustmentImpactBatchCalculation] 
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    08-17-2022   MY        JAZZ-41983  Initial Creation
	** 2    03-20-2023   MY        JAZZ-52181  New Structure
	*************************************************************/

	DECLARE @BudgetConfigID INT = (SELECT TOP 1 BudgetConfigID FROM fp.BudgetConfig WHERE IsActive = 1); -- Only the active config is used for these reports
	DECLARE @RowLimit INT = ISNULL((SELECT Value FROM fp.SystemSetting WHERE Name = 'Row Limit for Adjustment Impact Report Batch'), 5000000);

	IF OBJECT_ID('tempdb..#mappingsByRowCount') IS NOT NULL DROP TABLE #mappingsByRowCount;
	IF OBJECT_ID('tempdb..#currentBatch') IS NOT NULL DROP TABLE #currentBatch;

	SELECT EntityID, PatientClassID, MedicalSurgicalID, SUM(TotalRowCount) AS TotalRowCount
	INTO #mappingsByRowCount
	FROM (
		SELECT fcv.ServiceEntityID AS EntityID, fcv.PatientClassID, fcv.MedicalSurgicalID, COUNT(*) AS TotalRowCount
		FROM fp.ChargeVolume fcv
		WHERE BudgetConfigID = @BudgetConfigID
		GROUP BY fcv.ServiceEntityID, fcv.PatientClassID, fcv.MedicalSurgicalID
		UNION ALL
		SELECT sle.EntityID, sle.PatientClassID, sle.MedicalSurgicalID, COUNT(*) AS TotalRowCount
		FROM fp.ServiceLineEncounter sle
		WHERE BudgetConfigID = @BudgetConfigID
		GROUP BY sle.EntityID, sle.PatientClassID, sle.MedicalSurgicalID
	) dimensionality
	GROUP BY EntityID, PatientClassID, MedicalSurgicalID

	CREATE TABLE #currentBatch (
		EntityID INT NOT NULL DEFAULT(0),
		PatientClassID INT NOT NULL DEFAULT(0),
		MedicalSurgicalID INT NOT NULL DEFAULT(0),
		TotalRowCount INT NOT NULL DEFAULT(0)
	)

	TRUNCATE TABLE [fp].[AdjustmentImpactReportBatchConfiguration];

	-- Yes it's cursor, I know it's bad, but I don't know how else to do it in SQL other than bringing it in code and doing it there, but
	-- that seems silly just to avoid a cursor. This proc should only be run a handeful of times at best. Once initially and then anytime the batching
	-- may need to be re-calc'd
	DECLARE 
		@EntityID INT, 
		@PatientClassID INT,
		@MedicalSurgicalID INT,
		@RowCount INT,
		@BatchNumber INT = 1,
		@CurrentBatchRowCount INT = 0;

	DECLARE cursor_batches CURSOR
	FOR SELECT EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount FROM #mappingsByRowCount ORDER BY TotalRowCount;

	OPEN cursor_batches;
	FETCH NEXT FROM cursor_batches INTO 
		@EntityID, 
		@PatientClassID,
		@MedicalSurgicalID,
		@RowCount;

	WHILE @@FETCH_STATUS = 0
	BEGIN
	   
		IF (@CurrentBatchRowCount = 0)
		BEGIN

			-- Add current batch to existing batch
			INSERT INTO #currentBatch (EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount)
			SELECT @EntityID, @PatientClassID, @MedicalSurgicalID, @RowCount
	
			SET @CurrentBatchRowCount = @CurrentBatchRowCount + @RowCount;

		END ELSE BEGIN

			-- Need to cut off the current batch and start a new one
			IF (@CurrentBatchRowCount > @RowLimit OR @CurrentBatchRowCount + @RowCount > @RowLimit)
			BEGIN
				INSERT INTO [fp].[AdjustmentImpactReportBatchConfiguration] (BatchID, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount)
				SELECT @BatchNumber, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount
				FROM #currentBatch

				TRUNCATE TABLE #currentBatch;
				SET @BatchNumber = @BatchNumber + 1;
				SET @CurrentBatchRowCount = 0;
			END
	
			-- Add current batch to existing batch
			INSERT INTO #currentBatch (EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount)
			SELECT @EntityID, @PatientClassID, @MedicalSurgicalID, @RowCount
	
			SET @CurrentBatchRowCount = @CurrentBatchRowCount + @RowCount;

		END

		FETCH NEXT FROM cursor_batches INTO 
			@EntityID, 
			@PatientClassID,
			@MedicalSurgicalID,
			@RowCount;
	END;

	CLOSE cursor_batches;
	DEALLOCATE cursor_batches;

	INSERT INTO [fp].[AdjustmentImpactReportBatchConfiguration] (BatchID, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount)
	SELECT @BatchNumber, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount
	FROM #currentBatch

END
GO


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

-- fp.procApplyVariabilityToStaffing
/**************************************************************
** Change History 
**************************************************************
** CID  Date		Author	WI			Description
** 1	2018-10-04	IP		B-20922	    Added using source dimensionality
** 2	2018-11-06	NL		B-21035	    Adding spreading (and renaming proc)
** 3	2018-12-12	NL		D-07904	    Removing FTEs from the Fix/Var apply, recalc after instead
** 4	2019-01-09	IP		B-21757	    Change Initial Projection Calculation - remaining testing and bugs fixing
** 5	2019-02-06	BK		B-21763     Exclude designated productive classes from FTE calculation
** 6	2019-06-13	BK		D-08548     Modify to use hours instead of days in year and exclude Dollars-Only hours
** 7	2019-08-12	BK		D-08697     Performance enhancements
** 8	2019-08-13	MY		X-XXXXX     Update FTE calculation to calculate average, not / 12
** 9	2019-08-19	BK		B-24026     Performance enhancements
** 10	2019-10-21	BK		X-XXXXX     Fix issue when fiscal year <> projection year
** 11	2019-11-12	MY		B-24221     Remove feature flag for wage rate stuff
** 12	2020-07-08	BK		JAZZ-1796   Fix leap year average
** 13	2020-07-20	BK		JAZZ-2117   Add Employee joins for EB
** 14	2020-08-05  LR      JAZZ-1226	Added clean up for variable hours and FTEs with Fixed override
** 15	2020-11-02	BK		JAZZ-8379   Add support for provider fields and update filtering logic
** 16   2021-02-17  MD		JAZZ-14996  Added missing EmployeeID join on FTE update
** 17   2021-02-17  LR		JAZZ-9006   Added missing variability IDs to UPDATE statement
** 18   2021-08-16  BK		JAZZ-21272  Use cached variability table for cleaning up variable records
** 19 	2022-04-29  MY		JAZZ-28395  Cache Variability Percentage on FactStaffing
** 20	2022-10-04  MY		JAZZ-37262  Remove Feature Flag 'Use Variability From FactStaffing Table'
** 21	2022-11-07  MY      JAZZ-35951	Add EmployeeID to FactStaffingVariabilityDetail
** 22	2023-09-20  BK      JAZZ-60973	Update for data restructure
** 23	2024-01-24  MY      JAZZ-65733	Fix issue where the data wasn't getting rolled up above variability causing the data to not be re-split
** 24	2024-01-31  NH      JAZZ-64064	Move Provider Planning FF as a setting in Plan Config
** 25	2024-02-08  MD      JAZZ-66903	Add code changes from JAZZ-66611 - Fix projection months loaded being recalculated. Do not overwrite values
** 26	2024-02-20  BW      JAZZ-66903	fix for provider InitialRate for variable is zeroed out
** 27	2024-06-14  SM      JAZZ-71536  change JobCodeID from smallint to int
*************************************************************/
CREATE   PROCEDURE [fp].[procApplyVariabilityToStaffing]
	 @EntityGroupConfigID INT,
	 @FiscalYearID INT,
	 @MonthsLoaded INT,
	 @ProjectionFiscalYearID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
	 WITH RECOMPILE
 AS
 BEGIN
 
	SET NOCOUNT ON 
 
 	IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable
	IF OBJECT_ID('tempdb..#BudgetWorkingHours') IS NOT NULL DROP TABLE #BudgetWorkingHours
	IF OBJECT_ID('tempdb..#preSpreadFixedVar') IS NOT NULL DROP TABLE #preSpreadFixedVar
	IF OBJECT_ID('tempdb..#preSpreadFixedVarDollars') IS NOT NULL DROP TABLE #preSpreadFixedVarDollars
	IF OBJECT_ID('tempdb..#spreadFixedVar') IS NOT NULL DROP TABLE #spreadFixedVar
	IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals
	IF OBJECT_ID('tempdb..#fteTemp') IS NOT NULL DROP TABLE #fteTemp
	IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp
	IF OBJECT_ID('tempdb..#MonthsLoadedTotal') IS NOT NULL DROP TABLE #MonthsLoadedTotal
	IF OBJECT_ID('tempdb..#ProjectionWorkingHours') IS NOT NULL DROP TABLE #ProjectionWorkingHours
	IF OBJECT_ID('tempdb..#ProjectionYTD') IS NOT NULL DROP TABLE #ProjectionYTD
	IF OBJECT_ID('tempdb..#HoursAndWorkingHours') IS NOT NULL DROP TABLE #HoursAndWorkingHours
	IF OBJECT_ID('tempdb..#DollarTotals') IS NOT NULL DROP TABLE #DollarTotals
	IF OBJECT_ID('tempdb..#HoursForFteUpdate') IS NOT NULL DROP TABLE #HoursForFteUpdate
	IF OBJECT_ID('tempdb..#Variability') IS NOT NULL DROP TABLE #Variability
	IF OBJECT_ID('tempdb..#variableStaffingRecordsToCleanUp') IS NOT NULL DROP TABLE #variableStaffingRecordsToCleanUp
	IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability
	IF OBJECT_ID('tempdb..#combinedStaffingDollarsAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingDollarsAboveVariability
	
	CREATE TABLE #FilteringTable (
		DepartmentID INT
		,INDEX ix_1 NONCLUSTERED (DepartmentID)
		)

	INSERT INTO #FilteringTable (DepartmentID)
	SELECT DepartmentID
	FROM @SourceDimensionality

	DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER;
	SET @EntityGroupConfigGUID = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID)
	
	DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable)

	IF (@isFilterPresent=0) BEGIN
		INSERT INTO #FilteringTable (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	
	
	DECLARE @IsProviderPlanningEnabled BIT
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled 
	FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID 
	WHERE EntityGroupConfigID = @EntityGroupConfigID;	
		
	DECLARE @ProviderSubsectionID INT = 4;
	DECLARE @StaffingSubsectionID INT = 3;   
			
	DECLARE @SourceFiscalYearID int
	DECLARE @SourceTimeClassID int
	SELECT @SourceTimeClassID = PayrollTimeClassID, @SourceFiscalYearID = PayrollFiscalYearID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID
	DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @ProjectionFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)
	
	CREATE TABLE #Variability (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6))
	
	INSERT INTO #Variability (DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage)
	SELECT v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage
	FROM [fp].[viewFactStaffingVariability] v
		INNER JOIN #FilteringTable f ON v.DepartmentID = f.DepartmentID
	WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
	GROUP BY v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID

	-- Pre spread values. Basically we need the fixed/variable split before we spread it evenly
	CREATE TABLE #preSpreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT,
						ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
						InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8),
						InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8),
						InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8),
						InitialBudgetTotal DECIMAL(19,8),
						InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8),
						InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8),
						InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8),
						InitialProjectionTotal DECIMAL(19,8),
						INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID)
						)
	  -- we need this for projection dollars months loaded to be allocated to fixed/variable properly for when no hours exist but dollars do (jazz-66611)
	CREATE TABLE #preSpreadFixedVarDollars ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT,
						ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, 
						InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8),
						InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8),
						InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8)
						INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID)
						)

      CREATE TABLE #spreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT,
							ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
							InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8),
							InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8),
							InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8),
							InitialBudgetTotal DECIMAL(19,8),
							InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8),
							InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8),
							InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8),
							InitialProjectionTotal DECIMAL(19,8),
							INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID)
							)
	
	-- We need to find the totals above Variability so we can resplit the data.
	SELECT
		fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        SUM(fs.SampledBudgetHours01) AS SampledBudgetHours01,
        SUM(fs.SampledBudgetHours02) AS SampledBudgetHours02,
        SUM(fs.SampledBudgetHours03) AS SampledBudgetHours03,
        SUM(fs.SampledBudgetHours04) AS SampledBudgetHours04,
        SUM(fs.SampledBudgetHours05) AS SampledBudgetHours05,
        SUM(fs.SampledBudgetHours06) AS SampledBudgetHours06,
        SUM(fs.SampledBudgetHours07) AS SampledBudgetHours07,
        SUM(fs.SampledBudgetHours08) AS SampledBudgetHours08,
        SUM(fs.SampledBudgetHours09) AS SampledBudgetHours09,
        SUM(fs.SampledBudgetHours10) AS SampledBudgetHours10,
        SUM(fs.SampledBudgetHours11) AS SampledBudgetHours11,
        SUM(fs.SampledBudgetHours12) AS SampledBudgetHours12,	
        SUM(fs.SampledBudgetHoursTotal) AS SampledBudgetHoursTotal,
	    SUM(fs.SampledProjectionHours01) AS SampledProjectionHours01,	
        SUM(fs.SampledProjectionHours02) AS SampledProjectionHours02,
        SUM(fs.SampledProjectionHours03) AS SampledProjectionHours03,
        SUM(fs.SampledProjectionHours04) AS SampledProjectionHours04,
        SUM(fs.SampledProjectionHours05) AS SampledProjectionHours05,
        SUM(fs.SampledProjectionHours06) AS SampledProjectionHours06,
        SUM(fs.SampledProjectionHours07) AS SampledProjectionHours07,
        SUM(fs.SampledProjectionHours08) AS SampledProjectionHours08,
        SUM(fs.SampledProjectionHours09) AS SampledProjectionHours09,
        SUM(fs.SampledProjectionHours10) AS SampledProjectionHours10,
        SUM(fs.SampledProjectionHours11) AS SampledProjectionHours11,
        SUM(fs.SampledProjectionHours12) AS SampledProjectionHours12
	INTO #combinedStaffingHoursAboveVariability
    FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID )        
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID

		-- We need to find the totals above Variability so we can resplit the data.
	SELECT
		fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        SUM(fs.SampledBudgetDollars01) AS SampledBudgetDollars01,
        SUM(fs.SampledBudgetDollars02) AS SampledBudgetDollars02,
        SUM(fs.SampledBudgetDollars03) AS SampledBudgetDollars03,
        SUM(fs.SampledBudgetDollars04) AS SampledBudgetDollars04,
        SUM(fs.SampledBudgetDollars05) AS SampledBudgetDollars05,
        SUM(fs.SampledBudgetDollars06) AS SampledBudgetDollars06,
        SUM(fs.SampledBudgetDollars07) AS SampledBudgetDollars07,
        SUM(fs.SampledBudgetDollars08) AS SampledBudgetDollars08,
        SUM(fs.SampledBudgetDollars09) AS SampledBudgetDollars09,
        SUM(fs.SampledBudgetDollars10) AS SampledBudgetDollars10,
        SUM(fs.SampledBudgetDollars11) AS SampledBudgetDollars11,
        SUM(fs.SampledBudgetDollars12) AS SampledBudgetDollars12,	
        SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal,
	    SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01,	
        SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02,
        SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03,
        SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04,
        SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05,
        SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06,
        SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07,
        SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08,
        SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09,
        SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10,
        SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11,
        SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12
	INTO #combinedStaffingDollarsAboveVariability
    FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID )        
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID
		
	INSERT INTO #preSpreadFixedVar (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,
							InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,	InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,	InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, InitialBudgetTotal,
							InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours01) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours01) END as InitialBudgetHours01,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours02) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours02) END as InitialBudgetHours02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours03) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours03) END as InitialBudgetHours03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours04) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours04) END as InitialBudgetHours04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours05) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours05) END as InitialBudgetHours05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours06) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours06) END as InitialBudgetHours06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours07) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours07) END as InitialBudgetHours07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours08) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours08) END as InitialBudgetHours08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours09) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours09) END as InitialBudgetHours09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours10) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours10) END as InitialBudgetHours10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours11) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours11) END as InitialBudgetHours11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours12) END as InitialBudgetHours12,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHoursTotal) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHoursTotal) END as InitialBudgetHoursTotal,        
	    CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours01 END SampledProjectionHours01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours02 END SampledProjectionHours02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours03 END SampledProjectionHours03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours04 END SampledProjectionHours04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours05 END SampledProjectionHours05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours06 END SampledProjectionHours06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours07 END SampledProjectionHours07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours08 END SampledProjectionHours08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours09 END SampledProjectionHours09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours10 END SampledProjectionHours10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours11 END SampledProjectionHours11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours12 END SampledProjectionHours12
     FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
		INNER JOIN #combinedStaffingHoursAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID      
        LEFT JOIN #Variability fv 
            ON fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.ProviderLineItemID = fs.ProviderLineItemID
			AND fv.EmployeeID = fs.EmployeeID
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider

	INSERT INTO #preSpreadFixedVarDollars (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,							
							InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12
     FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
		INNER JOIN #combinedStaffingDollarsAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID      
        LEFT JOIN #Variability fv 
            ON fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.ProviderLineItemID = fs.ProviderLineItemID
			AND fv.EmployeeID = fs.EmployeeID
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider

	-- We no longer need this after splitting out the hours
	IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability
	
	INSERT INTO #spreadFixedVar (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,
		InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,	InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,	InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
		InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,
		InitialBudget01 / 12, 
		InitialBudget02 / 12, 
		InitialBudget03 / 12, 
		InitialBudget04 / 12,	
		InitialBudget05 / 12, 
		InitialBudget06 / 12, 
		InitialBudget07 / 12, 
		InitialBudget08 / 12,	
		InitialBudget09 / 12, 
		InitialBudget10 / 12, 
		InitialBudget11 / 12, 
		InitialBudgetTotal = InitialBudgetTotal - (InitialBudget01 / 12 + InitialBudget02 / 12 + InitialBudget03 / 12 + InitialBudget04 / 12 + InitialBudget05 / 12 + InitialBudget06 / 12 + 
			InitialBudget07 / 12 + InitialBudget08 / 12 + InitialBudget09 / 12 + InitialBudget10 / 12 + InitialBudget11 / 12),
		InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12
	FROM #preSpreadFixedVar				
	
	UPDATE a 
	SET 
		InitialBudgetTotal =  InitialBudget01 + InitialBudget02 + InitialBudget03 + InitialBudget04 + InitialBudget05 + InitialBudget06 + InitialBudget07 + InitialBudget08 + InitialBudget09 + InitialBudget10 + InitialBudget11 + InitialBudget12,
		InitialProjectionTotal = InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10 + InitialProjection11 + InitialProjection12
	FROM #spreadFixedVar a				
	
	SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID,
							Month01, Month02, Month03, Month04,
							Month05, Month06, Month07, Month08,
							Month09, Month10, Month11, Month12, MonthYearly   -- Jazz-1796
	INTO #BudgetWorkingHours									
	FROM [fp].[Staffing] fs
		  INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID 
		  INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
          INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID
          INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)
        WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID)  -- exclude provider
		

	SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, 
							pwh.Month01, pwh.Month02, pwh.Month03, pwh.Month04,
							pwh.Month05, pwh.Month06, pwh.Month07, pwh.Month08,
							pwh.Month09, pwh.Month10, pwh.Month11, pwh.Month12, pwh.MonthYearly  -- Jazz-1796
	INTO #ProjectionWorkingHours									
	FROM #BudgetWorkingHours fs				
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
        INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID
        INNER JOIN [client].[FactWorkingHoursPerMonth] pwh on pwh.FiscalYearID = @ProjectionFiscalYearID and pwh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)
	
	
	SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, ytd.YTDHours
	INTO #ProjectionYTD
	FROM #ProjectionWorkingHours fs
	   INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
       INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID
       INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @ProjectionFiscalYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) 
	   INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID
	
	CREATE TABLE #HoursAndWorkingHours ( StaffingID INT, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, EntityGroupConfigID INT, VariabilityID INT,
							ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
							InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8),
							InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8),
							InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8),
							InitialBudgetTotal DECIMAL(19,8),
							Month01 DECIMAL(19,8), Month02 DECIMAL(19,8), Month03 DECIMAL(19,8), Month04 DECIMAL(19,8),
							Month05 DECIMAL(19,8), Month06 DECIMAL(19,8), Month07 DECIMAL(19,8), Month08 DECIMAL(19,8),
							Month09 DECIMAL(19,8), Month10 DECIMAL(19,8), Month11 DECIMAL(19,8), Month12 DECIMAL(19,8), TotalWorkingHours DECIMAL(19,8),  -- Jazz-1796
							INDEX ix_sfv_1 NONCLUSTERED (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID)
							)

    INSERT INTO #HoursAndWorkingHours (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, EntityGroupConfigID, VariabilityID,
							ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,  
							InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,
							InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,
							InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
							InitialBudgetTotal,
							Month01, Month02, Month03, Month04,
							Month05, Month06, Month07, Month08,
							Month09, Month10, Month11, Month12, TotalWorkingHours)
	SELECT h.StaffingID, h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.EntityGroupConfigID, h.VariabilityID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.SubsectionID,
		h.InitialBudget01, h.InitialBudget02, h.InitialBudget03, h.InitialBudget04, h.InitialBudget05, h.InitialBudget06, h.InitialBudget07, h.InitialBudget08, h.InitialBudget09, h.InitialBudget10, h.InitialBudget11 , h.InitialBudget12,
		h.InitialBudgetTotal,
		wh.Month01, wh.Month02, wh.Month03, wh.Month04, wh.Month05, wh.Month06, wh.Month07, wh.Month08, wh.Month09, wh.Month10, wh.Month11 , wh.Month12, wh.MonthYearly  -- Jazz-1796
	FROM #preSpreadFixedVar h -- We need the pre-spread here because we'll use the YTD hours later
    	LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID 
        INNER JOIN #BudgetWorkingHours wh on h.StaffingID = wh.StaffingID
    WHERE  h.EntityGroupConfigID = @EntityGroupConfigID AND (h.VariabilityID = 1 OR exc.PayCodeGroupID IS NOT NULL)

	CREATE TABLE #flatFteTemp (StaffingID INT, AverageFTE DECIMAL(19,8))	
	
  	-- budget  ------------------------------------------------------------------------------------------------
	-- spread hours so that FTEs remain flat for fixed job codes
	-- figure out ftes...
	
	INSERT INTO #flatFteTemp 
		SELECT h.StaffingID, 
			    (h.InitialBudget01 / h.TotalWorkingHours) +
		        (h.InitialBudget02 / h.TotalWorkingHours) +
		        (h.InitialBudget03 / h.TotalWorkingHours) +
		        (h.InitialBudget04 / h.TotalWorkingHours) +
		        (h.InitialBudget05 / h.TotalWorkingHours) +
		        (h.InitialBudget06 / h.TotalWorkingHours) +
		        (h.InitialBudget07 / h.TotalWorkingHours) +
		        (h.InitialBudget08 / h.TotalWorkingHours) +
		       (h.InitialBudget09 / h.TotalWorkingHours) +
		        (h.InitialBudget10 / h.TotalWorkingHours) +
		        (h.InitialBudget11 / h.TotalWorkingHours) +
		        (h.InitialBudget12 / h.TotalWorkingHours)  AS AverageFTE  --Use a weighted average, not a straight average
	FROM #HoursAndWorkingHours h 						
		
	
	-- now back into hours
	UPDATE
		fs
	SET
		InitialBudgetHours01 = AverageFTE * wh.Month01,
		InitialBudgetHours02 = AverageFTE * wh.Month02,
		InitialBudgetHours03 = AverageFTE * wh.Month03,
		InitialBudgetHours04 = AverageFTE * wh.Month04,
		InitialBudgetHours05 = AverageFTE * wh.Month05,
		InitialBudgetHours06 = AverageFTE * wh.Month06,
		InitialBudgetHours07 = AverageFTE * wh.Month07,
		InitialBudgetHours08 = AverageFTE * wh.Month08,
		InitialBudgetHours09 = AverageFTE * wh.Month09,
		InitialBudgetHours10 = AverageFTE * wh.Month10,
		InitialBudgetHours11 = AverageFTE * wh.Month11,
		InitialBudgetHours12 = AverageFTE * wh.Month12  		
   FROM [fp].[Staffing] fs 
	  INNER JOIN #flatFteTemp fte ON fs.StaffingID = fte.StaffingID 
	  INNER JOIN #BudgetWorkingHours wh on fs.StaffingID = wh.StaffingID

	-- update the initial values to be equal to the sampled values for variable job codes
	UPDATE
		fs
	SET
		fs.InitialBudgetHours01 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours02 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours03 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours04 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours05 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours06 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours07 = fv.InitialBudgetTotal / 12,				
		fs.InitialBudgetHours08 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours09 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours10 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours11 = fv.InitialBudgetTotal / 12,
		fs.InitialBudgetHours12 = fv.InitialBudgetTotal / 12				
	FROM [fp].[Staffing] fs
		INNER JOIN #spreadFixedVar fv on fs.StaffingID = fv.StaffingID 
		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID        
	WHERE fs.VariabilityID = 2 
		AND exc.PayCodeGroupID IS NULL 
	
	-- projection hours and FTEs  ------------------------------------------------------------------------------------------------
	SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.EmployeeID, fs.VariabilityID,
		CASE 
		 WHEN @MonthsLoaded = 12 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10 + InitialProjection11 + InitialProjection12
		 WHEN @MonthsLoaded >= 11 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10 + InitialProjection11
		 WHEN @MonthsLoaded >= 10 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10
		 WHEN @MonthsLoaded >= 9 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 
		 WHEN @MonthsLoaded >= 8 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08
		 WHEN @MonthsLoaded >= 7 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07
		 WHEN @MonthsLoaded >= 6 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06
		 WHEN @MonthsLoaded >= 5 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 
		 WHEN @MonthsLoaded >= 4 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04
		 WHEN @MonthsLoaded >= 3 THEN InitialProjection01 + InitialProjection02 + InitialProjection03
		 WHEN @MonthsLoaded >= 2 THEN InitialProjection01 + InitialProjection02 
		ELSE InitialProjection01				
		END AS SampledProjectionTotal
	INTO #MonthsLoadedTotal
	FROM #spreadFixedVar fs
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
     		   
   	-- spread hours so that FTEs remain flat for fixed job codes
	-- figure out ftes...
	SELECT h.StaffingID,
	     mnlt.SampledProjectionTotal / ytd.YTDHours AS AverageFTE
    INTO #fteTemp 
    FROM [fp].[Staffing] h 
		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID      
		INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID
	 	INNER JOIN #ProjectionYTD ytd on ytd.StaffingID = h.StaffingID  		       
    WHERE h.EntityGroupConfigID  = @EntityGroupConfigID AND (exc.PayCodeGroupID IS NOT NULL OR h.VariabilityID = 1) 
		
	-- Projected hours should vary by working hours for fixed JobCodes 
	UPDATE
		fs
	SET
		InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1  THEN psfv.InitialProjection01 ELSE AverageFTE * wh.Month01 END,
		InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2  THEN psfv.InitialProjection02 ELSE AverageFTE * wh.Month02 END,
		InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3  THEN psfv.InitialProjection03 ELSE AverageFTE * wh.Month03 END,
		InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4  THEN psfv.InitialProjection04 ELSE AverageFTE * wh.Month04 END,
		InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5  THEN psfv.InitialProjection05 ELSE AverageFTE * wh.Month05 END,
		InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6  THEN psfv.InitialProjection06 ELSE AverageFTE * wh.Month06 END,
		InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7  THEN psfv.InitialProjection07 ELSE AverageFTE * wh.Month07 END,
		InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8  THEN psfv.InitialProjection08 ELSE AverageFTE * wh.Month08 END,
		InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9  THEN psfv.InitialProjection09 ELSE AverageFTE * wh.Month09 END,
		InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE AverageFTE * wh.Month10 END,
		InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE AverageFTE * wh.Month11 END,
		InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE AverageFTE * wh.Month12 END
	FROM [fp].[Staffing] fs 
		INNER JOIN #spreadFixedVar sfv on fs.StaffingID = sfv.StaffingID 
		INNER JOIN #preSpreadFixedVar psfv on fs.StaffingID = psfv.StaffingID -- we need this because we need the actual values for months loaded projection unfortunately
		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID  
		INNER JOIN #fteTemp fte ON fte.StaffingID = fs.StaffingID  
		INNER JOIN #ProjectionWorkingHours wh on wh.StaffingID = fs.StaffingID  
	WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID 
		AND (exc.PayCodeGroupID IS NOT NULL OR fs.VariabilityID = 1) 
	
	-- Projected hours should be flat for variable Job Codes or PayCodeGroups that have ProductiveClass that is excluded from FTE calcs
	UPDATE
		fs
	SET
		InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1  THEN psfv.InitialProjection01 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2  THEN psfv.InitialProjection02 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3  THEN psfv.InitialProjection03 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4  THEN psfv.InitialProjection04 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5  THEN psfv.InitialProjection05 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6  THEN psfv.InitialProjection06 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7  THEN psfv.InitialProjection07 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8  THEN psfv.InitialProjection08 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9  THEN psfv.InitialProjection09 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END,
		InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END
	FROM [fp].[Staffing] fs INNER JOIN #MonthsLoadedTotal t on fs.StaffingID = t.StaffingID
		INNER JOIN #spreadFixedVar sfv on fs.StaffingID = sfv.StaffingID 
		INNER JOIN #preSpreadFixedVar psfv on fs.StaffingID = psfv.StaffingID -- we need this because we need the actual values for months loaded projection unfortunately
		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID           
	WHERE fs.VariabilityID = 2 
		AND exc.PayCodeGroupID IS NULL 
			
	-- update FTEs -- all hours should have been spread properly now, so FTEs should be simply hours / working hours			
	-- JAZZ-14996 - Added missing EmployeeID join on FTE update
	UPDATE fte SET         
	 	fte.InitialBudgetFTEs01 = fte.InitialBudgetHours01 / h.Month01,
	 	fte.InitialBudgetFTEs02 = fte.InitialBudgetHours02 / h.Month02,
	 	fte.InitialBudgetFTEs03 = fte.InitialBudgetHours03 / h.Month03,
	 	fte.InitialBudgetFTEs04 = fte.InitialBudgetHours04 / h.Month04,
	 	fte.InitialBudgetFTEs05 = fte.InitialBudgetHours05 / h.Month05,
	 	fte.InitialBudgetFTEs06 = fte.InitialBudgetHours06 / h.Month06,
	 	fte.InitialBudgetFTEs07 = fte.InitialBudgetHours07 / h.Month07,
	 	fte.InitialBudgetFTEs08 = fte.InitialBudgetHours08 / h.Month08,
	 	fte.InitialBudgetFTEs09 = fte.InitialBudgetHours09 / h.Month09,
	 	fte.InitialBudgetFTEs10 = fte.InitialBudgetHours10 / h.Month10,
	 	fte.InitialBudgetFTEs11 = fte.InitialBudgetHours11 / h.Month11,
	 	fte.InitialBudgetFTEs12 = fte.InitialBudgetHours12 / h.Month12,  
		fte.InitialProjectionFTEs01 = fte.InitialProjectionHours01 / pwh.Month01,
		fte.InitialProjectionFTEs02 = fte.InitialProjectionHours02 / pwh.Month02,
		fte.InitialProjectionFTEs03 = fte.InitialProjectionHours03 / pwh.Month03,
		fte.InitialProjectionFTEs04 = fte.InitialProjectionHours04 / pwh.Month04,
		fte.InitialProjectionFTEs05 = fte.InitialProjectionHours05 / pwh.Month05,
		fte.InitialProjectionFTEs06 = fte.InitialProjectionHours06 / pwh.Month06,
		fte.InitialProjectionFTEs07 = fte.InitialProjectionHours07 / pwh.Month07,
		fte.InitialProjectionFTEs08 = fte.InitialProjectionHours08 / pwh.Month08,
		fte.InitialProjectionFTEs09 = fte.InitialProjectionHours09 / pwh.Month09,
		fte.InitialProjectionFTEs10 = fte.InitialProjectionHours10 / pwh.Month10,
		fte.InitialProjectionFTEs11 = fte.InitialProjectionHours11 / pwh.Month11,
		fte.InitialProjectionFTEs12 = fte.InitialProjectionHours12 / pwh.Month12 
    FROM [fp].[Staffing] fte		
		INNER JOIN #BudgetWorkingHours h ON h.StaffingID = fte.StaffingID -- we can use StaffingID now instead of all the dimensionality since it's the same row
 		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON h.PayCodeGroupID = exc.PayCodeGroupID
  		INNER JOIN #ProjectionWorkingHours pwh ON pwh.StaffingID = fte.StaffingID 
		WHERE fte.EntityGroupConfigID = @EntityGroupConfigID 
		  AND exc.PayCodeGroupID IS NULL


	------ Dollars ----------------------------------------------------
	UPDATE
		fs
	SET
		fs.InitialBudgetDollars01 = fs.InitialBudgetHours01 * wr.InitialBudget01,
		fs.InitialBudgetDollars02 = fs.InitialBudgetHours02 * wr.InitialBudget02,
		fs.InitialBudgetDollars03 = fs.InitialBudgetHours03 * wr.InitialBudget03,
		fs.InitialBudgetDollars04 = fs.InitialBudgetHours04 * wr.InitialBudget04,
		fs.InitialBudgetDollars05 = fs.InitialBudgetHours05 * wr.InitialBudget05,
		fs.InitialBudgetDollars06 = fs.InitialBudgetHours06 * wr.InitialBudget06,
		fs.InitialBudgetDollars07 = fs.InitialBudgetHours07 * wr.InitialBudget07,
		fs.InitialBudgetDollars08 = fs.InitialBudgetHours08 * wr.InitialBudget08,
		fs.InitialBudgetDollars09 = fs.InitialBudgetHours09 * wr.InitialBudget09,
		fs.InitialBudgetDollars10 = fs.InitialBudgetHours10 * wr.InitialBudget10,
		fs.InitialBudgetDollars11 = fs.InitialBudgetHours11 * wr.InitialBudget11,
		fs.InitialBudgetDollars12 = fs.InitialBudgetHours12 * wr.InitialBudget12, 
		fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN psfv.InitialProjection01 ELSE fs.InitialProjectionHours01 * wr.InitialProjection01 END,
		fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN psfv.InitialProjection02 ELSE fs.InitialProjectionHours02 * wr.InitialProjection02 END,
		fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN psfv.InitialProjection03 ELSE fs.InitialProjectionHours03 * wr.InitialProjection03 END,
		fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN psfv.InitialProjection04 ELSE fs.InitialProjectionHours04 * wr.InitialProjection04 END,
		fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN psfv.InitialProjection05 ELSE fs.InitialProjectionHours05 * wr.InitialProjection05 END,
		fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN psfv.InitialProjection06 ELSE fs.InitialProjectionHours06 * wr.InitialProjection06 END,
		fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN psfv.InitialProjection07 ELSE fs.InitialProjectionHours07 * wr.InitialProjection07 END,
		fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN psfv.InitialProjection08 ELSE fs.InitialProjectionHours08 * wr.InitialProjection08 END,
		fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN psfv.InitialProjection09 ELSE fs.InitialProjectionHours09 * wr.InitialProjection09 END,
		fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE fs.InitialProjectionHours10 * wr.InitialProjection10 END,
		fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE fs.InitialProjectionHours11 * wr.InitialProjection11 END,
		fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE fs.InitialProjectionHours12 * wr.InitialProjection12 END 
	FROM [fp].[Staffing] fs 
		INNER JOIN fp.StaffingWageRate wr on fs.StaffingWageRateID = wr.StaffingWageRateID
		INNER JOIN #preSpreadFixedVarDollars psfv  -- we need this unfortunately because we need the actual values for months loaded projection 
 			ON psfv.StaffingID = fs.StaffingID 
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.ProductiveClassID <> 4 -- exclude 'Dollars-Only'
		AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	
	
	-- now update dollars-only productive class 
	DELETE FROM #spreadFixedVar

	INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, 
		 ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, 
		 SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, 
		 SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12)
	SELECT
		 fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		 fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
		 SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, 
		 SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, 
		 SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, 
		 SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, 
		 SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, 
		 SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, 
		 SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, 
		 SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, 
		 SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, 
		 SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, 
		 SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, 
		 SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, 
		 SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12
    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID         
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.ProductiveClassID = 4 -- 'Dollars-Only'
    	AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID
		
	INSERT INTO #spreadFixedVar (StaffingID, 
						InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,	InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,	InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
						InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		 fs.StaffingID, 
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05,
       CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11,
         CASE WHEN fs.VariabilityID = 1                                                                                                                                                     
								  THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
							      ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
						          END as InitialBudgetDollars12,	
	    CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12
    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID    
		 INNER JOIN #combinedStaffingDollarsAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID    
         LEFT JOIN #Variability fv ON 
				fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.EmployeeID = fs.EmployeeID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.ProductiveClassID = 4 -- 'Dollars-Only'
    	AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider
    
	TRUNCATE TABLE #combinedStaffingDollarsAboveVariability;

    --------------------------- Provider Line Item variability ---------------------------	
	
	INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, 
		 ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, 
		 SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, 
		 SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12)
	SELECT
		 fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		 fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
		 SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, 
		 SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, 
		 SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, 
		 SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, 
		 SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, 
		 SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, 
		 SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, 
		 SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, 
		 SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, 
		 SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, 
		 SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, 
		 SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, 
		 SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12
    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID         
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
    	AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID)  --  provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID

	INSERT INTO #spreadFixedVar (StaffingID, 
						InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,	InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,	InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
						InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		 fs.StaffingID, 
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11,
         CASE WHEN fs.VariabilityID = 1                                                                                                                       
								  THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
							      ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
						          END as InitialBudgetDollars12,	
	    CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12

    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID   
		 INNER JOIN #combinedStaffingDollarsAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID   
         LEFT JOIN #Variability fv   -- if this is a filtered call, filtering was done here
            ON fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.ProviderLineItemID = fs.ProviderLineItemID
			AND fv.EmployeeID = fs.EmployeeID
	WHERE 
    	fs.EntityGroupConfigID = @EntityGroupConfigID 
    	AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID)  --  provider


	-- update initial budget for dollars
	UPDATE fs
	SET
		fs.InitialBudgetDollars01 = sfv.InitialBudget01,
		fs.InitialBudgetDollars02 = sfv.InitialBudget02,
		fs.InitialBudgetDollars03 = sfv.InitialBudget03,
		fs.InitialBudgetDollars04 = sfv.InitialBudget04,
		fs.InitialBudgetDollars05 = sfv.InitialBudget05,
		fs.InitialBudgetDollars06 = sfv.InitialBudget06,
		fs.InitialBudgetDollars07 = sfv.InitialBudget07,
		fs.InitialBudgetDollars08 = sfv.InitialBudget08,
		fs.InitialBudgetDollars09 = sfv.InitialBudget09,
		fs.InitialBudgetDollars10 = sfv.InitialBudget10,
		fs.InitialBudgetDollars11 = sfv.InitialBudget11,
		fs.InitialBudgetDollars12 = sfv.InitialBudget12		
	FROM 
		[fp].[Staffing] fs
	INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID	


	 CREATE TABLE #DollarTotals (StaffingID INT, ProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8),
		INDEX ix_dol_1 NONCLUSTERED (StaffingID)
	 ) 
    INSERT INTO #DollarTotals (StaffingID, ProjectionTotal)
    SELECT StaffingID, 
	   CASE WHEN @MonthsLoaded = 11 THEN staff.InitialProjection12  
			 WHEN @MonthsLoaded = 10 THEN staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 9 THEN staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 8 THEN staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 7 THEN staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 6 THEN staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 5 THEN staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 4 THEN staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 3 THEN staff.InitialProjection04 + staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10  + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 2 THEN staff.InitialProjection03 + staff.InitialProjection04 + staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12
			 WHEN @MonthsLoaded = 1 THEN staff.InitialProjection02 + staff.InitialProjection03 + staff.InitialProjection04 + staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12  
		 	 ELSE 0
		END
    FROM #spreadFixedVar staff		      	  
	      
    UPDATE a 
	    SET NewValue = ProjectionTotal / (12.0 - @MonthsLoaded)
	FROM #DollarTotals a
		
		
	-- update initial projection for dollars and hours
	UPDATE fs
	SET		
		fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN sfv.InitialProjection01 ELSE t.NewValue END,
	    fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN sfv.InitialProjection02 ELSE t.NewValue END,
	    fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN sfv.InitialProjection03 ELSE t.NewValue END,
	    fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN sfv.InitialProjection04 ELSE t.NewValue END,
	    fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN sfv.InitialProjection05 ELSE t.NewValue END,
	    fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN sfv.InitialProjection06 ELSE t.NewValue END,
	    fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN sfv.InitialProjection07 ELSE t.NewValue END,
	    fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN sfv.InitialProjection08 ELSE t.NewValue END,
	    fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN sfv.InitialProjection09 ELSE t.NewValue END,
	    fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN sfv.InitialProjection10 ELSE t.NewValue END,
	    fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN sfv.InitialProjection11 ELSE t.NewValue END,
	    fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN sfv.InitialProjection12 ELSE t.NewValue END
	FROM [fp].[Staffing] fs 
		INNER JOIN #DollarTotals t on fs.StaffingID = t.StaffingID
		INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID			
 
	-- Cleaning up records where flexMethod = 6 (Fixed) AND variabilityID = 2 (Variable)
	
	UPDATE fs SET         
	 	fs.InitialBudgetFTEs01 = 0,
	 	fs.InitialBudgetFTEs02 = 0,
	 	fs.InitialBudgetFTEs03 = 0,
	 	fs.InitialBudgetFTEs04 = 0,
	 	fs.InitialBudgetFTEs05 = 0,
	 	fs.InitialBudgetFTEs06 = 0,
	 	fs.InitialBudgetFTEs07 = 0,
	 	fs.InitialBudgetFTEs08 = 0,
	 	fs.InitialBudgetFTEs09 = 0,
	 	fs.InitialBudgetFTEs10 = 0,
	 	fs.InitialBudgetFTEs11 = 0,
	 	fs.InitialBudgetFTEs12 = 0,  
		fs.InitialProjectionFTEs01 = 0,
		fs.InitialProjectionFTEs02 = 0,
		fs.InitialProjectionFTEs03 = 0,
		fs.InitialProjectionFTEs04 = 0,
		fs.InitialProjectionFTEs05 = 0,
		fs.InitialProjectionFTEs06 = 0,
		fs.InitialProjectionFTEs07 = 0,
		fs.InitialProjectionFTEs08 = 0,
		fs.InitialProjectionFTEs09 = 0,
		fs.InitialProjectionFTEs10 = 0,
		fs.InitialProjectionFTEs11 = 0,
		fs.InitialProjectionFTEs12 = 0,
		
		fs.TargetAdjustedFTEs01 = 0,
	 	fs.TargetAdjustedFTEs02 = 0,
	 	fs.TargetAdjustedFTEs03 = 0,
	 	fs.TargetAdjustedFTEs04 = 0,
	 	fs.TargetAdjustedFTEs05 = 0,
	 	fs.TargetAdjustedFTEs06 = 0,
	 	fs.TargetAdjustedFTEs07 = 0,
	 	fs.TargetAdjustedFTEs08 = 0,
	 	fs.TargetAdjustedFTEs09 = 0,
	 	fs.TargetAdjustedFTEs10 = 0,
	 	fs.TargetAdjustedFTEs11 = 0,
	 	fs.TargetAdjustedFTEs12 = 0, 
		fs.BudgetAdjustedFTEs01 = 0,
	 	fs.BudgetAdjustedFTEs02 = 0,
	 	fs.BudgetAdjustedFTEs03 = 0,
	 	fs.BudgetAdjustedFTEs04 = 0,
	 	fs.BudgetAdjustedFTEs05 = 0,
	 	fs.BudgetAdjustedFTEs06 = 0,
	 	fs.BudgetAdjustedFTEs07 = 0,
	 	fs.BudgetAdjustedFTEs08 = 0,
	 	fs.BudgetAdjustedFTEs09 = 0,
	 	fs.BudgetAdjustedFTEs10 = 0,
	 	fs.BudgetAdjustedFTEs11 = 0,
	 	fs.BudgetAdjustedFTEs12 = 0,

		fs.ProjectionAdjustedFTEs01 = 0,
		fs.ProjectionAdjustedFTEs02 = 0,
		fs.ProjectionAdjustedFTEs03 = 0,
		fs.ProjectionAdjustedFTEs04 = 0,
		fs.ProjectionAdjustedFTEs05 = 0,
		fs.ProjectionAdjustedFTEs06 = 0,
		fs.ProjectionAdjustedFTEs07 = 0,
		fs.ProjectionAdjustedFTEs08 = 0,
		fs.ProjectionAdjustedFTEs09 = 0,
		fs.ProjectionAdjustedFTEs10 = 0,
		fs.ProjectionAdjustedFTEs11 = 0,
		fs.ProjectionAdjustedFTEs12 = 0,
		fs.TargetFTEsPercentAdjustmentFactor01 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor02 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor03 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor04 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor05 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor06 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor07 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor08 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor09 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor10 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor11 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor12 = 0, 
		fs.BudgetFTEsPercentAdjustmentFactor01 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor02 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor03 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor04 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor05 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor06 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor07 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor08 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor09 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor10 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor11 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor12 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor01 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor02 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor03 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor04 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor05 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor06 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor07 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor08 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor09 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor10 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor11 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor12 = 0,

		fs.InitialBudgetRate01 = 0,
	 	fs.InitialBudgetRate02 = 0,
	 	fs.InitialBudgetRate03 = 0,
	 	fs.InitialBudgetRate04 = 0,
	 	fs.InitialBudgetRate05 = 0,
	 	fs.InitialBudgetRate06 = 0,
	 	fs.InitialBudgetRate07 = 0,
	 	fs.InitialBudgetRate08 = 0,
	 	fs.InitialBudgetRate09 = 0,
	 	fs.InitialBudgetRate10 = 0,
	 	fs.InitialBudgetRate11 = 0,
	 	fs.InitialBudgetRate12 = 0, 
		fs.InitialProjectionRate01 = 0,
	 	fs.InitialProjectionRate02 = 0,
	 	fs.InitialProjectionRate03 = 0,
	 	fs.InitialProjectionRate04 = 0,
	 	fs.InitialProjectionRate05 = 0,
	 	fs.InitialProjectionRate06 = 0,
	 	fs.InitialProjectionRate07 = 0,
	 	fs.InitialProjectionRate08 = 0,
	 	fs.InitialProjectionRate09 = 0,
	 	fs.InitialProjectionRate10 = 0,
	 	fs.InitialProjectionRate11 = 0,
	 	fs.InitialProjectionRate12 = 0,
		fs.TargetAdjustedRate01 = 0,
	 	fs.TargetAdjustedRate02 = 0,
	 	fs.TargetAdjustedRate03 = 0,
	 	fs.TargetAdjustedRate04 = 0,
	 	fs.TargetAdjustedRate05 = 0,
	 	fs.TargetAdjustedRate06 = 0,
	 	fs.TargetAdjustedRate07 = 0,
	 	fs.TargetAdjustedRate08 = 0,
	 	fs.TargetAdjustedRate09 = 0,
	 	fs.TargetAdjustedRate10 = 0,
	 	fs.TargetAdjustedRate11 = 0,
	 	fs.TargetAdjustedRate12 = 0, 
		fs.BudgetAdjustedRate01 = 0,
	 	fs.BudgetAdjustedRate02 = 0,
	 	fs.BudgetAdjustedRate03 = 0,
	 	fs.BudgetAdjustedRate04 = 0,
	 	fs.BudgetAdjustedRate05 = 0,
	 	fs.BudgetAdjustedRate06 = 0,
	 	fs.BudgetAdjustedRate07 = 0,
	 	fs.BudgetAdjustedRate08 = 0,
	 	fs.BudgetAdjustedRate09 = 0,
	 	fs.BudgetAdjustedRate10 = 0,
	 	fs.BudgetAdjustedRate11 = 0,
	 	fs.BudgetAdjustedRate12 = 0,
		fs.ProjectionAdjustedRate01 = 0,
		fs.ProjectionAdjustedRate02 = 0,
		fs.ProjectionAdjustedRate03 = 0,
		fs.ProjectionAdjustedRate04 = 0,
		fs.ProjectionAdjustedRate05 = 0,
		fs.ProjectionAdjustedRate06 = 0,
		fs.ProjectionAdjustedRate07 = 0,
		fs.ProjectionAdjustedRate08 = 0,
		fs.ProjectionAdjustedRate09 = 0,
		fs.ProjectionAdjustedRate10 = 0,
		fs.ProjectionAdjustedRate11 = 0,
		fs.ProjectionAdjustedRate12 = 0
   FROM [fp].[Staffing] fs
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
		LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID 
			AND fs.JobCodeID = v.JobCodeID 
			AND fs.PayCodeGroupID = v.PayCodeGroupID
			AND v.ProviderLineItemID = fs.ProviderLineItemID
			AND v.EmployeeID = fs.EmployeeID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
		AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL)
		AND fs.VariabilityID = 2
   

 END;
GO


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

-- fp.procApplyVariabilityToStaffingHistory
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI		   Description
** 1	2018-10-04  IP      B-20922	   Added using source dimensionality
** 2	2019-08-19  BK      B-24026	   Performance updates
** 3  	2020-07-20  MW		JAZZ-2212	   Add EmployeeID for EB
** 4	2020-08-05  LR      JAZZ-1226	   Added clean up for variable hours and FTEs with Fixed override
** 5	2020-10-27  LR 		JAZZ-6178    Alter ApplyVariabilityToStaffingHistory to fix migration override
** 6	2020-11-04  BK 		JAZZ-8379    Add provider fields to proc and clean up filtering
** 7 	2021-08-16  BK		JAZZ-21272   Use cached variability table for cleaning up variable records
** 8 	2022-04-12  OP      JAZZ-36116   Sampled all hours as fixed for provider compensation
** 9 	2022-04-29  MY		JAZZ-28395   Cache Variability Percentage on FactStaffing
** 10	2022-10-04  MY		JAZZ-37262   Remove Feature Flag 'Use Variability From FactStaffing Table'
** 11	2022-11-07  MY      JAZZ-35951   Add EmployeeID to FactStaffingVariabilityDetail
** 12	2023-09-20  BK      JAZZ-60973   Update for new data structure
** 13	2023-12-26 NH/NT    JAZZ-64324   Remove 'Use Hours and FTE on Provider Compensation (doing this in restructure branch on behalf of Softserve)
** 14	2024-01-31  NH      JAZZ-64064   Move Provider Planning FF as a setting in Plan Config
*************************************************************/
CREATE   PROCEDURE [fp].[procApplyVariabilityToStaffingHistory]
	@EntityGroupConfigID INT,
	@FiscalYearID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN

 	IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals
 	IF OBJECT_ID('tempdb..#FilteredTotals') IS NOT NULL DROP TABLE #FilteredTotals
 	IF OBJECT_ID('tempdb..#Variability') IS NOT NULL DROP TABLE #Variability
		
 	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	CREATE TABLE #FilteringTable (
		DepartmentID INT
		,INDEX ix_1 NONCLUSTERED (DepartmentID)
	)

	INSERT INTO #FilteringTable (DepartmentID)
	SELECT DepartmentID
	FROM @SourceDimensionality
	
	DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER;
	SET @EntityGroupConfigGUID = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID)
	
	CREATE TABLE #Variability (  DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(19,8),
									INDEX ix_totals_1 NONCLUSTERED ( DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID)
									)

	DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable)

	IF (@isFilterPresent=0) BEGIN
		INSERT INTO #FilteringTable (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	
		
	INSERT INTO #Variability (DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage)
	SELECT v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage
	FROM [fp].[viewFactStaffingVariability] v
		INNER JOIN #FilteringTable f ON v.DepartmentID = f.DepartmentID
	WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
	GROUP BY v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID


	SELECT 
		fs.DepartmentID,
		fs.JobCodeID,
		fs.EmployeeID,
		fs.PayCodeGroupID,
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
		SUM(b.PriorYearActualHours01) AS PriorYearActualHours01,
		SUM(b.PriorYearActualHours02) AS PriorYearActualHours02,
		SUM(b.PriorYearActualHours03) AS PriorYearActualHours03,
		SUM(b.PriorYearActualHours04) AS PriorYearActualHours04,
		SUM(b.PriorYearActualHours05) AS PriorYearActualHours05,
		SUM(b.PriorYearActualHours06) AS PriorYearActualHours06,
		SUM(b.PriorYearActualHours07) AS PriorYearActualHours07,
		SUM(b.PriorYearActualHours08) AS PriorYearActualHours08,
		SUM(b.PriorYearActualHours09) AS PriorYearActualHours09,
		SUM(b.PriorYearActualHours10) AS PriorYearActualHours10,
		SUM(b.PriorYearActualHours11) AS PriorYearActualHours11,
		SUM(b.PriorYearActualHours12) AS PriorYearActualHours12,
		SUM(b.ActualYTDHours01) AS ActualYTDHours01,
		SUM(b.ActualYTDHours02) AS ActualYTDHours02,
		SUM(b.ActualYTDHours03) AS ActualYTDHours03,
		SUM(b.ActualYTDHours04) AS ActualYTDHours04,
		SUM(b.ActualYTDHours05) AS ActualYTDHours05,
		SUM(b.ActualYTDHours06) AS ActualYTDHours06,
		SUM(b.ActualYTDHours07) AS ActualYTDHours07,
		SUM(b.ActualYTDHours08) AS ActualYTDHours08,
		SUM(b.ActualYTDHours09) AS ActualYTDHours09,
		SUM(b.ActualYTDHours10) AS ActualYTDHours10,
		SUM(b.ActualYTDHours11) AS ActualYTDHours11,
		SUM(b.ActualYTDHours12) AS ActualYTDHours12,
		SUM(b.CurrentYearBudgetHours01) AS CurrentYearBudgetHours01,
		SUM(b.CurrentYearBudgetHours02) AS CurrentYearBudgetHours02,
		SUM(b.CurrentYearBudgetHours03) AS CurrentYearBudgetHours03,
		SUM(b.CurrentYearBudgetHours04) AS CurrentYearBudgetHours04,
		SUM(b.CurrentYearBudgetHours05) AS CurrentYearBudgetHours05,
		SUM(b.CurrentYearBudgetHours06) AS CurrentYearBudgetHours06,
		SUM(b.CurrentYearBudgetHours07) AS CurrentYearBudgetHours07,
		SUM(b.CurrentYearBudgetHours08) AS CurrentYearBudgetHours08,
		SUM(b.CurrentYearBudgetHours09) AS CurrentYearBudgetHours09,
		SUM(b.CurrentYearBudgetHours10) AS CurrentYearBudgetHours10,
		SUM(b.CurrentYearBudgetHours11) AS CurrentYearBudgetHours11,
		SUM(b.CurrentYearBudgetHours12) AS CurrentYearBudgetHours12,
		SUM(b.PriorYearActualDollars01) AS PriorYearActualDollars01,
		SUM(b.PriorYearActualDollars02) AS PriorYearActualDollars02,
		SUM(b.PriorYearActualDollars03) AS PriorYearActualDollars03,
		SUM(b.PriorYearActualDollars04) AS PriorYearActualDollars04,
		SUM(b.PriorYearActualDollars05) AS PriorYearActualDollars05,
		SUM(b.PriorYearActualDollars06) AS PriorYearActualDollars06,
		SUM(b.PriorYearActualDollars07) AS PriorYearActualDollars07,
		SUM(b.PriorYearActualDollars08) AS PriorYearActualDollars08,
		SUM(b.PriorYearActualDollars09) AS PriorYearActualDollars09,
		SUM(b.PriorYearActualDollars10) AS PriorYearActualDollars10,
		SUM(b.PriorYearActualDollars11) AS PriorYearActualDollars11,
		SUM(b.PriorYearActualDollars12) AS PriorYearActualDollars12,
		SUM(b.ActualYTDDollars01) AS ActualYTDDollars01,
		SUM(b.ActualYTDDollars02) AS ActualYTDDollars02,
		SUM(b.ActualYTDDollars03) AS ActualYTDDollars03,
		SUM(b.ActualYTDDollars04) AS ActualYTDDollars04,
		SUM(b.ActualYTDDollars05) AS ActualYTDDollars05,
		SUM(b.ActualYTDDollars06) AS ActualYTDDollars06,
		SUM(b.ActualYTDDollars07) AS ActualYTDDollars07,
		SUM(b.ActualYTDDollars08) AS ActualYTDDollars08,
		SUM(b.ActualYTDDollars09) AS ActualYTDDollars09,
		SUM(b.ActualYTDDollars10) AS ActualYTDDollars10,
		SUM(b.ActualYTDDollars11) AS ActualYTDDollars11,
		SUM(b.ActualYTDDollars12) AS ActualYTDDollars12,
		SUM(b.CurrentYearBudgetDollars01) AS CurrentYearBudgetDollars01,
		SUM(b.CurrentYearBudgetDollars02) AS CurrentYearBudgetDollars02,
		SUM(b.CurrentYearBudgetDollars03) AS CurrentYearBudgetDollars03,
		SUM(b.CurrentYearBudgetDollars04) AS CurrentYearBudgetDollars04,
		SUM(b.CurrentYearBudgetDollars05) AS CurrentYearBudgetDollars05,
		SUM(b.CurrentYearBudgetDollars06) AS CurrentYearBudgetDollars06,
		SUM(b.CurrentYearBudgetDollars07) AS CurrentYearBudgetDollars07,
		SUM(b.CurrentYearBudgetDollars08) AS CurrentYearBudgetDollars08,
		SUM(b.CurrentYearBudgetDollars09) AS CurrentYearBudgetDollars09,
		SUM(b.CurrentYearBudgetDollars10) AS CurrentYearBudgetDollars10,
		SUM(b.CurrentYearBudgetDollars11) AS CurrentYearBudgetDollars11,
		SUM(b.CurrentYearBudgetDollars12) AS CurrentYearBudgetDollars12,
		SUM(b.PriorYearActualFTEs01) AS PriorYearActualFTEs01,
		SUM(b.PriorYearActualFTEs02) AS PriorYearActualFTEs02,
		SUM(b.PriorYearActualFTEs03) AS PriorYearActualFTEs03,
		SUM(b.PriorYearActualFTEs04) AS PriorYearActualFTEs04,
		SUM(b.PriorYearActualFTEs05) AS PriorYearActualFTEs05,
		SUM(b.PriorYearActualFTEs06) AS PriorYearActualFTEs06,
		SUM(b.PriorYearActualFTEs07) AS PriorYearActualFTEs07,
		SUM(b.PriorYearActualFTEs08) AS PriorYearActualFTEs08,
		SUM(b.PriorYearActualFTEs09) AS PriorYearActualFTEs09,
		SUM(b.PriorYearActualFTEs10) AS PriorYearActualFTEs10,
		SUM(b.PriorYearActualFTEs11) AS PriorYearActualFTEs11,
		SUM(b.PriorYearActualFTEs12) AS PriorYearActualFTEs12,
		SUM(b.ActualYTDFTEs01) AS ActualYTDFTEs01,
		SUM(b.ActualYTDFTEs02) AS ActualYTDFTEs02,
		SUM(b.ActualYTDFTEs03) AS ActualYTDFTEs03,
		SUM(b.ActualYTDFTEs04) AS ActualYTDFTEs04,
		SUM(b.ActualYTDFTEs05) AS ActualYTDFTEs05,
		SUM(b.ActualYTDFTEs06) AS ActualYTDFTEs06,
		SUM(b.ActualYTDFTEs07) AS ActualYTDFTEs07,
		SUM(b.ActualYTDFTEs08) AS ActualYTDFTEs08,
		SUM(b.ActualYTDFTEs09) AS ActualYTDFTEs09,
		SUM(b.ActualYTDFTEs10) AS ActualYTDFTEs10,
		SUM(b.ActualYTDFTEs11) AS ActualYTDFTEs11,
		SUM(b.ActualYTDFTEs12) AS ActualYTDFTEs12,
		SUM(b.CurrentYearBudgetFTEs01) AS CurrentYearBudgetFTEs01,
		SUM(b.CurrentYearBudgetFTEs02) AS CurrentYearBudgetFTEs02,
		SUM(b.CurrentYearBudgetFTEs03) AS CurrentYearBudgetFTEs03,
		SUM(b.CurrentYearBudgetFTEs04) AS CurrentYearBudgetFTEs04,
		SUM(b.CurrentYearBudgetFTEs05) AS CurrentYearBudgetFTEs05,
		SUM(b.CurrentYearBudgetFTEs06) AS CurrentYearBudgetFTEs06,
		SUM(b.CurrentYearBudgetFTEs07) AS CurrentYearBudgetFTEs07,
		SUM(b.CurrentYearBudgetFTEs08) AS CurrentYearBudgetFTEs08,
		SUM(b.CurrentYearBudgetFTEs09) AS CurrentYearBudgetFTEs09,
		SUM(b.CurrentYearBudgetFTEs10) AS CurrentYearBudgetFTEs10,
		SUM(b.CurrentYearBudgetFTEs11) AS CurrentYearBudgetFTEs11,
		SUM(b.CurrentYearBudgetFTEs12) AS CurrentYearBudgetFTEs12
	INTO #FilteredTotals
	FROM 
	    [fp].[StaffingHistory] b  INNER JOIN [fp].[Staffing] fs ON b.StaffingID = fs.StaffingID
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
	WHERE 
	    fs.EntityGroupConfigID = @EntityGroupConfigID
	GROUP BY
		fs.DepartmentID,
		fs.JobCodeID,
		fs.EmployeeID,
		fs.PayCodeGroupID,
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID
		
	-- dollars and ftes should be updated no matter what					
	UPDATE basis
	SET 
	   
		basis.PriorYearActualDollars01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars01 END,
	    basis.PriorYearActualDollars02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars02 END,
	    basis.PriorYearActualDollars03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars03 END,
	    basis.PriorYearActualDollars04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars04 END,
	    basis.PriorYearActualDollars05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars05 END,
	    basis.PriorYearActualDollars06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars06 END,
	    basis.PriorYearActualDollars07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars07 END,
	    basis.PriorYearActualDollars08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars08 END,
	    basis.PriorYearActualDollars09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars09 END,
	    basis.PriorYearActualDollars10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars10 END,
	    basis.PriorYearActualDollars11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars11 END,
	    basis.PriorYearActualDollars12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars12 END,
	
	    basis.ActualYTDDollars01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars01 END,
	    basis.ActualYTDDollars02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars02 END,
	    basis.ActualYTDDollars03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars03 END,
	    basis.ActualYTDDollars04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars04 END,
	    basis.ActualYTDDollars05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars05 END,
	    basis.ActualYTDDollars06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars06 END,
	    basis.ActualYTDDollars07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars07 END,
	    basis.ActualYTDDollars08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars08 END,
	    basis.ActualYTDDollars09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars09 END,
	    basis.ActualYTDDollars10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars10 END,
	    basis.ActualYTDDollars11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars11 END,
	    basis.ActualYTDDollars12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars12 END,
	
	    basis.CurrentYearBudgetDollars01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars01 END,
	    basis.CurrentYearBudgetDollars02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars02 END,
	    basis.CurrentYearBudgetDollars03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars03 END,
	    basis.CurrentYearBudgetDollars04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars04 END,
	    basis.CurrentYearBudgetDollars05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars05 END,
	    basis.CurrentYearBudgetDollars06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars06 END,
	    basis.CurrentYearBudgetDollars07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars07 END,
	    basis.CurrentYearBudgetDollars08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars08 END,
	    basis.CurrentYearBudgetDollars09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars09 END,
	    basis.CurrentYearBudgetDollars10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars10 END,
	    basis.CurrentYearBudgetDollars11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars11 END,
	    basis.CurrentYearBudgetDollars12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars12 END,

		basis.PriorYearActualFTEs01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs01 END,
	    basis.PriorYearActualFTEs02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs02 END,
	    basis.PriorYearActualFTEs03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs03 END,
	    basis.PriorYearActualFTEs04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs04 END,
	    basis.PriorYearActualFTEs05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs05 END,
	    basis.PriorYearActualFTEs06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs06 END,
	    basis.PriorYearActualFTEs07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs07 END,
	    basis.PriorYearActualFTEs08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs08 END,
	    basis.PriorYearActualFTEs09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs09 END,
	    basis.PriorYearActualFTEs10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs10 END,
	    basis.PriorYearActualFTEs11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs11 END,
	    basis.PriorYearActualFTEs12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs12 END,
	
	    basis.ActualYTDFTEs01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs01 END,
	    basis.ActualYTDFTEs02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs02 END,
	    basis.ActualYTDFTEs03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs03 END,
	    basis.ActualYTDFTEs04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs04 END,
	    basis.ActualYTDFTEs05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs05 END,
	    basis.ActualYTDFTEs06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs06 END,
	    basis.ActualYTDFTEs07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs07 END,
	    basis.ActualYTDFTEs08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs08 END,
	    basis.ActualYTDFTEs09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs09 END,
	    basis.ActualYTDFTEs10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs10 END,
	    basis.ActualYTDFTEs11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs11 END,
	    basis.ActualYTDFTEs12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs12 END,
	
	    basis.CurrentYearBudgetFTEs01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs01 END,
	    basis.CurrentYearBudgetFTEs02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs02 END,
	    basis.CurrentYearBudgetFTEs03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs03 END,
	    basis.CurrentYearBudgetFTEs04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs04 END,
	    basis.CurrentYearBudgetFTEs05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs05 END,
	    basis.CurrentYearBudgetFTEs06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs06 END,
	    basis.CurrentYearBudgetFTEs07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs07 END,
	    basis.CurrentYearBudgetFTEs08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs08 END,
	    basis.CurrentYearBudgetFTEs09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs09 END,
	    basis.CurrentYearBudgetFTEs10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs10 END,
	    basis.CurrentYearBudgetFTEs11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs11 END,
	    basis.CurrentYearBudgetFTEs12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs12 END
	FROM 
	    [fp].[StaffingHistory] basis
	    INNER JOIN [fp].[Staffing] fs ON basis.StaffingID = fs.StaffingID
		INNER JOIN #FilteredTotals total 
			ON total.DepartmentID = fs.DepartmentID 
	        AND total.JobCodeID = fs.JobCodeID
	        AND total.PayCodeGroupID = fs.PayCodeGroupID
	        AND total.EmployeeID = fs.EmployeeID
	    LEFT JOIN #Variability fv 
	        ON fv.DepartmentID = fs.DepartmentID 
	        AND fv.JobCodeID = fs.JobCodeID
	        AND fv.PayCodeGroupID = fs.PayCodeGroupID
	        AND fv.EmployeeID = fs.EmployeeID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID

	UPDATE basis
	SET 
	    basis.PriorYearActualHours01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours01 END,
	    basis.PriorYearActualHours02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours02 END,
	    basis.PriorYearActualHours03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours03 END,
	    basis.PriorYearActualHours04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours04 END,
	    basis.PriorYearActualHours05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours05 END,
	    basis.PriorYearActualHours06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours06 END,
	    basis.PriorYearActualHours07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours07 END,
	    basis.PriorYearActualHours08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours08 END,
	    basis.PriorYearActualHours09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours09 END,
	    basis.PriorYearActualHours10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours10 END,
	    basis.PriorYearActualHours11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours11 END,
	    basis.PriorYearActualHours12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours12 END,
	
	    basis.ActualYTDHours01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours01 END,
	    basis.ActualYTDHours02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours02 END,
	    basis.ActualYTDHours03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours03 END,
	    basis.ActualYTDHours04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours04 END,
	    basis.ActualYTDHours05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours05 END,
	    basis.ActualYTDHours06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours06 END,
	    basis.ActualYTDHours07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours07 END,
	    basis.ActualYTDHours08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours08 END,
	    basis.ActualYTDHours09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours09 END,
	    basis.ActualYTDHours10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours10 END,
	    basis.ActualYTDHours11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours11 END,
	    basis.ActualYTDHours12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours12 END,
	
	    basis.CurrentYearBudgetHours01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours01 END,
	    basis.CurrentYearBudgetHours02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours02 END,
	    basis.CurrentYearBudgetHours03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours03 END,
	    basis.CurrentYearBudgetHours04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours04 END,
	    basis.CurrentYearBudgetHours05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours05 END,
	    basis.CurrentYearBudgetHours06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours06 END,
	    basis.CurrentYearBudgetHours07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours07 END,
	    basis.CurrentYearBudgetHours08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours08 END,
	    basis.CurrentYearBudgetHours09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours09 END,
	    basis.CurrentYearBudgetHours10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours10 END,
	    basis.CurrentYearBudgetHours11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours11 END,
	    basis.CurrentYearBudgetHours12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours12 END
	
	FROM 
	    [fp].[StaffingHistory] basis
	    INNER JOIN [fp].[Staffing] fs ON basis.StaffingID = fs.StaffingID
		INNER JOIN #FilteredTotals total  
			ON total.DepartmentID = fs.DepartmentID 
	        AND total.JobCodeID = fs.JobCodeID
	        AND total.PayCodeGroupID = fs.PayCodeGroupID
	        AND total.EmployeeID = fs.EmployeeID	   
	    LEFT JOIN #Variability fv 
	        ON fv.DepartmentID = fs.DepartmentID 
	        AND fv.JobCodeID = fs.JobCodeID
	        AND fv.PayCodeGroupID = fs.PayCodeGroupID
	        AND fv.EmployeeID = fs.EmployeeID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 3 OR @IsProviderPlanningEnabled = 0)

	IF(@IsProviderPlanningEnabled = 1) BEGIN
		
		UPDATE basis
		SET 
	        basis.PriorYearActualHours01 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours01 ELSE 0 END,
	        basis.PriorYearActualHours02 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours02 ELSE 0 END,
	        basis.PriorYearActualHours03 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours03 ELSE 0 END,
	        basis.PriorYearActualHours04 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours04 ELSE 0 END,
	        basis.PriorYearActualHours05 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours05 ELSE 0 END,
	        basis.PriorYearActualHours06 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours06 ELSE 0 END,
	        basis.PriorYearActualHours07 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours07 ELSE 0 END,
	        basis.PriorYearActualHours08 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours08 ELSE 0 END,
	        basis.PriorYearActualHours09 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours09 ELSE 0 END,
	        basis.PriorYearActualHours10 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours10 ELSE 0 END,
	        basis.PriorYearActualHours11 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours11 ELSE 0 END,
	        basis.PriorYearActualHours12 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours12 ELSE 0 END,
	
	        basis.ActualYTDHours01 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours01 ELSE 0 END,
	        basis.ActualYTDHours02 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours02 ELSE 0 END,
	        basis.ActualYTDHours03 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours03 ELSE 0 END,
	        basis.ActualYTDHours04 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours04 ELSE 0 END,
	        basis.ActualYTDHours05 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours05 ELSE 0 END,
	        basis.ActualYTDHours06 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours06 ELSE 0 END,
	        basis.ActualYTDHours07 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours07 ELSE 0 END,
	        basis.ActualYTDHours08 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours08 ELSE 0 END,
	        basis.ActualYTDHours09 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours09 ELSE 0 END,
	        basis.ActualYTDHours10 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours10 ELSE 0 END,
	        basis.ActualYTDHours11 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours11 ELSE 0 END,
	        basis.ActualYTDHours12 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours12 ELSE 0 END,
	
	        basis.CurrentYearBudgetHours01 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours01 ELSE 0 END,
	        basis.CurrentYearBudgetHours02 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours02 ELSE 0 END,
	        basis.CurrentYearBudgetHours03 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours03 ELSE 0 END,
	        basis.CurrentYearBudgetHours04 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours04 ELSE 0 END,
	        basis.CurrentYearBudgetHours05 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours05 ELSE 0 END,
	        basis.CurrentYearBudgetHours06 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours06 ELSE 0 END,
	        basis.CurrentYearBudgetHours07 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours07 ELSE 0 END,
	        basis.CurrentYearBudgetHours08 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours08 ELSE 0 END,
	        basis.CurrentYearBudgetHours09 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours09 ELSE 0 END,
	        basis.CurrentYearBudgetHours10 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours10 ELSE 0 END,
	        basis.CurrentYearBudgetHours11 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours11 ELSE 0 END,
	        basis.CurrentYearBudgetHours12 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours12 ELSE 0 END
	    FROM 
	        [fp].[StaffingHistory] basis
	        INNER JOIN [fp].[Staffing] fs ON basis.StaffingID = fs.StaffingID
			INNER JOIN #FilteredTotals total  
				ON total.DepartmentID = fs.DepartmentID 
				AND total.JobCodeID = fs.JobCodeID
				AND total.PayCodeGroupID = fs.PayCodeGroupID
				AND total.EmployeeID = fs.EmployeeID	   	        
	        LEFT JOIN #Variability fv 
	            ON fv.DepartmentID = fs.DepartmentID 
	            AND fv.JobCodeID = fs.JobCodeID
	            AND fv.PayCodeGroupID = fs.PayCodeGroupID
				AND fv.EmployeeID = fs.EmployeeID
	    WHERE 
	        fs.EntityGroupConfigID = @EntityGroupConfigID	
			AND fs.SubsectionID = 4 

	END

	-- Cleaning up variable records where flexMethod = 6 (Fixed) AND variabilityID = 2 (Variable) AND unitTypeID = 144 or 172 (Hours Per UOS or FTEs)	
	CREATE TABLE #variableStaffingRecordsToCleanUp ( StaffingID int )
	
	IF @isFilterPresent = 0 BEGIN	
		INSERT INTO #variableStaffingRecordsToCleanUp		
		SELECT fs.StaffingID			
		FROM [fp].[Staffing] fs
			INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID
			LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID 
				AND fs.JobCodeID = v.JobCodeID 
				AND fs.PayCodeGroupID = v.PayCodeGroupID
				AND fs.EmployeeID = v.EmployeeID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL)
			AND fs.VariabilityID = 2 --AND (fs.UnitTypeID = 144 OR fs.UnitTypeID = 172)			
	END ELSE BEGIN		
		INSERT INTO #variableStaffingRecordsToCleanUp
		SELECT fs.StaffingID
		FROM [fp].[Staffing] fs
			INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
			INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID
			LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID 
				and fs.JobCodeID = v.JobCodeID 
				AND fs.PayCodeGroupID = v.PayCodeGroupID
				AND fs.EmployeeID = v.EmployeeID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID		
			AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL)
			AND fs.VariabilityID = 2 --AND (fs.UnitTypeID = 144 OR fs.UnitTypeID = 172)			
	END
	
	UPDATE fs SET         
	 	fs.PriorYearActualFTEs01 = 0,
	 	fs.PriorYearActualFTEs02 = 0,
	 	fs.PriorYearActualFTEs03 = 0,
	 	fs.PriorYearActualFTEs04 = 0,
	 	fs.PriorYearActualFTEs05 = 0,
	 	fs.PriorYearActualFTEs06 = 0,
	 	fs.PriorYearActualFTEs07 = 0,
	 	fs.PriorYearActualFTEs08 = 0,
	 	fs.PriorYearActualFTEs09 = 0,
	 	fs.PriorYearActualFTEs10 = 0,
	 	fs.PriorYearActualFTEs11 = 0,
	 	fs.PriorYearActualFTEs12 = 0,  
		fs.ActualYTDFTEs01 = 0,
		fs.ActualYTDFTEs02 = 0,
		fs.ActualYTDFTEs03 = 0,
		fs.ActualYTDFTEs04 = 0,
		fs.ActualYTDFTEs05 = 0,
		fs.ActualYTDFTEs06 = 0,
		fs.ActualYTDFTEs07 = 0,
		fs.ActualYTDFTEs08 = 0,
		fs.ActualYTDFTEs09 = 0,
		fs.ActualYTDFTEs10 = 0,
		fs.ActualYTDFTEs11 = 0,
		fs.ActualYTDFTEs12 = 0,
		fs.CurrentYearBudgetFTEs01 = 0,
	 	fs.CurrentYearBudgetFTEs02 = 0,
	 	fs.CurrentYearBudgetFTEs03 = 0,
	 	fs.CurrentYearBudgetFTEs04 = 0,
	 	fs.CurrentYearBudgetFTEs05 = 0,
	 	fs.CurrentYearBudgetFTEs06 = 0,
	 	fs.CurrentYearBudgetFTEs07 = 0,
	 	fs.CurrentYearBudgetFTEs08 = 0,
	 	fs.CurrentYearBudgetFTEs09 = 0,
	 	fs.CurrentYearBudgetFTEs10 = 0,
	 	fs.CurrentYearBudgetFTEs11 = 0,
	 	fs.CurrentYearBudgetFTEs12 = 0
    FROM [fp].[StaffingHistory] fs
		INNER JOIN #variableStaffingRecordsToCleanUp c ON c.StaffingID = fs.StaffingID
	
 END
GO


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

-- fp.procApplyVariabilityToStaffing_InitialPlan
/**************************************************************
** Change History 
**************************************************************
** CID  Date		Author	WI			  Description
** 1	2024-10-24	MY		JAZZ-78967    Initial Creation
*************************************************************/
CREATE   PROCEDURE [fp].[procApplyVariabilityToStaffing_InitialPlan]
	 @EntityGroupConfigID INT,
	 @FiscalYearID INT,
	 @MonthsLoaded INT,
	 @ProjectionFiscalYearID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0 -- WARNING: This will still update records, this just gives you a bit on insight on the temp tables. 
WITH RECOMPILE
AS
BEGIN
 
	SET NOCOUNT ON 
 
 	IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable
	IF OBJECT_ID('tempdb..#BudgetWorkingHours') IS NOT NULL DROP TABLE #BudgetWorkingHours
	IF OBJECT_ID('tempdb..#preSpreadFixedVar') IS NOT NULL DROP TABLE #preSpreadFixedVar
	IF OBJECT_ID('tempdb..#preSpreadFixedVarDollars') IS NOT NULL DROP TABLE #preSpreadFixedVarDollars
	IF OBJECT_ID('tempdb..#spreadFixedVar') IS NOT NULL DROP TABLE #spreadFixedVar
	IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals
	IF OBJECT_ID('tempdb..#fteTemp') IS NOT NULL DROP TABLE #fteTemp
	IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp
	IF OBJECT_ID('tempdb..#MonthsLoadedTotal') IS NOT NULL DROP TABLE #MonthsLoadedTotal
	IF OBJECT_ID('tempdb..#ProjectionWorkingHours') IS NOT NULL DROP TABLE #ProjectionWorkingHours
	IF OBJECT_ID('tempdb..#ProjectionYTD') IS NOT NULL DROP TABLE #ProjectionYTD
	IF OBJECT_ID('tempdb..#HoursAndWorkingHours') IS NOT NULL DROP TABLE #HoursAndWorkingHours
	IF OBJECT_ID('tempdb..#DollarTotals') IS NOT NULL DROP TABLE #DollarTotals
	IF OBJECT_ID('tempdb..#HoursForFteUpdate') IS NOT NULL DROP TABLE #HoursForFteUpdate
	IF OBJECT_ID('tempdb..#Variability') IS NOT NULL DROP TABLE #Variability
	IF OBJECT_ID('tempdb..#variableStaffingRecordsToCleanUp') IS NOT NULL DROP TABLE #variableStaffingRecordsToCleanUp
	IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability
	IF OBJECT_ID('tempdb..#combinedStaffingDollarsAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingDollarsAboveVariability
	
	CREATE TABLE #FilteringTable (
		DepartmentID INT
		,INDEX ix_1 NONCLUSTERED (DepartmentID)
		)

	INSERT INTO #FilteringTable (DepartmentID)
	SELECT DepartmentID
	FROM @SourceDimensionality

	DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER;
	SET @EntityGroupConfigGUID = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID)
	
	DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable)

	IF (@isFilterPresent=0) BEGIN
		INSERT INTO #FilteringTable (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	
	
	DECLARE @IsProviderPlanningEnabled BIT
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled 
	FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID 
	WHERE EntityGroupConfigID = @EntityGroupConfigID;	
		
	DECLARE @ProviderSubsectionID INT = 4;
	DECLARE @StaffingSubsectionID INT = 3;   
			
	DECLARE @SourceFiscalYearID int
	DECLARE @SourceTimeClassID int
	SELECT @SourceTimeClassID = PayrollTimeClassID, @SourceFiscalYearID = PayrollFiscalYearID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID
	DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @ProjectionFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)
	
	CREATE TABLE #Variability (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6))
	
	INSERT INTO #Variability (DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage)
	SELECT v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage
	FROM [fp].[viewFactStaffingVariability] v
		INNER JOIN #FilteringTable f ON v.DepartmentID = f.DepartmentID
	WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
	GROUP BY v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID

	-- Pre spread values. Basically we need the fixed/variable split before we spread it evenly
	CREATE TABLE #preSpreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT,
						ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
						InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8),
						InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8),
						InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8),
						InitialBudgetTotal DECIMAL(19,8),
						InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8),
						InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8),
						InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8),
						InitialProjectionTotal DECIMAL(19,8),
						INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID)
						)
	  -- we need this for projection dollars months loaded to be allocated to fixed/variable properly for when no hours exist but dollars do (jazz-66611)
	CREATE TABLE #preSpreadFixedVarDollars ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT,
						ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, 
						InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8),
						InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8),
						InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8)
						INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID)
						)

      CREATE TABLE #spreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT,
							ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
							InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8),
							InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8),
							InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8),
							InitialBudgetTotal DECIMAL(19,8),
							InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8),
							InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8),
							InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8),
							InitialProjectionTotal DECIMAL(19,8),
							INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID)
							)
	
	-- We need to find the totals above Variability so we can resplit the data.
	SELECT
		fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        SUM(fs.SampledBudgetHours01) AS SampledBudgetHours01,
        SUM(fs.SampledBudgetHours02) AS SampledBudgetHours02,
        SUM(fs.SampledBudgetHours03) AS SampledBudgetHours03,
        SUM(fs.SampledBudgetHours04) AS SampledBudgetHours04,
        SUM(fs.SampledBudgetHours05) AS SampledBudgetHours05,
        SUM(fs.SampledBudgetHours06) AS SampledBudgetHours06,
        SUM(fs.SampledBudgetHours07) AS SampledBudgetHours07,
        SUM(fs.SampledBudgetHours08) AS SampledBudgetHours08,
        SUM(fs.SampledBudgetHours09) AS SampledBudgetHours09,
        SUM(fs.SampledBudgetHours10) AS SampledBudgetHours10,
        SUM(fs.SampledBudgetHours11) AS SampledBudgetHours11,
        SUM(fs.SampledBudgetHours12) AS SampledBudgetHours12,	
        SUM(fs.SampledBudgetHoursTotal) AS SampledBudgetHoursTotal,
	    SUM(fs.SampledProjectionHours01) AS SampledProjectionHours01,	
        SUM(fs.SampledProjectionHours02) AS SampledProjectionHours02,
        SUM(fs.SampledProjectionHours03) AS SampledProjectionHours03,
        SUM(fs.SampledProjectionHours04) AS SampledProjectionHours04,
        SUM(fs.SampledProjectionHours05) AS SampledProjectionHours05,
        SUM(fs.SampledProjectionHours06) AS SampledProjectionHours06,
        SUM(fs.SampledProjectionHours07) AS SampledProjectionHours07,
        SUM(fs.SampledProjectionHours08) AS SampledProjectionHours08,
        SUM(fs.SampledProjectionHours09) AS SampledProjectionHours09,
        SUM(fs.SampledProjectionHours10) AS SampledProjectionHours10,
        SUM(fs.SampledProjectionHours11) AS SampledProjectionHours11,
        SUM(fs.SampledProjectionHours12) AS SampledProjectionHours12
	INTO #combinedStaffingHoursAboveVariability
    FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID )        
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID

	IF @IsDebug = 1
	BEGIN
		SELECT '#combinedStaffingHoursAboveVariability', * FROM #combinedStaffingHoursAboveVariability
	END

	-- We need to find the totals above Variability so we can resplit the data.
	SELECT
		fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        SUM(fs.SampledBudgetDollars01) AS SampledBudgetDollars01,
        SUM(fs.SampledBudgetDollars02) AS SampledBudgetDollars02,
        SUM(fs.SampledBudgetDollars03) AS SampledBudgetDollars03,
        SUM(fs.SampledBudgetDollars04) AS SampledBudgetDollars04,
        SUM(fs.SampledBudgetDollars05) AS SampledBudgetDollars05,
        SUM(fs.SampledBudgetDollars06) AS SampledBudgetDollars06,
        SUM(fs.SampledBudgetDollars07) AS SampledBudgetDollars07,
        SUM(fs.SampledBudgetDollars08) AS SampledBudgetDollars08,
        SUM(fs.SampledBudgetDollars09) AS SampledBudgetDollars09,
        SUM(fs.SampledBudgetDollars10) AS SampledBudgetDollars10,
        SUM(fs.SampledBudgetDollars11) AS SampledBudgetDollars11,
        SUM(fs.SampledBudgetDollars12) AS SampledBudgetDollars12,	
        SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal,
	    SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01,	
        SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02,
        SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03,
        SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04,
        SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05,
        SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06,
        SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07,
        SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08,
        SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09,
        SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10,
        SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11,
        SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12
	INTO #combinedStaffingDollarsAboveVariability
    FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID )        
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID
		
	IF @IsDebug = 1
	BEGIN
		SELECT '#combinedStaffingDollarsAboveVariability', * FROM #combinedStaffingDollarsAboveVariability
	END

	INSERT INTO #preSpreadFixedVar (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,
							InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,	InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,	InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, InitialBudgetTotal,
							InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours01) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours01) END as InitialBudgetHours01,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours02) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours02) END as InitialBudgetHours02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours03) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours03) END as InitialBudgetHours03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours04) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours04) END as InitialBudgetHours04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours05) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours05) END as InitialBudgetHours05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours06) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours06) END as InitialBudgetHours06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours07) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours07) END as InitialBudgetHours07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours08) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours08) END as InitialBudgetHours08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours09) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours09) END as InitialBudgetHours09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours10) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours10) END as InitialBudgetHours10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours11) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours11) END as InitialBudgetHours11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours12) END as InitialBudgetHours12,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHoursTotal) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHoursTotal) END as InitialBudgetHoursTotal,        
	    CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours01 END SampledProjectionHours01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours02 END SampledProjectionHours02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours03 END SampledProjectionHours03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours04 END SampledProjectionHours04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours05 END SampledProjectionHours05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours06 END SampledProjectionHours06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours07 END SampledProjectionHours07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours08 END SampledProjectionHours08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours09 END SampledProjectionHours09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours10 END SampledProjectionHours10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours11 END SampledProjectionHours11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours12 END SampledProjectionHours12
     FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
		INNER JOIN #combinedStaffingHoursAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID      
        LEFT JOIN #Variability fv 
            ON fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.ProviderLineItemID = fs.ProviderLineItemID
			AND fv.EmployeeID = fs.EmployeeID
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider

	INSERT INTO #preSpreadFixedVarDollars (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,							
							InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12
     FROM [fp].[Staffing] fs 
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
		INNER JOIN #combinedStaffingDollarsAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID      
        LEFT JOIN #Variability fv 
            ON fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.ProviderLineItemID = fs.ProviderLineItemID
			AND fv.EmployeeID = fs.EmployeeID
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider

	IF @IsDebug = 1
	BEGIN
		SELECT '#preSpreadFixedVar', * FROM #preSpreadFixedVar
	END

	-- We no longer need this after splitting out the hours
	IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability
				
	SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID,
							Month01, Month02, Month03, Month04,
							Month05, Month06, Month07, Month08,
							Month09, Month10, Month11, Month12, MonthYearly   -- Jazz-1796
	INTO #BudgetWorkingHours									
	FROM [fp].[Staffing] fs
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID 
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
        INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID
        INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)
    WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID)  -- exclude provider
		

	SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, 
							pwh.Month01, pwh.Month02, pwh.Month03, pwh.Month04,
							pwh.Month05, pwh.Month06, pwh.Month07, pwh.Month08,
							pwh.Month09, pwh.Month10, pwh.Month11, pwh.Month12, pwh.MonthYearly  -- Jazz-1796
	INTO #ProjectionWorkingHours									
	FROM #BudgetWorkingHours fs				
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID
        INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID
        INNER JOIN [client].[FactWorkingHoursPerMonth] pwh on pwh.FiscalYearID = @ProjectionFiscalYearID and pwh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)

	IF @IsDebug = 1
	BEGIN
		SELECT '#BudgetWorkingHours', * FROM #BudgetWorkingHours ORDER BY DepartmentID, JobCodeID, PayCodeGroupID
		SELECT '#ProjectionWorkingHours', * FROM #ProjectionWorkingHours ORDER BY DepartmentID, JobCodeID, PayCodeGroupID
	END

	-- Projected hours should vary by working hours for fixed JobCodes 
	UPDATE
		fs
	SET
		InitialBudgetHours01 = psfv.InitialBudget01,
		InitialBudgetHours02 = psfv.InitialBudget02,
		InitialBudgetHours03 = psfv.InitialBudget03,
		InitialBudgetHours04 = psfv.InitialBudget04,
		InitialBudgetHours05 = psfv.InitialBudget05,
		InitialBudgetHours06 = psfv.InitialBudget06,
		InitialBudgetHours07 = psfv.InitialBudget07,
		InitialBudgetHours08 = psfv.InitialBudget08,
		InitialBudgetHours09 = psfv.InitialBudget09,
		InitialBudgetHours10 = psfv.InitialBudget10,
		InitialBudgetHours11 = psfv.InitialBudget11,
		InitialBudgetHours12 = psfv.InitialBudget12,
		InitialProjectionHours01 = psfv.InitialProjection01,
		InitialProjectionHours02 = psfv.InitialProjection02,
		InitialProjectionHours03 = psfv.InitialProjection03,
		InitialProjectionHours04 = psfv.InitialProjection04,
		InitialProjectionHours05 = psfv.InitialProjection05,
		InitialProjectionHours06 = psfv.InitialProjection06,
		InitialProjectionHours07 = psfv.InitialProjection07,
		InitialProjectionHours08 = psfv.InitialProjection08,
		InitialProjectionHours09 = psfv.InitialProjection09,
		InitialProjectionHours10 = psfv.InitialProjection10,
		InitialProjectionHours11 = psfv.InitialProjection11,
		InitialProjectionHours12 = psfv.InitialProjection12
	FROM [fp].[Staffing] fs 
		INNER JOIN #preSpreadFixedVar psfv on fs.StaffingID = psfv.StaffingID -- we need this because we need the actual values for months loaded projection unfortunately
	WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID 
		AND fs.ProductiveClassID != 4 -- Ignore Dollars Only
		
	UPDATE fte SET         
	 	fte.InitialBudgetFTEs01 = fte.InitialBudgetHours01 / h.Month01,
	 	fte.InitialBudgetFTEs02 = fte.InitialBudgetHours02 / h.Month02,
	 	fte.InitialBudgetFTEs03 = fte.InitialBudgetHours03 / h.Month03,
	 	fte.InitialBudgetFTEs04 = fte.InitialBudgetHours04 / h.Month04,
	 	fte.InitialBudgetFTEs05 = fte.InitialBudgetHours05 / h.Month05,
	 	fte.InitialBudgetFTEs06 = fte.InitialBudgetHours06 / h.Month06,
	 	fte.InitialBudgetFTEs07 = fte.InitialBudgetHours07 / h.Month07,
	 	fte.InitialBudgetFTEs08 = fte.InitialBudgetHours08 / h.Month08,
	 	fte.InitialBudgetFTEs09 = fte.InitialBudgetHours09 / h.Month09,
	 	fte.InitialBudgetFTEs10 = fte.InitialBudgetHours10 / h.Month10,
	 	fte.InitialBudgetFTEs11 = fte.InitialBudgetHours11 / h.Month11,
	 	fte.InitialBudgetFTEs12 = fte.InitialBudgetHours12 / h.Month12,  
		fte.InitialProjectionFTEs01 = fte.InitialProjectionHours01 / pwh.Month01,
		fte.InitialProjectionFTEs02 = fte.InitialProjectionHours02 / pwh.Month02,
		fte.InitialProjectionFTEs03 = fte.InitialProjectionHours03 / pwh.Month03,
		fte.InitialProjectionFTEs04 = fte.InitialProjectionHours04 / pwh.Month04,
		fte.InitialProjectionFTEs05 = fte.InitialProjectionHours05 / pwh.Month05,
		fte.InitialProjectionFTEs06 = fte.InitialProjectionHours06 / pwh.Month06,
		fte.InitialProjectionFTEs07 = fte.InitialProjectionHours07 / pwh.Month07,
		fte.InitialProjectionFTEs08 = fte.InitialProjectionHours08 / pwh.Month08,
		fte.InitialProjectionFTEs09 = fte.InitialProjectionHours09 / pwh.Month09,
		fte.InitialProjectionFTEs10 = fte.InitialProjectionHours10 / pwh.Month10,
		fte.InitialProjectionFTEs11 = fte.InitialProjectionHours11 / pwh.Month11,
		fte.InitialProjectionFTEs12 = fte.InitialProjectionHours12 / pwh.Month12 
    FROM [fp].[Staffing] fte		
		INNER JOIN #BudgetWorkingHours h ON h.StaffingID = fte.StaffingID -- we can use StaffingID now instead of all the dimensionality since it's the same row
  		INNER JOIN #ProjectionWorkingHours pwh ON pwh.StaffingID = fte.StaffingID 
 		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON h.PayCodeGroupID = exc.PayCodeGroupID
	WHERE fte.EntityGroupConfigID = @EntityGroupConfigID 
		AND exc.PayCodeGroupID IS NULL

	------ Dollars ----------------------------------------------------
	UPDATE
		fs
	SET
		fs.InitialBudgetDollars01 = fs.InitialBudgetHours01 * wr.InitialBudget01,
		fs.InitialBudgetDollars02 = fs.InitialBudgetHours02 * wr.InitialBudget02,
		fs.InitialBudgetDollars03 = fs.InitialBudgetHours03 * wr.InitialBudget03,
		fs.InitialBudgetDollars04 = fs.InitialBudgetHours04 * wr.InitialBudget04,
		fs.InitialBudgetDollars05 = fs.InitialBudgetHours05 * wr.InitialBudget05,
		fs.InitialBudgetDollars06 = fs.InitialBudgetHours06 * wr.InitialBudget06,
		fs.InitialBudgetDollars07 = fs.InitialBudgetHours07 * wr.InitialBudget07,
		fs.InitialBudgetDollars08 = fs.InitialBudgetHours08 * wr.InitialBudget08,
		fs.InitialBudgetDollars09 = fs.InitialBudgetHours09 * wr.InitialBudget09,
		fs.InitialBudgetDollars10 = fs.InitialBudgetHours10 * wr.InitialBudget10,
		fs.InitialBudgetDollars11 = fs.InitialBudgetHours11 * wr.InitialBudget11,
		fs.InitialBudgetDollars12 = fs.InitialBudgetHours12 * wr.InitialBudget12, 
		fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN psfv.InitialProjection01 ELSE fs.InitialProjectionHours01 * wr.InitialProjection01 END,
		fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN psfv.InitialProjection02 ELSE fs.InitialProjectionHours02 * wr.InitialProjection02 END,
		fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN psfv.InitialProjection03 ELSE fs.InitialProjectionHours03 * wr.InitialProjection03 END,
		fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN psfv.InitialProjection04 ELSE fs.InitialProjectionHours04 * wr.InitialProjection04 END,
		fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN psfv.InitialProjection05 ELSE fs.InitialProjectionHours05 * wr.InitialProjection05 END,
		fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN psfv.InitialProjection06 ELSE fs.InitialProjectionHours06 * wr.InitialProjection06 END,
		fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN psfv.InitialProjection07 ELSE fs.InitialProjectionHours07 * wr.InitialProjection07 END,
		fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN psfv.InitialProjection08 ELSE fs.InitialProjectionHours08 * wr.InitialProjection08 END,
		fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN psfv.InitialProjection09 ELSE fs.InitialProjectionHours09 * wr.InitialProjection09 END,
		fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE fs.InitialProjectionHours10 * wr.InitialProjection10 END,
		fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE fs.InitialProjectionHours11 * wr.InitialProjection11 END,
		fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE fs.InitialProjectionHours12 * wr.InitialProjection12 END 
	FROM [fp].[Staffing] fs 
		INNER JOIN fp.StaffingWageRate wr on fs.StaffingWageRateID = wr.StaffingWageRateID
		INNER JOIN #preSpreadFixedVarDollars psfv  -- we need this unfortunately because we need the actual values for months loaded projection 
 			ON psfv.StaffingID = fs.StaffingID 
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.ProductiveClassID <> 4 -- exclude 'Dollars-Only'
		AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	
	-- now update dollars-only productive class 
	DELETE FROM #spreadFixedVar

	INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, 
		 ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, 
		 SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, 
		 SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12)
	SELECT
		 fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		 fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
		 SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, 
		 SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, 
		 SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, 
		 SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, 
		 SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, 
		 SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, 
		 SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, 
		 SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, 
		 SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, 
		 SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, 
		 SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, 
		 SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, 
		 SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12
    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID         
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.ProductiveClassID = 4 -- 'Dollars-Only'
    	AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID

	INSERT INTO #spreadFixedVar (StaffingID, 
						InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,	InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,	InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
						InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		 fs.StaffingID, 
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05,
		 CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11,
         CASE WHEN fs.VariabilityID = 1                                                                                                                                                     
								  THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
							      ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
						          END as InitialBudgetDollars12,	
	    CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12
    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID    
		 INNER JOIN #combinedStaffingDollarsAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID    
         LEFT JOIN #Variability fv ON 
				fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.EmployeeID = fs.EmployeeID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.ProductiveClassID = 4 -- 'Dollars-Only'
    	AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID)  -- exclude provider
    
	IF @IsDebug = 1
	BEGIN
		SELECT '#combinedStaffingDollarsAboveVariability', * FROM #combinedStaffingDollarsAboveVariability
		SELECT '#spreadFixedVar - Dollars', * FROM #spreadFixedVar
	END

	TRUNCATE TABLE #combinedStaffingDollarsAboveVariability;

    --------------------------- Provider Line Item variability ---------------------------	
	
	INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, 
		 ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, 
		 SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, 
		 SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12)
	SELECT
		 fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		 fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,
		 SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, 
		 SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, 
		 SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, 
		 SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, 
		 SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, 
		 SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, 
		 SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, 
		 SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, 
		 SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, 
		 SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, 
		 SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, 
		 SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, 
		 SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12
    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID         
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
    	AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID)  --  provider
	GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, 
		fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID

	INSERT INTO #spreadFixedVar (StaffingID, 
						InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04,	InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08,	InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
						InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04,	InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08,	InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)
	SELECT
		 fs.StaffingID, 
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10,
         CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11,
         CASE WHEN fs.VariabilityID = 1                                                                                                                       
								  THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
							      ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) +
						       		(total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) 
						          END as InitialBudgetDollars12,	
	    CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01,	
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11,
        CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12
    FROM [fp].[Staffing] fs
	     INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID   
		 INNER JOIN #combinedStaffingDollarsAboveVariability total ON
				fs.DepartmentID = total.DepartmentID
			AND fs.JobCodeID = total.JobCodeID
			AND fs.PayCodeGroupID = total.PayCodeGroupID
			AND fs.EmployeeID = total.EmployeeID
			AND fs.ProductiveClassID = total.ProductiveClassID
			AND fs.EntityGroupConfigID = total.EntityGroupConfigID
			AND fs.ProviderID = total.ProviderID
			AND fs.ProviderTypeID = total.ProviderTypeID
			AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID
			AND fs.ProviderLineItemID = total.ProviderLineItemID
			AND fs.SubsectionID = total.SubsectionID   
         LEFT JOIN #Variability fv   -- if this is a filtered call, filtering was done here
            ON fv.DepartmentID = fs.DepartmentID 
            AND fv.JobCodeID = fs.JobCodeID
            AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.ProviderLineItemID = fs.ProviderLineItemID
			AND fv.EmployeeID = fs.EmployeeID
	WHERE 
    	fs.EntityGroupConfigID = @EntityGroupConfigID 
    	AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID)  --  provider
			
	IF @IsDebug = 1
	BEGIN
		SELECT '#combinedStaffingDollarsAboveVariability - Provider Line Item variability', * FROM #combinedStaffingDollarsAboveVariability
		SELECT '#spreadFixedVar - Provider Line Item variability', * FROM #spreadFixedVar
	END

	-- update initial budget for dollars
	UPDATE fs
	SET
		fs.InitialBudgetDollars01 = sfv.InitialBudget01,
		fs.InitialBudgetDollars02 = sfv.InitialBudget02,
		fs.InitialBudgetDollars03 = sfv.InitialBudget03,
		fs.InitialBudgetDollars04 = sfv.InitialBudget04,
		fs.InitialBudgetDollars05 = sfv.InitialBudget05,
		fs.InitialBudgetDollars06 = sfv.InitialBudget06,
		fs.InitialBudgetDollars07 = sfv.InitialBudget07,
		fs.InitialBudgetDollars08 = sfv.InitialBudget08,
		fs.InitialBudgetDollars09 = sfv.InitialBudget09,
		fs.InitialBudgetDollars10 = sfv.InitialBudget10,
		fs.InitialBudgetDollars11 = sfv.InitialBudget11,
		fs.InitialBudgetDollars12 = sfv.InitialBudget12		
	FROM [fp].[Staffing] fs
		INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID	
		
	-- update initial projection for dollars
	UPDATE fs
	SET		
		fs.InitialProjectionDollars01 = sfv.InitialProjection01,
	    fs.InitialProjectionDollars02 = sfv.InitialProjection02,
	    fs.InitialProjectionDollars03 = sfv.InitialProjection03,
	    fs.InitialProjectionDollars04 = sfv.InitialProjection04,
	    fs.InitialProjectionDollars05 = sfv.InitialProjection05,
	    fs.InitialProjectionDollars06 = sfv.InitialProjection06,
	    fs.InitialProjectionDollars07 = sfv.InitialProjection07,
	    fs.InitialProjectionDollars08 = sfv.InitialProjection08,
	    fs.InitialProjectionDollars09 = sfv.InitialProjection09,
	    fs.InitialProjectionDollars10 = sfv.InitialProjection10,
	    fs.InitialProjectionDollars11 = sfv.InitialProjection11,
	    fs.InitialProjectionDollars12 = sfv.InitialProjection12
	FROM [fp].[Staffing] fs 
		INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID			
 
	-- Cleaning up records where flexMethod = 6 (Fixed) AND variabilityID = 2 (Variable)	
	UPDATE fs SET         
	 	fs.InitialBudgetFTEs01 = 0,
	 	fs.InitialBudgetFTEs02 = 0,
	 	fs.InitialBudgetFTEs03 = 0,
	 	fs.InitialBudgetFTEs04 = 0,
	 	fs.InitialBudgetFTEs05 = 0,
	 	fs.InitialBudgetFTEs06 = 0,
	 	fs.InitialBudgetFTEs07 = 0,
	 	fs.InitialBudgetFTEs08 = 0,
	 	fs.InitialBudgetFTEs09 = 0,
	 	fs.InitialBudgetFTEs10 = 0,
	 	fs.InitialBudgetFTEs11 = 0,
	 	fs.InitialBudgetFTEs12 = 0,  
		fs.InitialProjectionFTEs01 = 0,
		fs.InitialProjectionFTEs02 = 0,
		fs.InitialProjectionFTEs03 = 0,
		fs.InitialProjectionFTEs04 = 0,
		fs.InitialProjectionFTEs05 = 0,
		fs.InitialProjectionFTEs06 = 0,
		fs.InitialProjectionFTEs07 = 0,
		fs.InitialProjectionFTEs08 = 0,
		fs.InitialProjectionFTEs09 = 0,
		fs.InitialProjectionFTEs10 = 0,
		fs.InitialProjectionFTEs11 = 0,
		fs.InitialProjectionFTEs12 = 0,
		
		fs.TargetAdjustedFTEs01 = 0,
	 	fs.TargetAdjustedFTEs02 = 0,
	 	fs.TargetAdjustedFTEs03 = 0,
	 	fs.TargetAdjustedFTEs04 = 0,
	 	fs.TargetAdjustedFTEs05 = 0,
	 	fs.TargetAdjustedFTEs06 = 0,
	 	fs.TargetAdjustedFTEs07 = 0,
	 	fs.TargetAdjustedFTEs08 = 0,
	 	fs.TargetAdjustedFTEs09 = 0,
	 	fs.TargetAdjustedFTEs10 = 0,
	 	fs.TargetAdjustedFTEs11 = 0,
	 	fs.TargetAdjustedFTEs12 = 0, 
		fs.BudgetAdjustedFTEs01 = 0,
	 	fs.BudgetAdjustedFTEs02 = 0,
	 	fs.BudgetAdjustedFTEs03 = 0,
	 	fs.BudgetAdjustedFTEs04 = 0,
	 	fs.BudgetAdjustedFTEs05 = 0,
	 	fs.BudgetAdjustedFTEs06 = 0,
	 	fs.BudgetAdjustedFTEs07 = 0,
	 	fs.BudgetAdjustedFTEs08 = 0,
	 	fs.BudgetAdjustedFTEs09 = 0,
	 	fs.BudgetAdjustedFTEs10 = 0,
	 	fs.BudgetAdjustedFTEs11 = 0,
	 	fs.BudgetAdjustedFTEs12 = 0,

		fs.ProjectionAdjustedFTEs01 = 0,
		fs.ProjectionAdjustedFTEs02 = 0,
		fs.ProjectionAdjustedFTEs03 = 0,
		fs.ProjectionAdjustedFTEs04 = 0,
		fs.ProjectionAdjustedFTEs05 = 0,
		fs.ProjectionAdjustedFTEs06 = 0,
		fs.ProjectionAdjustedFTEs07 = 0,
		fs.ProjectionAdjustedFTEs08 = 0,
		fs.ProjectionAdjustedFTEs09 = 0,
		fs.ProjectionAdjustedFTEs10 = 0,
		fs.ProjectionAdjustedFTEs11 = 0,
		fs.ProjectionAdjustedFTEs12 = 0,
		fs.TargetFTEsPercentAdjustmentFactor01 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor02 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor03 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor04 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor05 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor06 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor07 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor08 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor09 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor10 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor11 = 0,
	 	fs.TargetFTEsPercentAdjustmentFactor12 = 0, 
		fs.BudgetFTEsPercentAdjustmentFactor01 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor02 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor03 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor04 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor05 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor06 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor07 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor08 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor09 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor10 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor11 = 0,
	 	fs.BudgetFTEsPercentAdjustmentFactor12 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor01 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor02 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor03 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor04 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor05 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor06 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor07 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor08 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor09 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor10 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor11 = 0,
		fs.ProjectionFTEsPercentAdjustmentFactor12 = 0,

		fs.InitialBudgetRate01 = 0,
	 	fs.InitialBudgetRate02 = 0,
	 	fs.InitialBudgetRate03 = 0,
	 	fs.InitialBudgetRate04 = 0,
	 	fs.InitialBudgetRate05 = 0,
	 	fs.InitialBudgetRate06 = 0,
	 	fs.InitialBudgetRate07 = 0,
	 	fs.InitialBudgetRate08 = 0,
	 	fs.InitialBudgetRate09 = 0,
	 	fs.InitialBudgetRate10 = 0,
	 	fs.InitialBudgetRate11 = 0,
	 	fs.InitialBudgetRate12 = 0, 
		fs.InitialProjectionRate01 = 0,
	 	fs.InitialProjectionRate02 = 0,
	 	fs.InitialProjectionRate03 = 0,
	 	fs.InitialProjectionRate04 = 0,
	 	fs.InitialProjectionRate05 = 0,
	 	fs.InitialProjectionRate06 = 0,
	 	fs.InitialProjectionRate07 = 0,
	 	fs.InitialProjectionRate08 = 0,
	 	fs.InitialProjectionRate09 = 0,
	 	fs.InitialProjectionRate10 = 0,
	 	fs.InitialProjectionRate11 = 0,
	 	fs.InitialProjectionRate12 = 0,
		fs.TargetAdjustedRate01 = 0,
	 	fs.TargetAdjustedRate02 = 0,
	 	fs.TargetAdjustedRate03 = 0,
	 	fs.TargetAdjustedRate04 = 0,
	 	fs.TargetAdjustedRate05 = 0,
	 	fs.TargetAdjustedRate06 = 0,
	 	fs.TargetAdjustedRate07 = 0,
	 	fs.TargetAdjustedRate08 = 0,
	 	fs.TargetAdjustedRate09 = 0,
	 	fs.TargetAdjustedRate10 = 0,
	 	fs.TargetAdjustedRate11 = 0,
	 	fs.TargetAdjustedRate12 = 0, 
		fs.BudgetAdjustedRate01 = 0,
	 	fs.BudgetAdjustedRate02 = 0,
	 	fs.BudgetAdjustedRate03 = 0,
	 	fs.BudgetAdjustedRate04 = 0,
	 	fs.BudgetAdjustedRate05 = 0,
	 	fs.BudgetAdjustedRate06 = 0,
	 	fs.BudgetAdjustedRate07 = 0,
	 	fs.BudgetAdjustedRate08 = 0,
	 	fs.BudgetAdjustedRate09 = 0,
	 	fs.BudgetAdjustedRate10 = 0,
	 	fs.BudgetAdjustedRate11 = 0,
	 	fs.BudgetAdjustedRate12 = 0,
		fs.ProjectionAdjustedRate01 = 0,
		fs.ProjectionAdjustedRate02 = 0,
		fs.ProjectionAdjustedRate03 = 0,
		fs.ProjectionAdjustedRate04 = 0,
		fs.ProjectionAdjustedRate05 = 0,
		fs.ProjectionAdjustedRate06 = 0,
		fs.ProjectionAdjustedRate07 = 0,
		fs.ProjectionAdjustedRate08 = 0,
		fs.ProjectionAdjustedRate09 = 0,
		fs.ProjectionAdjustedRate10 = 0,
		fs.ProjectionAdjustedRate11 = 0,
		fs.ProjectionAdjustedRate12 = 0
   FROM [fp].[Staffing] fs
		INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID
		LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID 
			AND fs.JobCodeID = v.JobCodeID 
			AND fs.PayCodeGroupID = v.PayCodeGroupID
			AND v.ProviderLineItemID = fs.ProviderLineItemID
			AND v.EmployeeID = fs.EmployeeID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
		AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL)
		AND fs.VariabilityID = 2  

 END;
GO


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

-- fp.procArchiveBenefitsData
CREATE PROCEDURE [fp].[procArchiveBenefitsData] 
    @budgetConfigID SMALLINT
AS
BEGIN
    SET NOCOUNT ON;

--    BEGIN TRANSACTION ArchiveBenefitsData;
--
--    BEGIN TRY
--
---- copy FactBenefits table
--
--        -- copy records
--		SET IDENTITY_INSERT [fp].[ArchiveFactBenefits] ON
--		INSERT INTO [fp].[ArchiveFactBenefits] ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12])
--		SElECT [BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12] FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactBenefits] WHERE [BudgetConfigID] = @budgetConfigID);
--        DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactBenefits] table.', 15, 1);
--        
--
---- copy FactBenefitsBudget table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactBenefitsBudget] ([BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT bdgt.[BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] 
--		FROM [fp].[FactBenefitsBudget] bdgt
--		INNER JOIN [fp].[ArchiveFactBenefits] gl ON bdgt.BenefitsID = gl.BenefitsID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactBenefitsBudget] bdgt
--			INNER JOIN [fp].[ArchiveFactBenefits] gl ON bdgt.BenefitsID = gl.BenefitsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--        
--		DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactBenefitsBudget] bdgt
--			INNER JOIN [fp].[FactBenefits] gl ON bdgt.BenefitsID = gl.BenefitsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactBenefitsBudget] table.', 15, 1);
--
--
--
---- copy FactBenefitsProjection table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactBenefitsProjection] ([BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT proj.[BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]
--		FROM [fp].[FactBenefitsProjection] proj
--		INNER JOIN [fp].[ArchiveFactBenefits] gl ON proj.BenefitsID = gl.BenefitsID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactBenefitsProjection] proj
--			INNER JOIN [fp].[ArchiveFactBenefits] gl ON proj.BenefitsID = gl.BenefitsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--       
--		DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactBenefitsProjection] proj
--			INNER JOIN [fp].[FactBenefits] gl ON proj.BenefitsID = gl.BenefitsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactBenefitsProjection] table.', 15, 1);
--
--
---- copy FactBenefitsHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactBenefitsHistory]([BenefitsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12])
--        SELECT
--            hist.[BenefitsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]
--	    FROM [fp].[FactBenefitsHistory] hist
--	    INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactBenefitsHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactBenefitsHistory] hist
--			INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalFactBenefitsHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[FactBenefitsHistory] hist
--            INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactBenefitsHistoryRecords <> @numberOfOriginalFactBenefitsHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactBenefitsHistory] table.', 15, 1);
--
---- copy BenefitsChangeHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveBenefitsChangeHistory]([BenefitsID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue])
--        SELECT
--           hist.[BenefitsID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]
--	    FROM [fp].[BenefitsChangeHistory] hist
--	    INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedBenefitsChangeHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveBenefitsChangeHistory] hist
--			INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalBenefitsChangeHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[BenefitsChangeHistory] hist
--            INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedBenefitsChangeHistoryRecords <> @numberOfOriginalBenefitsChangeHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[BenefitsChangeHistory] table.', 15, 1);
--
--
---- remove original data (FK will cascade deletes)
--        DELETE FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        IF EXISTS(SELECT 1 FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactBenefits] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactBenefitsBudget] bdgt INNER JOIN [fp].[FactBenefits] b ON bdgt.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactBenefitsBudget] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactBenefitsProjection] proj INNER JOIN [fp].[FactBenefits] b ON proj.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactBenefitsProjection] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[FactBenefitsHistory] hist INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactBenefitsHistory] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[BenefitsChangeHistory] hist INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[BenefitsChangeHistory] table.', 15, 2);
--
--
--        COMMIT TRANSACTION ArchiveBenefitsData;
--    END TRY
--    BEGIN CATCH
--        ROLLBACK TRANSACTION ArchiveBenefitsData;
--
--        DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
--        DECLARE @errorSeverity INT = ERROR_SEVERITY();
--        DECLARE @errorState INT = ERROR_STATE();
--
--        RAISERROR (@errorMessage, @errorSeverity, @errorState);
--    END CATCH
--
--RETURN;
END
GO


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

-- fp.procArchiveChargeVolumeData
CREATE PROCEDURE [fp].[procArchiveChargeVolumeData]
    @budgetConfigID SMALLINT
AS
BEGIN
    SET NOCOUNT ON;
--
--    BEGIN TRANSACTION ArchiveChargeVolumeData;
--
--    BEGIN TRY
--
--		-- copy FactChargeVolume table
--
--        -- copy records
--		SET IDENTITY_INSERT [fp].[ArchiveFactChargeVolume] ON
--		INSERT INTO [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12])
--		SElECT [ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12]
--		FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID);
--        DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactChargeVolume] table.', 15, 1);
--        
--
--		-- copy FactChargeVolumeBudget table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactChargeVolumeBudget] ([ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT bdgt.[ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]
--		FROM [fp].[FactChargeVolumeBudget] bdgt
--		INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactChargeVolumeBudget] bdgt
--			INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--        
--		DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactChargeVolumeBudget] bdgt
--			INNER JOIN [fp].[FactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactChargeVolumeBudget] table.', 15, 1);
--
--
--
--		-- copy FactChargeVolumeProjection table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactChargeVolumeProjection] ([ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT proj.[ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]
--		FROM [fp].[FactChargeVolumeProjection] proj
--		INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactChargeVolumeProjection] proj
--			INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--       
--		DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactChargeVolumeProjection] proj
--			INNER JOIN [fp].[FactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactChargeVolumeProjection] table.', 15, 1);
--
---- copy FactChargeVolumeHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactChargeVolumeHistory]([ChargeVolumeID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudgetValue01],[CurrentYearBudgetValue02],[CurrentYearBudgetValue03],[CurrentYearBudgetValue04],[CurrentYearBudgetValue05],[CurrentYearBudgetValue06],[CurrentYearBudgetValue07],[CurrentYearBudgetValue08],[CurrentYearBudgetValue09],[CurrentYearBudgetValue10],[CurrentYearBudgetValue11],[CurrentYearBudgetValue12])
--        SELECT
--            hist.[ChargeVolumeID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudgetValue01],[CurrentYearBudgetValue02],[CurrentYearBudgetValue03],[CurrentYearBudgetValue04],[CurrentYearBudgetValue05],[CurrentYearBudgetValue06],[CurrentYearBudgetValue07],[CurrentYearBudgetValue08],[CurrentYearBudgetValue09],[CurrentYearBudgetValue10],[CurrentYearBudgetValue11],[CurrentYearBudgetValue12]
--	    FROM [fp].[FactChargeVolumeHistory] hist
--	    INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactChargeVolumeHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactChargeVolumeHistory] hist
--			INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalFactChargeVolumeHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[FactChargeVolumeHistory] hist
--            INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactChargeVolumeHistoryRecords <> @numberOfOriginalFactChargeVolumeHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactChargeVolumeHistory] table.', 15, 1);
--
---- copy ChargeVolumeChangeHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveChargeVolumeChangeHistory]([ChargeVolumeID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue])
--        SELECT
--           hist.[ChargeVolumeID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]
--	    FROM [fp].[ChargeVolumeChangeHistory] hist
--	    INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedChargeVolumeChangeHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveChargeVolumeChangeHistory] hist
--			INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalChargeVolumeChangeHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[ChargeVolumeChangeHistory] hist
--            INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedChargeVolumeChangeHistoryRecords <> @numberOfOriginalChargeVolumeChangeHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[ChargeVolumeChangeHistory] table.', 15, 1);
--
--
--		-- remove original data (FK will cascade deletes)
--        DELETE FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactChargeVolume] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolumeBudget] bdgt INNER JOIN [fp].[FactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactChargeVolumeBudget] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolumeProjection] proj INNER JOIN [fp].[FactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactChargeVolumeProjection] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolumeHistory] hist INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactChargeVolumeHistory] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[ChargeVolumeChangeHistory] hist INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[ChargeVolumeChangeHistory] table.', 15, 2);
--
--        COMMIT TRANSACTION ArchiveChargeVolumeData;
--    END TRY
--    BEGIN CATCH
--        ROLLBACK TRANSACTION ArchiveChargeVolumeData;
--
--        DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
--        DECLARE @errorSeverity INT = ERROR_SEVERITY();
--        DECLARE @errorState INT = ERROR_STATE();
--
--        RAISERROR (@errorMessage, @errorSeverity, @errorState);
--    END CATCH
--
--RETURN;
END
GO


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

-- fp.procArchiveFactServiceLineData
CREATE PROCEDURE [fp].[procArchiveFactServiceLineData] 
    @budgetConfigID SMALLINT
AS
BEGIN
    SET NOCOUNT ON;
--
--    BEGIN TRANSACTION ArchiveServiceLineData;
--
--    BEGIN TRY
--
---- copy FactServiceLineEncounter table
--
--        -- copy records
--		SET IDENTITY_INSERT [fp].[ArchiveFactServiceLineEncounter] ON
--		INSERT INTO [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID],
--			[AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID], [AddDate],
--			[SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09],
--			[SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05],
--			[SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12], [InitialBudget01],
--			[InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10],
--			[InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06],
--			[InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12])
--		SElECT [ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID],
--			[AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID], [AddDate],
--			[SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09],
--			[SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05],
--			[SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12], [InitialBudget01],
--			[InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10],
--			[InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06],
--			[InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12]
--		FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID);
--        DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounter] table.', 15, 1);
--        
--
---- copy FactServiceLineEncounterBudget table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactServiceLineEncounterBudget] ([ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12])
--        SELECT bdgt.[ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12]
--		FROM [fp].[FactServiceLineEncounterBudget] bdgt
--			INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = (
--		SELECT COUNT(*) 
--		FROM [fp].[ArchiveFactServiceLineEncounterBudget] bdgt
--			INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID
--		WHERE [BudgetConfigID] = @budgetConfigID);
--        
--		DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = (
--		SELECT COUNT(*) 
--		FROM [fp].[FactServiceLineEncounterBudget] bdgt
--			INNER JOIN [fp].[FactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID
--		WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterBudget] table.', 15, 1);
--
--
--
---- copy FactServiceLineEncounterProjection table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactServiceLineEncounterProjection] ([ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12])
--        SELECT proj.[ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12]
--		FROM [fp].[FactServiceLineEncounterProjection] proj
--			INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = (
--		SELECT COUNT(*) 
--		FROM [fp].[ArchiveFactServiceLineEncounterProjection] proj
--			INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID
--		WHERE [BudgetConfigID] = @budgetConfigID);
--       
--		DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = (
--		SELECT COUNT(*) 
--		FROM [fp].[FactServiceLineEncounterProjection] proj
--			INNER JOIN [fp].[FactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID
--		WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterProjection] table.', 15, 1);
--
---- copy FactServiceLineEncounterHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactServiceLineEncounterHistory]([ServiceLineEncounterID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12])
--        SELECT
--            hist.[ServiceLineEncounterID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]
--	    FROM [fp].[FactServiceLineEncounterHistory] hist
--	    INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactServiceLineEncounterHistoryRecords INT = (
--		SELECT COUNT(*) 
--		FROM [fp].[ArchiveFactServiceLineEncounterHistory] hist
--			INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID
--		WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalFactServiceLineEncounterHistoryRecords INT = (
--        SELECT COUNT(*) 
--        FROM [fp].[FactServiceLineEncounterHistory] hist
--        	INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID
--        WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactServiceLineEncounterHistoryRecords <> @numberOfOriginalFactServiceLineEncounterHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterHistory] table.', 15, 1);
--
---- copy ServiceLineEncounterChangeHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveServiceLineEncounterChangeHistory]([ServiceLineEncounterID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue])
--        SELECT
--           hist.[ServiceLineEncounterID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]
--	    FROM [fp].[ServiceLineEncounterChangeHistory] hist
--	    	INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID;
--
--        -- ensure all records were copied
--        DECLARE @numberOfArchivedServiceLineEncounterChangeHistoryRecords INT = (
--		SELECT COUNT(*) 
--		FROM [fp].[ArchiveServiceLineEncounterChangeHistory] hist
--			INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID
--		WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalServiceLineEncounterChangeHistoryRecords INT = (
--        SELECT COUNT(*) 
--        FROM [fp].[ServiceLineEncounterChangeHistory] hist
--        	INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID
--        WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedServiceLineEncounterChangeHistoryRecords <> @numberOfOriginalServiceLineEncounterChangeHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[ServiceLineEncounterChangeHistory] table.', 15, 1);
--
--		-- remove original data (FK will cascade deletes)
--        DELETE FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounter] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterBudget] bdgt INNER JOIN [fp].[FactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterBudget] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterProjection] proj INNER JOIN [fp].[FactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterProjection] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterHistory] hist INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterHistory] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[ServiceLineEncounterChangeHistory] hist INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[ServiceLineEncounterChangeHistory] table.', 15, 2);
--
--        COMMIT TRANSACTION ArchiveServiceLineData;
--    END TRY
--    BEGIN CATCH
--        ROLLBACK TRANSACTION ArchiveServiceLineData;
--
--        DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
--        DECLARE @errorSeverity INT = ERROR_SEVERITY();
--        DECLARE @errorState INT = ERROR_STATE();
--
--        RAISERROR (@errorMessage, @errorSeverity, @errorState);
--    END CATCH
--
--RETURN;
END
GO


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

-- fp.procArchiveGeneralLedgerData
CREATE PROCEDURE [fp].[procArchiveGeneralLedgerData] 
    @budgetConfigID SMALLINT
AS
BEGIN
    SET NOCOUNT ON;
--
--    BEGIN TRANSACTION ArchiveGeneralLedgerData;
--
--    BEGIN TRY
--
---- copy FactGeneralLedger table
--
--        -- copy records
--		SET IDENTITY_INSERT [fp].[ArchiveFactGeneralLedger] ON
--		INSERT INTO [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID], [APEModelSectionID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12])
--		SElECT [GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID], [APEModelSectionID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12] FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID);
--        DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactGeneralLedger] table.', 15, 1);
--        
--
---- copy FactGeneralLedgerBudget table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactGeneralLedgerBudget] ([GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12],  [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12])
--        SELECT bdgt.[GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12], [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12] 
--		FROM [fp].[FactGeneralLedgerBudget] bdgt
--		INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactGeneralLedgerBudget] bdgt
--			INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--        
--		DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactGeneralLedgerBudget] bdgt
--			INNER JOIN [fp].[FactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactGeneralLedgerBudget] table.', 15, 1);
--
--
--
---- copy FactGeneralLedgerProjection table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactGeneralLedgerProjection] ([GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12], [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12])
--        SELECT proj.[GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12], [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12] 
--		FROM [fp].[FactGeneralLedgerProjection] proj
--		INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactGeneralLedgerProjection] proj
--			INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--       
--		DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactGeneralLedgerProjection] proj
--			INNER JOIN [fp].[FactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactGeneralLedgerProjection] table.', 15, 1);
--
---- copy FactGeneralLedgerHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactGeneralLedgerHistory]([GeneralLedgerID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12])
--        SELECT
--            hist.[GeneralLedgerID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]
--	    FROM [fp].[FactGeneralLedgerHistory] hist
--	    INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactGeneralLedgerHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactGeneralLedgerHistory] hist
--			INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalFactGeneralLedgerHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[FactGeneralLedgerHistory] hist
--            INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactGeneralLedgerHistoryRecords <> @numberOfOriginalFactGeneralLedgerHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactGeneralLedgerHistory] table.', 15, 1);
--
---- copy GeneralLedgerChangeHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveGeneralLedgerChangeHistory]([GeneralLedgerID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue])
--        SELECT
--           hist.[GeneralLedgerID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]
--	    FROM [fp].[GeneralLedgerChangeHistory] hist
--	    INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedGeneralLedgerChangeHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveGeneralLedgerChangeHistory] hist
--			INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalGeneralLedgerChangeHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[GeneralLedgerChangeHistory] hist
--            INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedGeneralLedgerChangeHistoryRecords <> @numberOfOriginalGeneralLedgerChangeHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[GeneralLedgerChangeHistory] table.', 15, 1);
--
--
---- remove original data (FK will cascade deletes)
--        DELETE FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactGeneralLedger] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedgerBudget] bdgt INNER JOIN [fp].[FactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactGeneralLedgerBudget] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedgerProjection] proj INNER JOIN [fp].[FactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactGeneralLedgerProjection] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedgerHistory] hist INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactGeneralLedgerHistory] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[GeneralLedgerChangeHistory] hist INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[GeneralLedgerChangeHistory] table.', 15, 2);
--
--        COMMIT TRANSACTION ArchiveGeneralLedgerData;
--    END TRY
--    BEGIN CATCH
--        ROLLBACK TRANSACTION ArchiveGeneralLedgerData;
--
--        DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
--        DECLARE @errorSeverity INT = ERROR_SEVERITY();
--        DECLARE @errorState INT = ERROR_STATE();
--
--        RAISERROR (@errorMessage, @errorSeverity, @errorState);
--    END CATCH
--
--RETURN;
END
GO


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

-- fp.procArchiveServiceLineData
CREATE PROCEDURE [fp].[procArchiveServiceLineData] 
    @budgetConfigID SMALLINT
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRANSACTION ArchiveServiceLineData;

    BEGIN TRY

-- copy FactServiceLineEncounterBasis table

        -- copy records
        INSERT INTO [fp].[ArchiveFactServiceLineEncounterBasis] ([BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ActualEncounters], [YTDEncounters], [BaseEncounters], [ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12], [ValueAnnualOriginal], [ChangeHistoryGUID])
        SELECT [BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ActualEncounters], [YTDEncounters], [BaseEncounters], [ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12], [ValueAnnualOriginal], [ChangeHistoryGUID] FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID;

        -- ensure all record were copied
        DECLARE @numberOfArchivedServiceLineEncounterBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID);
        DECLARE @numberOfOriginalServiceLineEncounterBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID);

        IF (@numberOfArchivedServiceLineEncounterBasisRecords <> @numberOfOriginalServiceLineEncounterBasisRecords)
            RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterBasis] table.', 15, 1);

        -- remove original data
        DELETE FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID;

        IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID)
            RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterBasis] table.', 15, 2);

        COMMIT TRANSACTION ArchiveServiceLineData;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION ArchiveServiceLineData;

        DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
        DECLARE @errorSeverity INT = ERROR_SEVERITY();
        DECLARE @errorState INT = ERROR_STATE();

        RAISERROR (@errorMessage, @errorSeverity, @errorState);
    END CATCH

RETURN;
END
GO


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

-- fp.procArchiveStaffingData
CREATE PROCEDURE [fp].[procArchiveStaffingData]
    @budgetConfigID SMALLINT
AS
BEGIN
	SET NOCOUNT ON;
--    BEGIN TRANSACTION ArchiveStaffingData;
--
--    BEGIN TRY
--
--		-- copy FactStaffing table
--
--        -- copy records
--		SET IDENTITY_INSERT [fp].[ArchiveFactStaffing] ON
--		INSERT INTO [fp].[ArchiveFactStaffing] ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12])
--		SElECT [StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12]
--		FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactStaffingBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactStaffing] WHERE [BudgetConfigID] = @budgetConfigID);
--        DECLARE @numberOfOriginalFactStaffingBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactStaffingBasisRecords <> @numberOfOriginalFactStaffingBasisRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStaffing] table.', 15, 1);
--        
--
--		-- copy FactStaffingBudget table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactStaffingBudget] ([StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT bdgt.[StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]
--		FROM [fp].[FactStaffingBudget] bdgt
--		INNER JOIN [fp].[ArchiveFactStaffing] st ON bdgt.StaffingID = st.StaffingID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactStaffingBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactStaffingBudget] bdgt
--			INNER JOIN [fp].[ArchiveFactStaffing] st ON bdgt.StaffingID = st.StaffingID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--        
--		DECLARE @numberOfOriginalFactStaffingBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactStaffingBudget] bdgt
--			INNER JOIN [fp].[FactStaffing] st ON bdgt.StaffingID = st.StaffingID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactStaffingBasisResultRecords <> @numberOfOriginalFactStaffingBasisResultRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStaffingBudget] table.', 15, 1);
--
--
--
--		-- copy FactStaffingProjection table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactStaffingProjection] ([StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT proj.[StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]
--		FROM [fp].[FactStaffingProjection] proj
--		INNER JOIN [fp].[ArchiveFactStaffing] st ON proj.StaffingID = st.StaffingID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactStaffingBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactStaffingProjection] proj
--			INNER JOIN [fp].[ArchiveFactStaffing] st ON proj.StaffingID = st.StaffingID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--       
--		DECLARE @numberOfOriginalFactStaffingBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactStaffingProjection] proj
--			INNER JOIN [fp].[FactStaffing] st ON proj.StaffingID = st.StaffingID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactStaffingBasisProjectionRecords <> @numberOfOriginalFactStaffingBasisProjectionRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStaffingProjection] table.', 15, 1);
--
---- copy FactStaffingHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactStaffingHistory]([StaffingID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12])
--        SELECT
--            hist.[StaffingID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]
--	    FROM [fp].[FactStaffingHistory] hist
--	    INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactStaffingHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactStaffingHistory] hist
--			INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalFactStaffingHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[FactStaffingHistory] hist
--            INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactStaffingHistoryRecords <> @numberOfOriginalFactStaffingHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStaffingHistory] table.', 15, 1);
--
---- copy StaffingChangeHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveStaffingChangeHistory]([StaffingID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue])
--        SELECT
--           hist.[StaffingID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]
--	    FROM [fp].[StaffingChangeHistory] hist
--	    INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedStaffingChangeHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveStaffingChangeHistory] hist
--			INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalStaffingChangeHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[StaffingChangeHistory] hist
--            INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedStaffingChangeHistoryRecords <> @numberOfOriginalStaffingChangeHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[StaffingChangeHistory] table.', 15, 1);
--
--
--		-- remove original data (FK will cascade deletes)
--        DELETE FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        IF EXISTS(SELECT 1 FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStaffing] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactStaffingBudget] bdgt INNER JOIN [fp].[FactStaffing] st ON bdgt.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStaffingBudget] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactStaffingProjection] proj INNER JOIN [fp].[FactStaffing] st ON proj.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStaffingProjection] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[FactStaffingHistory] hist INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStaffingHistory] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[StaffingChangeHistory] hist INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[StaffingChangeHistory] table.', 15, 2);
--
--
--        COMMIT TRANSACTION ArchiveStaffingData;
--    END TRY
--    BEGIN CATCH
--        ROLLBACK TRANSACTION ArchiveStaffingData;
--
--        DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
--        DECLARE @errorSeverity INT = ERROR_SEVERITY();
--        DECLARE @errorState INT = ERROR_STATE();
--
--        RAISERROR (@errorMessage, @errorSeverity, @errorState);
--    END CATCH
--
--RETURN;
END
GO


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

-- fp.procArchiveStatisticsData
CREATE PROCEDURE [fp].[procArchiveStatisticsData]
    @budgetConfigID SMALLINT
AS
BEGIN
    SET NOCOUNT ON;

--    BEGIN TRANSACTION ArchiveStatisticsData;
--
--    BEGIN TRY
--
--		-- copy FactStatistics table
--
--        -- copy records
--		SET IDENTITY_INSERT [fp].[ArchiveFactStatistics] ON
--		INSERT INTO [fp].[ArchiveFactStatistics] ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [PayorID], [FinancialReportingID], [AccountID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12])
--		SElECT [StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [PayorID], [FinancialReportingID], [AccountID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12]
--		FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactStatistics] WHERE [BudgetConfigID] = @budgetConfigID);
--        DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStatistics] table.', 15, 1);
--        
--
--		-- copy FactStatisticsBudget table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactStatisticsBudget] ([StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT bdgt.[StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]
--		FROM [fp].[FactStatisticsBudget] bdgt
--		INNER JOIN [fp].[ArchiveFactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactStatisticsBudget] bdgt
--			INNER JOIN [fp].[ArchiveFactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--        
--		DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactStatisticsBudget] bdgt
--			INNER JOIN [fp].[FactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStatisticsBudget] table.', 15, 1);
--
--
--
--		-- copy FactStatisticsProjection table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactStatisticsProjection] ([StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
--        SELECT proj.[StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]
--		FROM [fp].[FactStatisticsProjection] proj
--		INNER JOIN [fp].[ArchiveFactStatistics] stat ON proj.StatisticsID = stat.StatisticsID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactStatisticsProjection] proj
--			INNER JOIN [fp].[ArchiveFactStatistics] stat ON proj.StatisticsID = stat.StatisticsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--       
--		DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[FactStatisticsProjection] proj
--			INNER JOIN [fp].[FactStatistics] stat ON proj.StatisticsID = stat.StatisticsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStatisticsProjection] table.', 15, 1);
--
---- copy FactStatisticsHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveFactStatisticsHistory]([StatisticsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12])
--        SELECT
--            hist.[StatisticsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12],
--            [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12],
--            [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]
--	    FROM [fp].[FactStatisticsHistory] hist
--	    INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID;
--
--        -- ensure all record were copied
--        DECLARE @numberOfArchivedFactStatisticsHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveFactStatisticsHistory] hist
--			INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalFactStatisticsHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[FactStatisticsHistory] hist
--            INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedFactStatisticsHistoryRecords <> @numberOfOriginalFactStatisticsHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[FactStatisticsHistory] table.', 15, 1);
--
---- copy StatisticsChangeHistory table
--
--        -- copy records
--        INSERT INTO [fp].[ArchiveStatisticsChangeHistory]([StatisticsID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue])
--        SELECT
--           hist.[StatisticsID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]
--	    FROM [fp].[StatisticsChangeHistory] hist
--	    INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID;
--
--        -- ensure all records were copied
--        DECLARE @numberOfArchivedStatisticsChangeHistoryRecords INT = (
--			SELECT COUNT(*) 
--			FROM [fp].[ArchiveStatisticsChangeHistory] hist
--			INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID
--			WHERE [BudgetConfigID] = @budgetConfigID);
--
--        DECLARE @numberOfOriginalStatisticsChangeHistoryRecords INT = (
--            SELECT COUNT(*) 
--            FROM [fp].[StatisticsChangeHistory] hist
--            INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID
--            WHERE [BudgetConfigID] = @budgetConfigID);
--
--        IF (@numberOfArchivedStatisticsChangeHistoryRecords <> @numberOfOriginalStatisticsChangeHistoryRecords)
--            RAISERROR ('Not all records were archived from [fp].[StatisticsChangeHistory] table.', 15, 1);
--
--
--
--		-- remove original data (FK will cascade deletes)
--        DELETE FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID;
--
--        IF EXISTS(SELECT 1 FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStatistics] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactStatisticsBudget] bdgt INNER JOIN [fp].[FactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStatisticsBudget] table.', 15, 2);
--			
--		IF EXISTS(SELECT 1 FROM [fp].[FactStatisticsProjection] proj INNER JOIN [fp].[FactStatistics] stat ON proj.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStatisticsProjection] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[FactStatisticsHistory] hist INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[FactStatisticsHistory] table.', 15, 2);
--
--		IF EXISTS(SELECT 1 FROM [fp].[StatisticsChangeHistory] hist INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID)
--            RAISERROR ('Not all records were removed from [fp].[StatisticsChangeHistory] table.', 15, 2);
--
--
--        COMMIT TRANSACTION ArchiveStatisticsData;
--    END TRY
--    BEGIN CATCH
--        ROLLBACK TRANSACTION ArchiveStatisticsData;
--
--        DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE();
--        DECLARE @errorSeverity INT = ERROR_SEVERITY();
--        DECLARE @errorState INT = ERROR_STATE();
--
--        RAISERROR (@errorMessage, @errorSeverity, @errorState);
--    END CATCH
--
--RETURN;
END
GO


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

-- fp.procBenefitsApplySpread
CREATE PROCEDURE [fp].[procBenefitsApplySpread]
    @BudgetConfigID int,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

    /**************************************************************
    ** Change History
    **************************************************************
    ** CID  Date        Author  WI			Description
    ** 1    2019-03-19  AI      B-22404		Initial
	** 2    2019-07-09  VI      B-23668		Use viewBenefitsSpreads instead of fp.BenefitsSpreads
	** 3	2019-07-31	NL		D-08581		updating the way spread remainder is allocated (w/feature flag)
	** 4	2019-11-01	MY		B-24221		removing prevously added FF and making functionality always on
	** 5 	2022-08-09  JB  	JAZZ-23177	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
    *************************************************************/
  IF OBJECT_ID('tempdb..#tmpGL') IS NOT NULL DROP TABLE #tmpGL;
  IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
    CREATE TABLE #tmpGL (BenefitsID INT, DepartmentID INT, AccountID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

    IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
        BEGIN
            INSERT INTO #tmpGL (BenefitsID, DepartmentID, AccountID)
            SELECT DISTINCT basis.BenefitsID, basis.DepartmentID, basis.AccountID
            FROM [fp].[FactBenefits] basis
                     INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID
                     INNER JOIN [fp].[FactBenefitsBudget] bb ON basis.BenefitsID = bb.BenefitsID
            WHERE BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = 34 AND bb.LockType <> 5 AND bb.LockType <> 1
	END ELSE BEGIN
        INSERT INTO #tmpGL (BenefitsID, DepartmentID, AccountID)
        SELECT DISTINCT basis.BenefitsID, basis.DepartmentID, basis.AccountID
        FROM [fp].[FactBenefits] basis
                 INNER JOIN [fp].[FactBenefitsBudget] bb ON basis.BenefitsID = bb.BenefitsID
        WHERE BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = 34 AND bb.LockType <> 5 AND bb.LockType <> 1
    END
	
    UPDATE bb
    SET LockType = 6, LockFlag = 1
      	, AdjustedValue01 = CAST(AdjustedValueTotal * SpreadPercentage01 AS DECIMAL(19,8))
		, AdjustedValue02 = 
			CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
		, AdjustedValue03 = 
			CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
		, AdjustedValue04 = 
			CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
		, AdjustedValue05 = 
			CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
		, AdjustedValue06 = 
			CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
		, AdjustedValue07 = 
			CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
		, AdjustedValue08 = 
			CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
		, AdjustedValue09 = 
			CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
		, AdjustedValue10 = 
			CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
		, AdjustedValue11 = 
			CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
		, AdjustedValue12 = 
			CASE WHEN SpreadPercentage12 != 0
			THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
			ELSE CAST(AdjustedValueTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
    FROM
        [fp].[viewBenefitsSpreads] bs
            INNER JOIN [fp].[FactBenefits] b ON bs.BudgetConfigID = b.BudgetConfigID AND bs.DepartmentID = b.DepartmentID AND bs.AccountID = b.AccountID
            INNER JOIN #tmpGL tmp on b.BenefitsID = tmp.BenefitsID
            INNER JOIN [fp].[FactBenefitsBudget] bb on b.BenefitsID = bb.BenefitsID
    WHERE bb.BudgetPhaseID = 3
        AND bs.IsInactive = 0

	-- Unlock Spreads that are no longer active
    UPDATE bb
    SET LockType = 0, LockFlag = 0
    FROM
        [fp].[BenefitsSpreads] bs
            INNER JOIN [fp].[FactBenefits] b ON bs.BudgetConfigID = b.BudgetConfigID AND bs.DepartmentID = b.DepartmentID AND bs.AccountID = b.AccountID
            INNER JOIN #tmpGL tmp on b.BenefitsID = tmp.BenefitsID
            INNER JOIN [fp].[FactBenefitsBudget] bb on b.BenefitsID = bb.BenefitsID
    WHERE bb.BudgetPhaseID = 3
        AND bs.IsInactive = 1
        AND bb.LockFlag = 1
        AND bb.LockType = 6

END
GO


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

-- fp.procBenefitsCopyNewItems
CREATE PROCEDURE [fp].[procBenefitsCopyNewItems]
	@SourceBudgetConfigID INT,
	@SourceEntityGroupConfigID INT,
	@BudgetConfigID INT,
	@EntityGroupConfigID INT
AS 
BEGIN

	
INSERT INTO [fp].[FactBenefits] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, AddDate,
SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
IsNew)
SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, AddDate,
SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
IsNew
FROM [fp].[FactBenefits] 
WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1

END
GO


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

-- fp.procBudgetTargetSplitUpgrade
CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade
	@BudgetConfigID INT
AS
BEGIN
	
	IF EXISTS (
		SELECT TOP 1 1 FROM [fp].[StaffingAdjustment] adj
			INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID
		)
	BEGIN
		PRINT 'The upgrade has already been completed for this budget'
		RETURN;
	END

	IF EXISTS (
		SELECT TOP 1 1 FROM [fp].[GeneralLedgerAdjustment] adj
			INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID
		)
	BEGIN
		PRINT 'The upgrade has already been completed for this budget'
		RETURN;
	END
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'AdjustmentGrouping_PreSplitUpgrade'))
		DROP TABLE [bak].[AdjustmentGrouping_PreSplitUpgrade]
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StaffingAdjustment_PreSplitUpgrade'))
		DROP TABLE [bak].[StaffingAdjustment_PreSplitUpgrade]
		
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StaffingAdjustmentImport_PreSplitUpgrade'))
		DROP TABLE [bak].[StaffingAdjustmentImport_PreSplitUpgrade]
		
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StaffingBasisFlexRate_PreSplitUpgrade'))
		DROP TABLE [bak].[StaffingBasisFlexRate_PreSplitUpgrade]
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'FTERequest_PreSplitUpgrade'))
		DROP TABLE [bak].[FTERequest_PreSplitUpgrade]
		
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'FTERequestDetail_PreSplitUpgrade'))
		DROP TABLE [bak].[FTERequestDetail_PreSplitUpgrade]
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'GeneralLedgerAdjustment_PreSplitUpgrade'))
		DROP TABLE [bak].[GeneralLedgerAdjustment_PreSplitUpgrade]
		
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'GeneralLedgerAdjustmentImport_PreSplitUpgrade'))
		DROP TABLE [bak].[GeneralLedgerAdjustmentImport_PreSplitUpgrade]
	
	
	SELECT * INTO [bak].[AdjustmentGrouping_PreSplitUpgrade] FROM [fp].[AdjustmentGrouping]
	SELECT * INTO [bak].[StaffingAdjustment_PreSplitUpgrade] FROM [fp].[StaffingAdjustment]
	SELECT * INTO [bak].[StaffingAdjustmentImport_PreSplitUpgrade] FROM [fp].[StaffingAdjustmentImport]
	SELECT * INTO [bak].[StaffingBasisFlexRate_PreSplitUpgrade] FROM [fp].[StaffingBasisFlexRate]
	SELECT * INTO [bak].[FTERequest_PreSplitUpgrade] FROM [fp].[FTERequest]
	SELECT * INTO [bak].[FTERequestDetail_PreSplitUpgrade] FROM [fp].[FTERequestDetail]
	SELECT * INTO [bak].[GeneralLedgerAdjustment_PreSplitUpgrade] FROM [fp].[GeneralLedgerAdjustment]
	SELECT * INTO [bak].[GeneralLedgerAdjustmentImport_PreSplitUpgrade] FROM [fp].[GeneralLedgerAdjustmentImport]
	
	EXEC fp.procBudgetTargetSplitUpgrade_GeneralLedger @BudgetConfigID
	EXEC fp.procBudgetTargetSplitUpgrade_Staffing @BudgetConfigID
	
END
GO


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

-- fp.procBudgetTargetSplitUpgrade_Cleanup
CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade_Cleanup
	@BudgetConfigID INT
AS
BEGIN

	-- NOTE: This is for manual use only and used only in the event we need to roll back the upgrade for some reason. This will cleanup
	-- all adjustments in staffing and GL with the comment containing Target/Budget split
	
	SELECT adj.* 
	INTO #adjustmentsToCopy_Staffing
	FROM [fp].[StaffingAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE Comment LIKE '%Target/Budget Upgrade%'
		AND bc.BudgetConfigID = @BudgetConfigID
		
	DELETE data
	FROM [fp].[StaffingAdjustmentImport] data
		INNER JOIN #adjustmentsToCopy_Staffing adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	WHERE data.BudgetPhaseID = 3
	
	DELETE data
	FROM [fp].[StaffingBasisFlexRate] data
		INNER JOIN #adjustmentsToCopy_Staffing adj ON data.AdjustmentGUID = adj.AdjustmentGUID
		
	DELETE data 
	FROM [fp].[FTERequest] data
		INNER JOIN #adjustmentsToCopy_Staffing adj ON data.FTERequestGUID = adj.GroupingGUID
	
	DELETE data
	FROM [fp].[FTERequestDetail] data
		INNER JOIN #adjustmentsToCopy_Staffing adj ON data.FTERequestGUID = adj.GroupingGUID
	
	DELETE data
	FROM [fp].[StaffingAdjustment] data
		INNER JOIN #adjustmentsToCopy_Staffing adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	
	DELETE grp
	FROM [fp].[AdjustmentGrouping] grp
		INNER JOIN #adjustmentsToCopy_Staffing adj ON grp.GroupingGUID = adj.GroupingGUID 
		
	SELECT adj.* 
	INTO #adjustmentsToCopy_GeneralLedger
	FROM [fp].[GeneralLedgerAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE Comment LIKE '%Target/Budget Upgrade%'
		AND bc.BudgetConfigID = @BudgetConfigID
		
	DELETE data
	FROM [fp].[GeneralLedgerAdjustmentImport] data
		INNER JOIN #adjustmentsToCopy_GeneralLedger adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	WHERE data.BudgetPhaseID = 3
	
	DELETE data
	FROM [fp].[GeneralLedgerAdjustment] data
		INNER JOIN #adjustmentsToCopy_GeneralLedger adj ON data.AdjustmentGUID = adj.AdjustmentGUID	
		
	DELETE grp
	FROM [fp].[AdjustmentGrouping] grp
		INNER JOIN #adjustmentsToCopy_GeneralLedger adj ON grp.GroupingGUID = adj.GroupingGUID 
END
GO


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

-- fp.procBudgetTargetSplitUpgrade_Cleanup_Statistics
CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade_Cleanup_Statistics
	@BudgetConfigID INT
AS
BEGIN

	-- NOTE: This is for manual use only and used only in the event we need to roll back the upgrade for some reason. 

	IF OBJECT_ID('tempdb..#adjustmentsToCopy_Statistics') IS NOT NULL DROP TABLE #adjustmentsToCopy_Statistics
	
	SELECT adj.* 
	INTO #adjustmentsToCopy_Statistics
	FROM [fp].[StatisticsAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE Comment LIKE '%Target/Budget Upgrade%'
		AND bc.BudgetConfigID = @BudgetConfigID
	
	DELETE data
	FROM [fp].[StatisticsAdjustmentRate] data
		INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	WHERE data.BudgetPhaseID = 3

	DELETE data
	FROM [fp].[StatisticsAdjustmentImport] data
		INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	WHERE data.BudgetPhaseID = 3
	
	DELETE data
	FROM [fp].[StatisticAddProviderAdjustment] data
		INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	WHERE data.BudgetPhaseID = 3 AND data.TimeClassID = 2

	DELETE data
	FROM [fp].[StatisticsAdjustment] data
		INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	WHERE 
		adj.AdjustmentType <> 15 -- we don't need to delete add provider adjustments, only a comment update needed	
	
	UPDATE data
	SET Comment = REPLACE(data.Comment, 'Adjustment has been generated from the Target/Budget Upgrade.', ''),
	DateCreatedUTC = DATEADD(yy, +100, DateCreatedUTC) -- return the original date
	FROM [fp].[StatisticsAdjustment] data 
		INNER JOIN [fp].[BudgetConfig] bc ON data.BudgetConfigGUID = bc.BudgetConfigGUID 
		INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID
	WHERE BudgetConfigID = @BudgetConfigID
		AND data.AdjustmentType = 15
		AND data.Comment LIKE '%Adjustment has been generated from the Target/Budget Upgrade.%'
	
	DELETE grp
	FROM [fp].[AdjustmentGrouping] grp
		INNER JOIN #adjustmentsToCopy_Statistics adj ON grp.GroupingGUID = adj.GroupingGUID 
	WHERE adj.AdjustmentType <> 4
		
END
GO


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

-- fp.procBudgetTargetSplitUpgrade_GeneralLedger
CREATE PROCEDURE [fp].[procBudgetTargetSplitUpgrade_GeneralLedger]
	@BudgetConfigID INT,
	@IsDebug INT = 0
AS
BEGIN
	DECLARE @Message NVARCHAR(MAX) = 'Adjustment has been generated from the Target/Budget Upgrade.',
			@Spacing NVARCHAR(MAX) = '

'; -- I know this looks wierd, but leave it, it works.


	IF EXISTS (
		SELECT TOP 1 1 FROM [fp].[GeneralLedgerAdjustment] adj
			INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID
		)
	BEGIN
		PRINT 'The upgrade has already been completed for this budget'
		RETURN;
	END

	-- Get all of the adjustments we need to copy to Budget
	SELECT adj.*, adj.AdjustmentGUID AS OriginalAdjustmentGUID
	INTO #adjustmentsToCopy
	FROM [fp].[GeneralLedgerAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND BudgetPhaseID = 2 -- Imports do not use the budget phase property so we'll just need to make sure we copy those rows over later.
		AND TimeClassID = 2   -- We only need to copy budget adjustments, not projection
		AND AdjustmentType != 9 -- Spread unlocks can only happen to Budget, not target so we don't have to worry about these.
		AND AdjustmentType != 4 -- Just making sure the imports aren't included
		
	-- copy import adjustments to the table, we do these seperately because we only want target adjusted adjustments
	INSERT INTO #adjustmentsToCopy ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], 
			[Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], [IsRecordDeleted], [OriginalAdjustmentGUID])
	SELECT 
			adj.[AdjustmentGUID], adj.[BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], 
			[Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], adj.[BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], [IsRecordDeleted], adj.[AdjustmentGUID]
	FROM [fp].[GeneralLedgerAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN (SELECT DISTINCT AdjustmentGUID, BudgetPhaseID FROM [fp].[GeneralLedgerAdjustmentImport]) imp ON adj.AdjustmentGUID = imp.AdjustmentGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND imp.BudgetPhaseID = 2 -- We only want to copy imports that contain target adjustments
		AND adj.AdjustmentType = 4
		
	-- Get a list of all the unique groupingGuids. We'll then need to update these later
	SELECT DISTINCT GroupingGUID, NEWID() AS NewGroupingGUID
	INTO #groupings
	FROM #adjustmentsToCopy
	WHERE AdjustmentType != 4 -- We don't need to copy import because we're not creating seperate adjustments for these.
		AND GroupingGUID != '00000000-0000-0000-0000-000000000000'
		
	-- Create duplicate adjustment groupings
	SELECT  tmp.NewGroupingGUID, 
			Description = CASE WHEN LEN(TRIM(Description)) = 0 THEN @Message 
		 					   WHEN RIGHT(TRIM(Description), 1) != '.' THEN CONCAT(Description, CONCAT(CONCAT('. ', @Spacing), @Message))
		 					   ELSE CONCAT(Description, CONCAT(@Spacing, @Message)) END, 
			ExcelFile, 
			IsRecordDeleted
	INTO #newGroupings
	FROM [fp].[AdjustmentGrouping] grp
		INNER JOIN #groupings tmp ON grp.GroupingGUID = tmp.GroupingGUID
			
	-- Update the adjustments comment, phase, and date time so that they are before any final budget adjustments
	UPDATE #adjustmentsToCopy
	SET AdjustmentGUID = NEWID(),
		Comment = CASE  WHEN LEN(TRIM(Comment)) = 0 THEN @Message 
		 				WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message))
		 				ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) 
		END,
		BudgetPhaseID = 3,
		DateCreatedUtc = DATEADD(yy, -100, DateCreatedUtc), -- Descrease the current time by 100 years so we keep the rough date/time
		AdjustedProperty = CASE WHEN AdjustedProperty = 'CurrentBudget' THEN 'mgr' ELSE REPLACE(AdjustedProperty, 'm', 'mam') END
	
	-- Update the groupings for any existing groupings so we keep the adjustments together.
	UPDATE adj
	SET adj.GroupingGUID = grp.NewGroupingGUID
	FROM #adjustmentsToCopy adj
		INNER JOIN #groupings grp ON adj.GroupingGUID = grp.GroupingGUID
		
	-- Copy the target adjustments over to final budget for imports
	SELECT 
		adj.[AdjustmentGUID], [DepartmentID], [AccountID], [FinancialReportingID], imp.[FiscalYearID], imp.[UnitTypeID], [FiscalMonthID], 
		imp.[Value], [VariabilityID], [EntityID], imp.[TimeClassID], 3 AS BudgetPhaseID, imp.[IsRecordDeleted]
	INTO #newImportAdjustments
	FROM [fp].[GeneralLedgerAdjustmentImport] imp
		INNER JOIN #adjustmentsToCopy adj ON adj.OriginalAdjustmentGUID = imp.AdjustmentGUID
	WHERE imp.BudgetPhaseID = 2
		AND imp.TimeClassID = 2
		AND adj.AdjustmentType = 4
		
	IF @IsDebug = 1
	BEGIN
		
		SELECT 'New Groupings', * FROM #newGroupings
		SELECT 'New Imports', * FROM #newImportAdjustments
		SELECT 'New Adjustments', * FROM #adjustmentsToCopy
		
	END ELSE 
	BEGIN
	
		INSERT INTO [fp].[AdjustmentGrouping] ([GroupingGUID], [Description], [ExcelFile], [IsRecordDeleted])
		SELECT [NewGroupingGUID], [Description], [ExcelFile], [IsRecordDeleted]
		FROM #newGroupings		
	
		INSERT INTO [fp].[GeneralLedgerAdjustment] ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], 
			[Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], [IsRecordDeleted])
		SELECT
			[AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], 
			[LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], [IsRecordDeleted]
		FROM #adjustmentsToCopy	
		
		INSERT INTO [fp].[GeneralLedgerAdjustmentImport]([AdjustmentGUID], [DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], 
			[Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted])
		SELECT [AdjustmentGUID], [DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], 
			[Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted]
		FROM #newImportAdjustments			
	
	END
	
END;
GO


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

-- fp.procBudgetTargetSplitUpgrade_Staffing
CREATE PROCEDURE [fp].[procBudgetTargetSplitUpgrade_Staffing]
	@BudgetConfigID INT,
	@IsDebug INT = 0
AS
BEGIN
DECLARE @Message NVARCHAR(MAX) = 'Adjustment has been generated from the Target/Budget Upgrade.',
			@Spacing NVARCHAR(MAX) = '

'; -- I know this looks wierd, but leave it, it works.


	IF EXISTS (
		SELECT TOP 1 1 FROM [fp].[StaffingAdjustment] adj
			INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID
		)
	BEGIN
		PRINT 'The upgrade has already been completed for this budget'
		RETURN;
	END

	-- Get all of the adjustments we need to copy to Budget
	SELECT adj.*, adj.AdjustmentGUID AS OriginalAdjustmentGUID
	INTO #adjustmentsToCopy
	FROM [fp].[StaffingAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ((BudgetPhaseID = 2 AND TimeClassID = 2) OR AdjustmentType = 6) -- We need add fte and imports as well
		AND AdjustmentType != 9 -- Spread unlocks can only happen to Budget, not target so we don't have to worry about these.
		AND AdjustmentType != 4
		
	-- copy import adjustments to the table, we do these seperately because we only want target adjusted adjustments
	INSERT INTO #adjustmentsToCopy ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], 
			[Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], [IsRecordDeleted], [OriginalAdjustmentGUID], [ParentFilterJSON])
	SELECT 
		adj.[AdjustmentGUID], adj.[BudgetConfigGUID], [AdjustmentType], adj.[Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], 
			[Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], adj.[UnitTypeID], [GroupingGUID], adj.[TimeClassID], adj.[BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], adj.[IsRecordDeleted], adj.[AdjustmentGUID], [ParentFilterJSON]
	FROM [fp].[StaffingAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN (SELECT DISTINCT AdjustmentGUID, BudgetPhaseID FROM [fp].[StaffingAdjustmentImport]) imp ON adj.AdjustmentGUID = imp.AdjustmentGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND imp.BudgetPhaseID = 2 -- We only want to copy imports that contain target adjustments
		AND adj.AdjustmentType = 4
		
	-- Get a list of all the unique groupingGuids. We'll then need to update these later
	SELECT DISTINCT GroupingGUID, '00000000-0000-0000-0000-000000000000' AS NewGroupingGUID
	INTO #groupings
	FROM #adjustmentsToCopy
	WHERE GroupingGUID != '00000000-0000-0000-0000-000000000000'
			
	UPDATE #groupings SET NewGroupingGUID = NEWID();
			
	-- Create duplicate adjustment groupings
	SELECT  tmp.NewGroupingGUID, 
			Description = CASE WHEN LEN(TRIM(Description)) = 0 THEN @Message 
		 					   WHEN RIGHT(TRIM(Description), 1) != '.' THEN CONCAT(Description, CONCAT(CONCAT('. ', @Spacing), @Message))
		 					   ELSE CONCAT(Description, CONCAT(@Spacing, @Message)) END, 
			ExcelFile, 
			IsRecordDeleted
	INTO #newGroupings
	FROM [fp].[AdjustmentGrouping] grp
		INNER JOIN #groupings tmp ON grp.GroupingGUID = tmp.GroupingGUID
			
	-- Update the adjustments comment, phase, and date time so that they are before any final budget adjustments
	UPDATE #adjustmentsToCopy
	SET AdjustmentGUID = NEWID(),
		Comment = CASE  WHEN LEN(TRIM(Comment)) = 0 THEN @Message 
		 				WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message))
		 				ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) 
		END,
		BudgetPhaseID = 3,
		DateCreatedUtc = DATEADD(yy, -100, DateCreatedUtc), -- Descrease the current time by 100 years so we keep the rough date/time
		AdjustedProperty = CASE 
					WHEN AdjustedProperty LIKE 'CurrentBudget%' THEN REPLACE(AdjustedProperty, 'CurrentBudget', 'ManagerBudget') 
					WHEN AdjustedProperty LIKE 'f%' THEN REPLACE(AdjustedProperty, 'f', 'bf') 
					WHEN AdjustedProperty LIKE 'h%' THEN REPLACE(AdjustedProperty, 'h', 'bh') 
					WHEN AdjustedProperty LIKE 'd%' THEN REPLACE(AdjustedProperty, 'd', 'bd') 
					WHEN AdjustedProperty LIKE 'w%' THEN REPLACE(AdjustedProperty, 'w', 'bw') 
					ELSE AdjustedProperty
					END
	WHERE AdjustmentType != 8 -- Variable reset, these will need to be handled a bit differently
	
	------ VARIABLE SET ADJUSTMENTS - START -------
	
	-- Create new adjustmentGuids so we know what we need to populate, need the old one's so we know what we need to copy over and how to link them
	SELECT *, NEWID() AS NewAdjustmentGUID
	INTO #variableSetAdjustments
	FROM #adjustmentsToCopy
	WHERE AdjustmentType = 8
	
	-- Copy Basis Flex Rate table data
	SELECT flex.*, adj.NewAdjustmentGUID AS NewAdjustmentGUID -- The adjustment will get updated next
	INTO #variableSetAdjustmentsFlexRate
	FROM [fp].[StaffingBasisFlexRate] flex
		INNER JOIN #variableSetAdjustments adj ON flex.AdjustmentGUID = adj.AdjustmentGUID
		
	-- Update the adjustments for the variable set
	UPDATE adj
	SET adj.AdjustmentGUID = varAdj.NewAdjustmentGUID,
		adj.Comment = CASE  WHEN LEN(TRIM(adj.Comment)) = 0 THEN @Message 
		 				WHEN RIGHT(TRIM(adj.Comment), 1) != '.' THEN CONCAT(adj.Comment, CONCAT(CONCAT('. ', @Spacing), @Message))
		 				ELSE CONCAT(adj.Comment, CONCAT(@Spacing, @Message)) 
		END,
		adj.BudgetPhaseID = 3,
		adj.DateCreatedUtc = DATEADD(yy, -100, adj.DateCreatedUtc), -- Descrease the current time by 100 years so we keep the rough date/time
		adj.AdjustedProperty = CASE 
					WHEN adj.AdjustedProperty LIKE 'CurrentBudget%' THEN REPLACE(adj.AdjustedProperty, 'CurrentBudget', 'ManagerBudget') 
					WHEN adj.AdjustedProperty LIKE 'f%' THEN REPLACE(adj.AdjustedProperty, 'f', 'bf') 
					WHEN adj.AdjustedProperty LIKE 'h%' THEN REPLACE(adj.AdjustedProperty, 'h', 'bh') 
					WHEN adj.AdjustedProperty LIKE 'd%' THEN REPLACE(adj.AdjustedProperty, 'd', 'bd') 
					WHEN adj.AdjustedProperty LIKE 'w%' THEN REPLACE(adj.AdjustedProperty, 'w', 'bw') 
					ELSE adj.AdjustedProperty
					END
	FROM #adjustmentsToCopy adj
		INNER JOIN #variableSetAdjustments varAdj ON adj.AdjustmentGUID = varAdj.AdjustmentGUID
		
	------ VARIABLE SET ADJUSTMENTS - END -------
	
	-- Update the groupings for any existing groupings so we keep the adjustments together.
	UPDATE adj
	SET adj.GroupingGUID = grp.NewGroupingGUID
	FROM #adjustmentsToCopy adj
		INNER JOIN #groupings grp ON adj.GroupingGUID = grp.GroupingGUID

	------ ADD FTE - START -------
	
	-- Create new Requests
	SELECT [FTERequestGUID], NEWID() AS NewFTERequestGUID, fte.[BudgetConfigGUID], [DepartmentID], [JobCodeID], [FTEAmount], [StartFiscalMonthID], 
		[WageRate], [Comment], [DateCreatedUtc], grp.NewGroupingGUID AS GroupingGUID
	INTO #newFteRequests
	FROM [fp].[FTERequest] fte
		INNER JOIN fp.BudgetConfig bc ON fte.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN #groupings grp ON grp.GroupingGUID = fte.GroupingGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
	
	--  Create detail requests
	SELECT NEWID() AS FTERequestDetailGUID, req.[NewFTERequestGUID], [PayCodeGroupID], [HoursMix]
	INTO #newFteRequestDetails
	FROM [fp].[FTERequestDetail] detail
		INNER JOIN #newFteRequests req ON req.FTERequestGUID = detail.FTERequestGUID
	
	------ ADD FTE - END -------
		
	------ IMPORT - START -------
	
	-- Copy the target adjustments over to final budget for imports
	SELECT 
		adj.[AdjustmentGUID], [DepartmentID], [JobCodeID], [ProductiveClassID], [PayCodeGroupID], imp.[FiscalYearID], imp.[UnitTypeID], [FiscalMonthID], 
		imp.[Value], [VariabilityID], [EntityID], imp.[TimeClassID], 3 AS BudgetPhaseID, imp.[IsRecordDeleted]
	INTO #newImportAdjustments
	FROM [fp].[StaffingAdjustmentImport] imp
		INNER JOIN #adjustmentsToCopy adj ON imp.AdjustmentGUID = adj.OriginalAdjustmentGUID
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND imp.BudgetPhaseID = 2
		AND imp.TimeClassID = 2	-- We don't need to worry about Projection
		
	------ IMPORT - END -------
	
	IF @IsDebug = 1
	BEGIN
		
		SELECT 'New Groupings', * FROM #newGroupings
		SELECT 'New Imports', * FROM #newImportAdjustments
		SELECT 'New Adjustments', * FROM #adjustmentsToCopy
		SELECT 'New Variable Set Adjustments', * FROM #variableSetAdjustmentsFlexRate
		SELECT 'New FTE Request', * FROM #newFteRequests
		SELECT 'New FTE Request Details', * FROM #newFteRequestDetails
		
	END ELSE 
	BEGIN
	
		INSERT INTO [fp].[AdjustmentGrouping] ([GroupingGUID], [Description], [ExcelFile], [IsRecordDeleted])
		SELECT [NewGroupingGUID], [Description], [ExcelFile], [IsRecordDeleted]
		FROM #newGroupings		
	
		INSERT INTO [fp].[StaffingAdjustment] ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], 
			[Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], [IsRecordDeleted])
		SELECT
			[AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], 
			[LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], 
			[ClassificationCategoryID], [IsRecordDeleted]
		FROM #adjustmentsToCopy	
		
		INSERT INTO [fp].[StaffingAdjustmentImport]([AdjustmentGUID], [DepartmentID], [JobCodeID], [ProductiveClassID], [PayCodeGroupID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], 
			[Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted])
		SELECT [AdjustmentGUID], [DepartmentID], [JobCodeID], [ProductiveClassID], [PayCodeGroupID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], 
			[Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted]
		FROM #newImportAdjustments		
		
		INSERT INTO [fp].[StaffingBasisFlexRate]([EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [FlexRate], [BudgetConfigID], [AdjustmentGUID])
		SELECT [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [FiscalYearID], [FiscalMonthID], 
			[TimeClassID], [FlexRate], [BudgetConfigID], [NewAdjustmentGUID]
		FROM #variableSetAdjustmentsFlexRate	
	
		INSERT INTO [fp].[FTERequest] ([FTERequestGUID], [BudgetConfigGUID], [DepartmentID], [JobCodeID], [FTEAmount], [StartFiscalMonthID], [WageRate], [Comment], [DateCreatedUtc], [GroupingGUID])
		SELECT [NewFTERequestGUID], [BudgetConfigGUID], [DepartmentID], [JobCodeID], [FTEAmount], [StartFiscalMonthID], [WageRate], [Comment], [DateCreatedUtc], [GroupingGUID]
		FROM #newFteRequests
		
		INSERT INTO [fp].[FTERequestDetail] ([FTERequestDetailGUID], [FTERequestGUID], [PayCodeGroupID], [HoursMix])
		SELECT [FTERequestDetailGUID], [NewFTERequestGUID], [PayCodeGroupID], [HoursMix]
		FROM #newFteRequestDetails

	END
	
END;
GO


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

-- fp.procBudgetTargetSplitUpgrade_Statistics
CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade_Statistics
	@BudgetConfigID INT,
	@IsDebug INT = 0
AS
BEGIN

	IF OBJECT_ID('tempdb..#newGroupings') IS NOT NULL DROP TABLE #newGroupings
	IF OBJECT_ID('tempdb..#groupings') IS NOT NULL DROP TABLE #groupings
	IF OBJECT_ID('tempdb..#newImportAdjustments') IS NOT NULL DROP TABLE #newImportAdjustments
	IF OBJECT_ID('tempdb..#adjustmentsToCopy') IS NOT NULL DROP TABLE #adjustmentsToCopy
	IF OBJECT_ID('tempdb..#adjustmentRateToCopy') IS NOT NULL DROP TABLE #adjustmentRateToCopy
	IF OBJECT_ID('tempdb..#newAddProviderAdjustments') IS NOT NULL DROP TABLE #newAddProviderAdjustments

	DECLARE @Message NVARCHAR(MAX) = 'Adjustment has been generated from the Target/Budget Upgrade.',
			@Spacing NVARCHAR(MAX) = '

'; -- I know this looks wierd, but leave it, it works.


	IF EXISTS (
		SELECT TOP 1 1 FROM [fp].[StatisticsAdjustment] adj
			INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID
		)
	BEGIN
		PRINT 'The upgrade has already been completed for this budget'
		RETURN;
	END

	-- Get all of the adjustments we need to copy to Budget
	SELECT adj.*, adj.AdjustmentGUID AS OriginalAdjustmentGUID
	INTO #adjustmentsToCopy
	FROM [fp].[StatisticsAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND BudgetPhaseID = 2 -- Imports do not use the budget phase property so we'll just need to make sure we copy those rows over later.
		AND TimeClassID = 2   -- We only need to copy budget adjustments, not projection
		AND AdjustmentType != 9 -- Spread unlocks can only happen to Budget, not target so we don't have to worry about these.
		AND AdjustmentType != 4 -- Just making sure the imports aren't included
		AND AdjustmentType != 15 -- Just making sure the add provider aren't included
		
	-- copy import adjustments to the table, we do these seperately because we only want target adjusted adjustments
	INSERT INTO #adjustmentsToCopy ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON],
		[GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON], [TimeClassID],
		[ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted],[DateCreatedUtc], [LastModifiedDateUtc], [DimensionMemberJson],
		[AdjustmentID], [SubsectionID], adj.[BudgetPhaseID], [IsErrored], [OriginalAdjustmentGUID])
	SELECT 
			adj.[AdjustmentGUID], adj.[BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON],
		[GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON], [TimeClassID],
		[ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted],[DateCreatedUtc], [LastModifiedDateUtc], [DimensionMemberJson],
		[AdjustmentID], [SubsectionID], adj.[BudgetPhaseID], [IsErrored], adj.[AdjustmentGUID]
	FROM [fp].[StatisticsAdjustment] adj
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN (SELECT DISTINCT AdjustmentGUID, BudgetPhaseID FROM [fp].[StatisticsAdjustmentImport]) imp ON adj.AdjustmentGUID = imp.AdjustmentGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND imp.BudgetPhaseID = 2 -- We only want to copy imports that contain target adjustments
		AND adj.AdjustmentType = 4

	-- Get a list of all the unique groupingGuids. We'll then need to update these later
	SELECT DISTINCT GroupingGUID, NEWID() AS NewGroupingGUID
	INTO #groupings
	FROM #adjustmentsToCopy
	WHERE AdjustmentType != 4 -- We don't need to copy import because we're not creating seperate adjustments for these.
		AND AdjustmentType != 15 -- We don't need to copy for add provider
		AND GroupingGUID != '00000000-0000-0000-0000-000000000000'
		
	-- Create duplicate adjustment groupings
	SELECT  tmp.NewGroupingGUID, 
			Description = CASE WHEN LEN(TRIM(Description)) = 0 THEN @Message 
		 					   WHEN RIGHT(TRIM(Description), 1) != '.' THEN CONCAT(Description, CONCAT(CONCAT('. ', @Spacing), @Message))
		 					   ELSE CONCAT(Description, CONCAT(@Spacing, @Message)) END, 
			ExcelFile, 
			IsRecordDeleted
	INTO #newGroupings
	FROM [fp].[AdjustmentGrouping] grp
		INNER JOIN #groupings tmp ON grp.GroupingGUID = tmp.GroupingGUID
			
	-- Update the adjustments comment, phase, and date time so that they are before any final budget adjustments
	UPDATE #adjustmentsToCopy
	SET AdjustmentGUID = NEWID(),
		Comment = CASE  WHEN LEN(TRIM(Comment)) = 0 THEN @Message 
		 				WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message))
		 				ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) 
		END,
		BudgetPhaseID = 3,
		DateCreatedUTC = DATEADD(yy, -100, DateCreatedUTC), -- Descrease the current time by 100 years so we keep the rough date/time
		AdjustedProperty = CASE WHEN AdjustedProperty LIKE 'm[0-9]%' THEN REPLACE(AdjustedProperty, 'm', 'mam') ELSE AdjustedProperty END
	
	-- Update the groupings for any existing groupings so we keep the adjustments together.
	UPDATE adj
	SET adj.GroupingGUID = grp.NewGroupingGUID
	FROM #adjustmentsToCopy adj
		INNER JOIN #groupings grp ON adj.GroupingGUID = grp.GroupingGUID

	-- Copy Dependent Statistics adjustment rate
	SELECT adj.[AdjustmentGUID], rate.[AdjustmentID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],
		[PayorID], [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], rate.[SubsectionID],
		rate.[TimeClassID], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10],
		[Value11], [Value12], 3 AS [BudgetPhaseID]
	INTO #adjustmentRateToCopy
	FROM [fp].[StatisticsAdjustmentRate] rate
		INNER JOIN #adjustmentsToCopy adj ON adj.OriginalAdjustmentGUID = rate.AdjustmentGUID
	WHERE rate.BudgetPhaseID = 2
		AND rate.TimeClassID = 2

	-- Copy the target adjustments over to final budget for imports
	SELECT 
		adj.[AdjustmentGUID], [DepartmentID], [EntityID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], imp.[FiscalYearID],
		[FiscalMonthID], [UnitTypeID], imp.[Value], [Version], imp.[TimeClassID], imp.[IsRecordDeleted], imp.[AdjustmentID], [ProviderID],
		[ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], 3 as [BudgetPhaseID]
	INTO #newImportAdjustments
	FROM [fp].[StatisticsAdjustmentImport] imp
		INNER JOIN #adjustmentsToCopy adj ON adj.OriginalAdjustmentGUID = imp.AdjustmentGUID
	WHERE imp.BudgetPhaseID = 2
		AND imp.TimeClassID = 2
		AND adj.AdjustmentType = 4

	-- Copy add provider adjustments
	SELECT
		[BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],[PayorID],
		[PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [TimeClassID], 3 as [BudgetPhaseID], [SubsectionID],
		[IsRecordDeleted], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], [Value11], [Value12]
	INTO #newAddProviderAdjustments 
	FROM [fp].[StatisticAddProviderAdjustment]
	WHERE BudgetConfigID = @BudgetConfigID
		AND TimeClassID = 2
		AND BudgetPhaseID = 2
	
	-- Update the add provider adjustments comment and date
	UPDATE adj
	SET Comment = CASE  WHEN LEN(TRIM(Comment)) = 0 THEN @Message 
		 				WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message))
		 				ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) 
						END,
	DateCreatedUTC = DATEADD(yy, -100, DateCreatedUTC) -- If we don't do this, adjustments (made on this provider) generated by our split upgrade will be overridden by this
	FROM [fp].[StatisticsAdjustment] adj 
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE BudgetConfigID = @BudgetConfigID
		AND adj.AdjustmentType = 15
		
	IF @IsDebug = 1
	BEGIN
		
		SELECT 'New Groupings', * FROM #newGroupings
		SELECT 'New Imports', * FROM #newImportAdjustments
		SELECT 'New Adjustments', * FROM #adjustmentsToCopy
		SELECT 'New Add Provider', * FROM #newAddProviderAdjustments

	END ELSE 
	BEGIN
	
		INSERT INTO [fp].[AdjustmentGrouping] ([GroupingGUID], [Description], [ExcelFile], [IsRecordDeleted])
		SELECT [NewGroupingGUID], [Description], [ExcelFile], [IsRecordDeleted]
		FROM #newGroupings		
	
		INSERT INTO [fp].[StatisticsAdjustment] ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON],
			[GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON],
			[TimeClassID], [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted], [DateCreatedUtc], [LastModifiedDateUtc],
			[DimensionMemberJson], [SubsectionID], [IsErrored], [BudgetPhaseID] )
		SELECT
			[AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON],
			[GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON],
			[TimeClassID], [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted], [DateCreatedUtc], [LastModifiedDateUtc],
			[DimensionMemberJson], [SubsectionID], [IsErrored], [BudgetPhaseID]
		FROM #adjustmentsToCopy	
		
		INSERT INTO [fp].[StatisticsAdjustmentRate] ([AdjustmentGUID], [AdjustmentID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],
			[PayorID], [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [SubsectionID],
			[TimeClassID], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10],
			[Value11], [Value12], [BudgetPhaseID])
		SELECT
			[AdjustmentGUID], [AdjustmentID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],
			[PayorID], [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [SubsectionID],
			[TimeClassID], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10],
			[Value11], [Value12], [BudgetPhaseID]
		FROM #adjustmentRateToCopy

		INSERT INTO [fp].[StatisticsAdjustmentImport] ([AdjustmentGUID], [DepartmentID], [EntityID], [AccountID], [FinancialReportingID],
			[PayorID], [PatientClassID], [FiscalYearID], [FiscalMonthID], [UnitTypeID], [Value], [TimeClassID], [IsRecordDeleted],
			[AdjustmentID], [ProviderID], [ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], [BudgetPhaseID])
		SELECT [AdjustmentGUID], [DepartmentID], [EntityID], [AccountID], [FinancialReportingID],
			[PayorID], [PatientClassID], [FiscalYearID], [FiscalMonthID], [UnitTypeID], [Value], [TimeClassID], [IsRecordDeleted],
			[AdjustmentID], [ProviderID], [ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], [BudgetPhaseID]
		FROM #newImportAdjustments		
		
		INSERT INTO [fp].[StatisticAddProviderAdjustment] ([BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],[PayorID],
			[PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [TimeClassID], [BudgetPhaseID], [SubsectionID],
			[IsRecordDeleted], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], [Value11], [Value12])
		SELECT [BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],[PayorID],
			[PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [TimeClassID], [BudgetPhaseID], [SubsectionID],
			[IsRecordDeleted], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], [Value11], [Value12]
		FROM #newAddProviderAdjustments
	
	END
	
END
GO


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

-- fp.procBudgetedCostPerRVUSampling
CREATE     PROCEDURE [fp].[procBudgetedCostPerRVUSampling]
	@CostingConfigGUID UNIQUEIDENTIFIER,
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@IsDebug BIT = 0
AS
BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	2022-06-30  MD      JAZZ-13102		Use original department when populating variability
	** 2	11-16-2022  MY      JAZZ-46033		Add VariableDirectCost to proc when Enable Patient Activity Flexing Advanced Costing Methods is enabled
	** 3	12-15-2022  MY      JAZZ-46093		Overwrite variable costing rates for new activity
	** 4	01-25-2022  MY      JAZZ-48927		Update sampling so that the target table does not get deleted when detailed costing is run
	** 4	01-25-2022  MY      JAZZ-48927		Removed workaround where TimeClass was copied from 1 to the other. The load checks the TimeClass on the CostingConfig now so it's no longer necessary
	** 5   08-14-2024  NT      JAZZ-74586      Populate ChargeCodeID in fp.BudgetedCostPerRVU_Sampled when advanced costing method Feature Flag is ON
	** 6   10-24-2024  NT 		JAZZ-79088      Eliminate references to the dss.ChargeAllocation table when advanced costing method setting is ON
	*************************************************************/
	
	SET NOCOUNT ON;

	IF OBJECT_ID('tempdb..#costingData') IS NOT NULL DROP TABLE #costingData;
	IF OBJECT_ID('tempdb..#rowsToDelete') IS NOT NULL DROP TABLE #rowsToDelete;
	IF OBJECT_ID('tempdb..#costingResult') IS NOT NULL DROP TABLE #costingResult;
	IF OBJECT_ID('tempdb..#entities') IS NOT NULL DROP TABLE  #entities;

	CREATE TABLE #costingData (
		[DepartmentID] INT NOT NULL DEFAULT(0), 
		[AccountID] INT NOT NULL DEFAULT(0), 
		[JobCodeID] INT NOT NULL DEFAULT(0), 
		[PayCodeGroupID] INT NOT NULL DEFAULT(0), 
		[FiscalYearID] INT NOT NULL DEFAULT(0), 
		[CostComponentID] INT NOT NULL DEFAULT(0), 
		[ChargeCodeID] INT NOT NULL DEFAULT(0),
		[BudgetConfigID] INT NOT NULL DEFAULT(0), 
		[UnitTypeID] INT NOT NULL DEFAULT(0), 
		[VariableDirectUnitCostPerRVU] DECIMAL(38, 6) NOT NULL DEFAULT(0), 
		[TotalVariableDirectCost] DECIMAL(38,8) NOT NULL DEFAULT(0), 
		[TotalCost] DECIMAL(38,6) NOT NULL DEFAULT(0), 
		[PayCodeID] INT NOT NULL DEFAULT(0), 
		[TimeClassID] INT NOT NULL DEFAULT(0), 
		[VariableDirectCost] DECIMAL(38,6) NOT NULL DEFAULT(0)
	);

	CREATE TABLE #rowsToDelete (
		[RowID] INT NOT NULL DEFAULT(0)
	);

	DECLARE @IsAdvancedMethodologiesUsed BIT = ISNULL((SELECT Value FROM fp.SystemSetting WHERE Name = 'Enable Patient Activity Flexing Advanced Costing Methods'), 0)
	DECLARE @BudgetConfigID INT = (SELECT DISTINCT bc.BudgetConfigID 
		FROM [fp].[BudgetConfig] bc 
			INNER JOIN [fp].[EntityGroupConfig] ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID 
		WHERE ec.CostingConfigGUID = @CostingConfigGUID 
			AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID);

	SELECT DISTINCT(costRes.CostingResultID) 
	INTO #costingResult
	FROM (
		SELECT FiscalYearID, max(CostingResultID) as CostingResultID
 		FROM [dss].[CostingResult] cr2
			INNER JOIN [dss].[CostingConfig] cfg on cfg.CostingConfigGuid = cr2.CostingConfigGuid
		WHERE cr2.IsActivityBasedDetail = 1 
			AND cr2.IsMarkedForDeletion = 0 
			AND cr2.IsFailure = 0 
			AND cr2.CostingConfigGuid = @CostingConfigGUID
		GROUP BY FiscalYearID
	) costRes

	SELECT DISTINCT EntityID
	INTO #entities
	FROM fp.EntityGroupConfigMapping
	WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
					
	IF (@IsAdvancedMethodologiesUsed = 1)
	BEGIN
		--------------------------------------------------------------------------------------
		--					Advanced Costing Methods - Enabled
		--------------------------------------------------------------------------------------
		
		-- sample from dss.FactCostingOutDetailGL
		INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], 
			[TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost])
		SELECT
			  gl.OriginalDepartmentID AS DepartmentID --this uses the original department (not reclassed) to sample into the fp tables
			, OriginalAccountID AS AccountID
			, 0 AS [JobCodeID]
			, 0 AS [PayCodeID]
			, 0 AS [PayCodeGroupID]
			, gl.FiscalYearID
			, gl.CostComponentID
			, gl.ChargeCodeID
			, bc.BudgetConfigID
			, 34 AS [UnitTypeID]
			, gl.TimeClassID
			, 0 AS VariableDirectUnitCostPerRVU -- This isn't required as we aren't using RVUs for Advanced Costing
			, 0 AS TotalVariableDirectCost -- This is never used and not sure why we still have it, but leaving for now
			, SUM(gl.TotalCost) AS TotalCost
			, SUM(gl.VariableDirectUnitCost) AS VariableDirectCost
		 FROM [dss].[FactCostingOutDetailGL] gl
			INNER JOIN [dss].[CostingResult] cr ON gl.CostingResultID = cr.CostingResultID
			INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID 
				AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID 
			INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID 
				AND gl.OriginalDepartmentID = dept.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE gl.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult)
		GROUP BY
			  gl.OriginalAccountID
			, gl.OriginalDepartmentID  --group by same original department instead of reclassed
			, bc.BudgetConfigID
			, gl.FiscalYearID
			, gl.TimeClassID
			, gl.CostComponentID
			, gl.ChargeCodeID;
		
		-- sample from dss.FactCostingOutDetailPayroll
		INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], 
			[UnitTypeID], [TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost])
		SELECT
			  pay.OriginalDepartmentID AS DepartmentID  --this uses the original department (not reclassed) to sample into the fp tables
			, ISNULL(cw.AccountID, 0) AS AccountID
			, OriginalJobCodeID AS JobCodeID
			, OriginalPayCodeID AS PayCodeID
			, pc.PayCodeGroupID
			, pay.FiscalYearID
			, pay.CostComponentID
			, pay.ChargeCodeID
			, bc.BudgetConfigID
			, pay.UnitTypeID
			, pay.TimeClassID
			, 0 AS VariableDirectUnitCostPerRVU -- This isn't required as we aren't using RVUs for Advanced Costing
			, 0 AS TotalVariableDirectCost -- This is never used and not sure why we still have it, but leaving for now
			, SUM(pay.TotalCost) AS TotalCost
			, SUM(pay.VariableDirectUnitCost) AS VariableDirectCost
		FROM [dss].[FactCostingOutDetailPayroll] pay
			INNER JOIN [dss].[CostingResult] cr ON pay.CostingResultID = cr.CostingResultID
			INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID 
				AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID 
			INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID
				AND pay.OriginalDepartmentID = dept.DepartmentID   -- make sure that we join the original department to the fw.DimDepartment table
			INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pay.OriginalPayCodeID
			LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw ON pay.OriginalJobCodeID = cw.JobCodeID 
				AND pc.PayCodeGroupID = cw.PayCodeGroupID 
				AND cw.UnitTypeID = 34
		WHERE pay.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult)			
		GROUP BY
			  cw.AccountID
			, pay.OriginalJobCodeID
			, pay.OriginalPayCodeID
			, pc.PayCodeGroupID
			, pay.OriginalDepartmentID  --group by same original department instead of reclassed
			, bc.BudgetConfigID
			, pay.UnitTypeID
			, pay.TimeClassiD
			, pay.FiscalYearID
			, pay.CostComponentID
			, pay.ChargeCodeID;

		-- In the event new costing data is added that matches something in the import, we need to clear out the imported record
		-- as costing record wins
		INSERT INTO #rowsToDelete (RowID)
		SELECT cpr.RowID
		FROM #costingData cost
			INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] cpr ON 
					cost.[DepartmentID]    = cpr.[DepartmentID]
				AND cost.[AccountID] 	   = cpr.[AccountID] 
				AND cost.[CostComponentID] = cpr.[CostComponentID]
				AND cost.[ChargeCodeID] = cpr.[ChargeCodeID]
				AND cost.[BudgetConfigID]  = cpr.[BudgetConfigID]
			INNER JOIN fw.DimDepartment dept ON cpr.DepartmentID = dept.DepartmentID
			INNER JOIN #entities ent ON dept.EntityID = ent.EntityID
		WHERE cpr.BudgetConfigID = @BudgetConfigID
			AND cpr.IsImportedFromFile = 1


		-- In the event new costing data is added that matches something in the import, we need to clear out the imported record
		-- as costing record wins
		INSERT INTO #rowsToDelete (RowID)
		SELECT cpr.RowID
		FROM #costingData cost
			INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] cpr ON 
					cost.[DepartmentID]    = cpr.[DepartmentID]
				AND cost.[JobCodeID] 	   = cpr.[JobCodeID] 
				AND cost.[PayCodeGroupID]  = cpr.[PayCodeGroupID] 
				AND cost.[CostComponentID] = cpr.[CostComponentID]
				AND cost.[ChargeCodeID] = cpr.[ChargeCodeID]
				AND cost.[BudgetConfigID]  = cpr.[BudgetConfigID]
			INNER JOIN fw.DimDepartment dept ON cpr.DepartmentID = dept.DepartmentID
			INNER JOIN #entities ent ON dept.EntityID = ent.EntityID
		WHERE cpr.BudgetConfigID = @BudgetConfigID
			AND cpr.IsImportedFromFile = 1

	END ELSE BEGIN
		--------------------------------------------------------------------------------------
		--					Advanced Costing Methods - Disabled
		--------------------------------------------------------------------------------------

		-- sample from dss.FactCostingOutDetailGL
		INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [BudgetConfigID], [UnitTypeID], 
			[TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost])
		SELECT
			  gl.OriginalDepartmentID AS DepartmentID --this uses the original department (not reclassed) to sample into the fp tables
			, OriginalAccountID AS AccountID
			, 0 AS [JobCodeID]
			, 0 AS [PayCodeID]
			, 0 AS [PayCodeGroupID]
			, gl.FiscalYearID
			, gl.CostComponentID
			, bc.BudgetConfigID
			, 34 AS [UnitTypeID]
			, gl.TimeClassID
			, ISNULL(SUM(gl.VariableDirectUnitCost) / NULLIF(SUM(ca.RVU), 0), 0) AS VariableDirectUnitCostPerRVU
			, SUM(gl.VariableDirectUnitCost * gl.Volume) AS TotalVariableDirectCost
			, SUM(gl.TotalCost) AS TotalCost
			, 0 AS VariableDirectCost
		 FROM [dss].[FactCostingOutDetailGL] gl
			INNER JOIN [dss].[CostingResult] cr ON gl.CostingResultID = cr.CostingResultID
			INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID 
				AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID 
			INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID 
				AND gl.OriginalDepartmentID = dept.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
			INNER JOIN [dss].[ChargeAllocation] ca ON ca.CostingConfigGuid = cr.CostingConfigGUID
				AND ca.ChargeCodeID = gl.ChargeCodeID 
				AND ca.DepartmentID = gl.OriginalDepartmentID   -- this joins the reclassed department to the ChargeAllocation table	
				AND ca.CostComponentID = gl.CostComponentID
				AND AllocationType = 1 
				AND ca.IsFixed = 0 
				AND ca.IsIndirect = 0 
				AND ca.RVU <> 0
		WHERE gl.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult)
		GROUP BY
			  gl.OriginalAccountID
			, gl.OriginalDepartmentID  --group by same original department instead of reclassed
			, bc.BudgetConfigID
			, gl.FiscalYearID
			, gl.TimeClassID
			, gl.CostComponentID;
		
		-- sample from dss.FactCostingOutDetailPayroll
		INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [BudgetConfigID], 
			[UnitTypeID], [TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost])
		SELECT
			  pay.OriginalDepartmentID AS DepartmentID  --this uses the original department (not reclassed) to sample into the fp tables
			, ISNULL(cw.AccountID, 0) AS AccountID
			, OriginalJobCodeID AS JobCodeID
			, OriginalPayCodeID AS PayCodeID
			, pc.PayCodeGroupID
			, pay.FiscalYearID
			, pay.CostComponentID
			, bc.BudgetConfigID
			, pay.UnitTypeID
			, pay.TimeClassID
			, ISNULL(SUM(pay.VariableDirectUnitCost) / NULLIF(SUM(ca.RVU), 0), 0) AS VariableDirectUnitCostPerRVU
			, SUM(pay.VariableDirectUnitCost * pay.Volume) AS TotalVariableDirectCost
			, SUM(pay.TotalCost) AS TotalCost
			, 0 AS VariableDirectCost
		FROM [dss].[FactCostingOutDetailPayroll] pay
			INNER JOIN [dss].[CostingResult] cr ON pay.CostingResultID = cr.CostingResultID
			INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID 
				AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID 
			INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID
				AND pay.OriginalDepartmentID = dept.DepartmentID   -- make sure that we join the original department to the fw.DimDepartment table
			INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
			INNER JOIN [dss].[ChargeAllocation] ca ON ca.CostingConfigGuid = cr.CostingConfigGUID
				AND ca.ChargeCodeID = pay.ChargeCodeID 
				AND ca.DepartmentID = pay.OriginalDepartmentID   -- this joins the reclassed department to the ChargeAllocation table
				AND ca.CostComponentID = pay.CostComponentID
				AND AllocationType = 1 
				AND ca.IsFixed = 0 
				AND ca.IsIndirect = 0 
				AND ca.RVU <> 0
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pay.OriginalPayCodeID
			LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw ON pay.OriginalJobCodeID = cw.JobCodeID 
				AND pc.PayCodeGroupID = cw.PayCodeGroupID 
				AND cw.UnitTypeID = 34
		WHERE pay.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult)
		GROUP BY
			  cw.AccountID
			, pay.OriginalJobCodeID
			, pay.OriginalPayCodeID
			, pc.PayCodeGroupID
			, pay.OriginalDepartmentID  --group by same original department instead of reclassed
			, bc.BudgetConfigID
			, pay.UnitTypeID
			, pay.TimeClassiD
			, pay.FiscalYearID
			, pay.CostComponentID;

	END
		
	IF (@IsDebug = 1)
	BEGIN

		SELECT 'IsAdvancedMethodologiesUsed', @IsAdvancedMethodologiesUsed
		SELECT 'IsAdvancedMethodologiesUsed', EntityID FROM #entities
		SELECT '#costingResult', CostingResultID FROM #costingResult
		SELECT '#costingData', [DepartmentID], [AccountID], [JobCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], [VariableDirectUnitCostPerRVU], 
			[TotalVariableDirectCost], [TotalCost], [PayCodeID], [TimeClassID], [VariableDirectCost]
		FROM #costingData				
		SELECT '#rowsToDelete', RowID FROM #rowsToDelete

	END ELSE BEGIN
		
		-- Clear out the records for [fp].[BudgetedCostPerRVU_Sampled] that were not imported in
		DELETE sampl
		FROM [fp].[BudgetedCostPerRVU_Sampled] sampl
			INNER JOIN fw.DimDepartment dept ON sampl.DepartmentID = dept.DepartmentID
			INNER JOIN #entities ent ON dept.EntityID = ent.EntityID
		WHERE sampl.BudgetConfigID = @BudgetConfigID
			AND IsImportedFromFile = 0;

		IF (@IsAdvancedMethodologiesUsed = 1)
		BEGIN
			-- Clear out rows in the import that have the same dimensionality
			DELETE sampl
			FROM [fp].[BudgetedCostPerRVU_Sampled] sampl
				INNER JOIN #rowsToDelete del ON del.RowID = sampl.RowID
				INNER JOIN fw.DimDepartment dept ON sampl.DepartmentID = dept.DepartmentID
				INNER JOIN #entities ent ON dept.EntityID = ent.EntityID
			WHERE sampl.BudgetConfigID = @BudgetConfigID
				AND IsImportedFromFile = 1;
		END
			
		-- Populate costing data
		INSERT INTO [fp].[BudgetedCostPerRVU_Sampled] ([DepartmentID], [AccountID], [JobCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], [VariableDirectUnitCostPerRVU], 
			[TotalVariableDirectCost], [TotalCost], [PayCodeID], [TimeClassID], [VariableDirectCost])
		SELECT [DepartmentID], [AccountID], [JobCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], [VariableDirectUnitCostPerRVU], 
			[TotalVariableDirectCost], [TotalCost], [PayCodeID], [TimeClassID], [VariableDirectCost]
		FROM #costingData

	END
END
GO


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

-- fp.procCacheGeneralLedgerFlexingType
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			Description
** 1		2021-02-25	    MY	       JAZZ-17526	Corrected targeting for the update
** 2		2021-09-16	    NT	       JAZZ-25494	Replace funcGetGLVariableDataForServiceLineVolumeFlexing by procGetGLVariableDataForServiceLineVolumeFlexing
** 3		8-30-2023		NT		   JAZZ-59319	Data Restructure changea
** 4 		9-5-2023		NT         JAZZ-60140	Remove RowID from #patientActivityDimensionality
** 5		9-7-2023		NT			JAZZ-59598	Add PercentAdjustmentFactor to #patientActivityDimensionality to support change for PAF
***************************************************************/
CREATE        PROCEDURE [fp].[procCacheGeneralLedgerFlexingType]
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
 AS
BEGIN

	DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER = (SELECT EntityGroupConfigGUID	FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID)
	DECLARE @FiscalYearID SMALLINT = (SELECT FiscalYearID FROM [fp].[BudgetConfig] bc 
												INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID 
												WHERE EntityGroupConfigID = @EntityGroupConfigID)

	CREATE TABLE #filterTable (GeneralLedgerID INT);
	CREATE TABLE #patientActivityFlexing (GeneralLedgerID INT, FlexingTypeID INT);
	CREATE TABLE #otherFlexing (GeneralLedgerID INT, FlexingTypeID INT);

	-- Build the department filter
	SELECT DISTINCT DepartmentID 
	INTO #SourceDimensionality 
	FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- Gather filter table
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
 
	  	INSERT INTO #filterTable (GeneralLedgerID)
		SELECT DISTINCT basis.GeneralLedgerID
		FROM [fp].[GeneralLedger] basis
			INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID
		WHERE basis.EntityGroupConfigID = @EntityGroupConfigID 
  
	END ELSE BEGIN
  
	  	-- If the table source dimensionality is unfiltered, we don't wanna join on the department filter.
	  	INSERT INTO #filterTable (GeneralLedgerID)
		SELECT DISTINCT basis.GeneralLedgerID
		FROM [fp].[GeneralLedger] basis
		WHERE basis.EntityGroupConfigID = @EntityGroupConfigID 
  
	END
	
	-- Map records based on this page: 
	-- https://confluence.sdt.local/display/SWPRJ/Common+Calculations%2C+Equations%2C+IDs%2C+and+Look+Up+Values#CommonCalculations,Equations,IDs,andLookUpValues-FlexingType
	
	-- Note, if the flexing type in the configuration is set to flex, however, the data is not configured to flex, the flexing type ID will default to 0 (fixed)
	-- Once the proper data has been added, the flexing type will be cached
	
	-- Get the dimensionality based on what's being flexed by PAF. The function filters it to variable and dollars when we need everything.
	IF ((SELECT IsPatientActivityFlexingForNonStaffing FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) = 1)
	BEGIN
	
		EXEC[dbo].[procSysDropTempTable] '#patientActivityDimensionality'
		CREATE TABLE #patientActivityDimensionality (
		BasisID INT,
		BudgetPhaseID TINYINT,
		TimeClassID TINYINT,
		DepartmentID INT,
		AccountID INT,
		FiscalYearID SMALLINT,
		FiscalMonthID TINYINT,
		OriginalValue DECIMAL(19,8),
		PercentAdjustmentFactor DECIMAL(19,8))
	
		INSERT INTO #patientActivityDimensionality
		EXEC fp.procGetGLVariableDataForServiceLineVolumeFlexing @EntityGroupConfigGUID, @EntityGroupConfigID, @FiscalYearID, @SourceDimensionality
		
		INSERT INTO #patientActivityFlexing (GeneralLedgerID, FlexingTypeID)
		SELECT DISTINCT fgl.GeneralLedgerID, 7 AS FlexingTypeID
		FROM [fp].[GeneralLedger] fgl
			INNER JOIN #filterTable filter ON fgl.GeneralLedgerID = filter.GeneralLedgerID
			INNER JOIN #patientActivityDimensionality flex ON 
					fgl.DepartmentID = flex.DepartmentID 
				AND fgl.AccountID = flex.AccountID
		WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID 
	
	END
	
	INSERT INTO #otherFlexing (GeneralLedgerID, FlexingTypeID)
	SELECT DISTINCT gl.GeneralLedgerID, flex.FlexingTypeID
	FROM [fp].[FlexConfigMapping] flex
		INNER JOIN [fp].[GeneralLedger] gl ON flex.DepartmentID = gl.DepartmentID AND flex.GLAccountID = gl.AccountID AND flex.EntityGroupConfigID = gl.EntityGroupConfigID
		INNER JOIN #filterTable filter ON gl.GeneralLedgerID = filter.GeneralLedgerID
	WHERE flex.EntityGroupConfigID = @EntityGroupConfigID
	
	IF (@IsDebug = 1)
	BEGIN
		
		SELECT '#filterTable', * FROM #filterTable 
				
		IF OBJECT_ID('tempdb..#patientActivityDimensionality') IS NOT NULL
			SELECT '#patientActivityDimensionality', * FROM #patientActivityDimensionality 
		
		SELECT '#patientActivityFlexing', * FROM #patientActivityFlexing 
		SELECT '#otherFlexing', * FROM #otherFlexing 
	
	END ELSE BEGIN
	
		UPDATE gl
		SET gl.FlexingTypeID = COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0)
		FROM [fp].[GeneralLedger] gl
			INNER JOIN #filterTable filter ON gl.GeneralLedgerID = filter.GeneralLedgerID
			LEFT JOIN #patientActivityFlexing paf ON paf.GeneralLedgerID = gl.GeneralLedgerID
			LEFT JOIN #otherFlexing flex ON flex.GeneralLedgerID = gl.GeneralLedgerID
		WHERE gl.FlexingTypeID != COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0)
		AND gl.EntityGroupConfigID = @EntityGroupConfigID
	
	END

END;
GO


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

-- fp.procCacheStaffingFlexingType
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			Description
** 1		2021-02-25	    MY	       JAZZ-17526	Corrected targeting for the update
** 2		2021-05-24	    BK	       JAZZ-3089 	Make paf sql more efficient and add drop temp table statements
** 3		2021-07-01	    MY	       FAIL-TEST 	Corrected targeting case when there is no targeting filter for PAF
** 4		2023-11-07	    MD	       JAZZ-62448 	Update for staffing restructure
***************************************************************/
CREATE   PROCEDURE [fp].[procCacheStaffingFlexingType]
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
 AS
BEGIN

	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable
	IF OBJECT_ID('tempdb..#SourceDimensionality') IS NOT NULL DROP TABLE #SourceDimensionality
	IF OBJECT_ID('tempdb..#patientActivityFlexing') IS NOT NULL DROP TABLE #patientActivityFlexing
	IF OBJECT_ID('tempdb..#patientActivityDimensionality') IS NOT NULL DROP TABLE #patientActivityDimensionality
	IF OBJECT_ID('tempdb..#otherFlexing') IS NOT NULL DROP TABLE #otherFlexing

	DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER = (SELECT EntityGroupConfigGUID	FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID)
	DECLARE @FiscalYearID SMALLINT = (SELECT FiscalYearID FROM [fp].[BudgetConfig] bc 
												INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID 
												WHERE EntityGroupConfigID = @EntityGroupConfigID)

	CREATE TABLE #filterTable (StaffingID INT);
	CREATE TABLE #patientActivityFlexing (StaffingID INT, FlexingTYpeID INT);
	CREATE TABLE #otherFlexing (StaffingID INT, FlexingTYpeID INT);

	
	DECLARE @StaffingSubsectionID INT = 3
	DECLARE @ProviderSubsectionID INT = 4

	-- Build the department filter
	SELECT DISTINCT DepartmentID 
	INTO #SourceDimensionality 
	FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- Gather filter table
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
 
	  	INSERT INTO #filterTable (StaffingID)
		SELECT DISTINCT basis.StaffingID
		FROM [fp].[Staffing] basis
			INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID
		WHERE basis.EntityGroupConfigID = @EntityGroupConfigID 
  
	END ELSE BEGIN
  
	  	-- If the table source dimensionality is unfiltered, we don't wanna join on the department filter.
	  	INSERT INTO #filterTable (StaffingID)
		SELECT DISTINCT basis.StaffingID
		FROM [fp].[Staffing] basis
		WHERE basis.EntityGroupConfigID = @EntityGroupConfigID 
  
	END
	
	-- Map records based on this page: 
	-- https://confluence.sdt.local/display/SWPRJ/Common+Calculations%2C+Equations%2C+IDs%2C+and+Look+Up+Values#CommonCalculations,Equations,IDs,andLookUpValues-FlexingType
	
	-- Note, if the flexing type in the configuration is set to flex, however, the data is not configured to flex, the flexing type ID will default to 0 (fixed)
	-- Once the proper data has been added, the flexing type will be cached
	
	-- Get the dimensionality based on what's being flexed by PAF. The function filters it to variable and dollars when we need everything.
	
	IF ((SELECT IsPatientActivityFlexingForStaffing FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) = 1)
	BEGIN
		
		SELECT DISTINCT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID
		INTO #patientActivityDimensionality
		 FROM [fp].[Staffing] fs
			INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID
	        LEFT JOIN [fp].[FlexConfigMapping] map
	        ON fs.DepartmentID = map.DepartmentID
	            AND fs.JobCodeID = map.PRJobCodeID
	            AND fs.EntityGroupConfigID = map.EntityGroupConfigID
	        LEFT JOIN [fp].[viewStaffingExpenseFlexingConfig] fc
	        ON fs.DepartmentID = fc.DepartmentID
	            AND fs.JobCodeID = fc.JobCodeID
	            AND fc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		WHERE
		        fs.EntityGroupConfigID = @EntityGroupConfigID
		    AND fs.VariabilityID = 2
		    AND map.FlexingTypeID IS NULL
		    AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL)
		    
		INSERT INTO #patientActivityFlexing (StaffingID, FlexingTypeID)
		SELECT DISTINCT fs.StaffingID, 7 AS FlexingTypeID
		FROM [fp].[Staffing] fs
			INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID
			INNER JOIN #patientActivityDimensionality flex ON 
					fs.DepartmentID = flex.DepartmentID 
				AND fs.JobCodeID = flex.JobCodeID
				AND fs.PayCodeGroupID = flex.PayCodeGroupID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
	
	END

   -- Staffing
	INSERT INTO #otherFlexing (StaffingID, FlexingTypeID)
	SELECT DISTINCT staff.StaffingID, flex.FlexingTypeID
	FROM [fp].[FlexConfigMapping] flex
		INNER JOIN [fp].[Staffing] staff ON flex.DepartmentID = staff.DepartmentID AND flex.PRJobCodeID = staff.JobCodeID AND flex.EntityGroupConfigID = staff.EntityGroupConfigID
		INNER JOIN #filterTable filter ON staff.StaffingID = filter.StaffingID
	WHERE flex.EntityGroupConfigID = @EntityGroupConfigID and staff.SubsectionID = @StaffingSubsectionID

	-- Provider
	INSERT INTO #otherFlexing (StaffingID, FlexingTypeID)
	SELECT DISTINCT staff.StaffingID, flex.FlexingTypeID
	FROM [fp].[FlexConfigMapping] flex
		INNER JOIN [fp].[Staffing] staff ON flex.DepartmentID = staff.DepartmentID AND flex.PRJobCodeID = staff.JobCodeID 
			AND flex.ProviderLineItemID = staff.ProviderLineItemID AND flex.EntityGroupConfigID = staff.EntityGroupConfigID  
		INNER JOIN #filterTable filter ON staff.StaffingID = filter.StaffingID
	WHERE flex.EntityGroupConfigID = @EntityGroupConfigID and staff.SubsectionID = @ProviderSubsectionID
	
	
	IF (@IsDebug = 1)
	BEGIN
		
		SELECT '#filterTable', * FROM #filterTable 
				
		IF OBJECT_ID('tempdb..#patientActivityDimensionality') IS NOT NULL
			SELECT '#patientActivityDimensionality', * FROM #patientActivityDimensionality 
		
		SELECT '#patientActivityFlexing', * FROM #patientActivityFlexing 
		SELECT '#otherFlexing', * FROM #otherFlexing 
	
	END ELSE BEGIN
	
		UPDATE staff
		SET staff.FlexingTypeID = COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0)
		FROM [fp].[Staffing] staff 
			INNER JOIN #filterTable filter ON staff.StaffingID = filter.StaffingID
			LEFT JOIN #patientActivityFlexing paf ON paf.StaffingID = staff.StaffingID
			LEFT JOIN #otherFlexing flex ON flex.StaffingID = staff.StaffingID
		WHERE staff.FlexingTypeID != COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0)
		AND staff.EntityGroupConfigID = @EntityGroupConfigID
	
	END
END;
GO


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

-- fp.procCalculatePayrollDollarsByWageRate
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1	2019-03-08	IP		B-22295		Removed using table variables, small optimizations
*************************************************************/
CREATE PROCEDURE [fp].[procCalculatePayrollDollarsByWageRate]
	@EntityGroupConfigID INT,
	@TimeClassID INT
AS

DECLARE @BudgetConfigID INT
SET @BudgetConfigID = (
	SELECT bc.BudgetConfigID
	FROM [fp].[BudgetConfig] bc 
	INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID)
	
	
CREATE TABLE #EntityIDs(ID INT)
INSERT INTO #EntityIDs 
	SELECT DISTINCT map.EntityID
	FROM [fp].[EntityGroupConfig] egc
	INNER JOIN [fp].[EntityGroupConfigMapping] map on egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID

-- Budgeted	

		SELECT 
			DepartmentID,
			JobCodeID,
			PayCodeGroupID,
			BudgetConfigID,
			ProductiveClassID,
			VariabilityID,
			EntityID,
			TimeClassID,
			FiscalYearID,
			FiscalMonthID,
			Value,
			ManagerValue,
			OriginalValue
		INTO #hrs
		FROM [fp].[FactPayrollBasisResult] basis
		INNER JOIN #EntityIDs e on e.EntityID = basis.EntityID
		WHERE 
			BudgetConfigID = @BudgetConfigID
			AND UnitTypeID = 51
			AND TimeClassID = @TimeClassID

			(
		SELECT 
			DepartmentID,
			JobCodeID,
			PayCodeGroupID,
			BudgetConfigID,
			ProductiveClassID,
			VariabilityID,
			EntityID,
			TimeClassID,
			FiscalYearID,
			FiscalMonthID,
			Value,
			ManagerValue,
			OriginalValue
		INTO #wg
		FROM [fp].[FactPayrollBasisResult] basis
		INNER JOIN #EntityIDs e on e.EntityID = basis.EntityID
		WHERE 
			BudgetConfigID = @BudgetConfigID
			AND UnitTypeID = 159
			AND TimeClassID = @TimeClassID
		)

UPDATE basis
SET 
	basis.Value = wg.Value * hrs.Value,
	basis.ManagerValue = wg.ManagerValue * hrs.ManagerValue,
	basis.OriginalValue = wg.OriginalValue * hrs.OriginalValue
FROM [fp].[FactPayrollBasisResult] basis
INNER JOIN #EntityIDs e on e.EntityID = basis.EntityID
INNER JOIN #hrs
	ON hrs.DepartmentID = basis.DepartmentID
	AND hrs.JobCodeID = basis.JobCodeID
	AND hrs.PayCodeGroupID = basis.PayCodeGroupID
	AND hrs.BudgetConfigID = basis.BudgetConfigID
	AND hrs.ProductiveClassID = basis.ProductiveClassID
	AND hrs.VariabilityID = basis.VariabilityID
	AND hrs.EntityID = basis.EntityID
	AND hrs.TimeClassID = basis.TimeClassID
	AND hrs.FiscalYearID = basis.FiscalYearID
	AND hrs.FiscalMonthID = basis.FiscalMonthID
	INNER JOIN #wg wg
	ON wg.DepartmentID = basis.DepartmentID
	AND wg.JobCodeID = basis.JobCodeID
	AND wg.PayCodeGroupID = basis.PayCodeGroupID
	AND wg.BudgetConfigID = basis.BudgetConfigID
	AND wg.ProductiveClassID = basis.ProductiveClassID
	AND wg.VariabilityID = basis.VariabilityID
	AND wg.EntityID = basis.EntityID
	AND wg.TimeClassID = basis.TimeClassID
	AND wg.FiscalYearID = basis.FiscalYearID
	AND wg.FiscalMonthID = basis.FiscalMonthID
WHERE 
	basis.UnitTypeID = 34
	AND basis.BudgetConfigID = @BudgetConfigID
	AND basis.TimeClassID = @TimeClassID
GO


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

-- fp.procCascadeChargeMasterPrices
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			  Description
** 1	2021-04-15	LR		JAZZ-18924	  Adding rolling updates to avoid filling up the logs
** 2	2022-05-23	MY		JAZZ-37263	  Performance Improvements
** 3	2023-03-06	MY		JAZZ-48307	  Update charges adjustment to support data model changes
*************************************************************/
CREATE   PROCEDURE [fp].[procCascadeChargeMasterPrices]
	@BudgetConfigID INT,
	@IsEntityUsed BIT,
	@IsPatientClassUsed BIT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN	
	IF OBJECT_ID('tempdb..#recordsToProcess') IS NOT NULL DROP TABLE #recordsToProcess;
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END	
	
	DECLARE @ChargeRateMonth01 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(1, @BudgetConfigID)),
			@ChargeRateMonth02 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(2, @BudgetConfigID)),
			@ChargeRateMonth03 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(3, @BudgetConfigID)),
			@ChargeRateMonth04 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(4, @BudgetConfigID)),
			@ChargeRateMonth05 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(5, @BudgetConfigID)),
			@ChargeRateMonth06 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(6, @BudgetConfigID)),
			@ChargeRateMonth07 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(7, @BudgetConfigID)),
			@ChargeRateMonth08 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(8, @BudgetConfigID)),
			@ChargeRateMonth09 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(9, @BudgetConfigID)),
			@ChargeRateMonth10 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(10, @BudgetConfigID)),
			@ChargeRateMonth11 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(11, @BudgetConfigID)),
			@ChargeRateMonth12 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(12, @BudgetConfigID))
			
	-- Update Statistics before performing update per DBAs
	UPDATE STATISTICS fp.ChargeVolume
	UPDATE STATISTICS fp.FactChargeMaster

	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Update Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 500000 END;		 
				
	SELECT fcv.ChargeVolumeID
	INTO #recordsToProcess
	FROM fp.ChargeVolume fcv
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID
	WHERE fcv.BudgetConfigID = @BudgetConfigID
	ORDER BY fcv.ChargeVolumeID;

	PRINT 'Processing Budget'

	DECLARE @IsEntityUsedSQL NVARCHAR(MAX),
			@IsPatientClassUsedSQL NVARCHAR(MAX);

	SET @IsEntityUsedSQL = CASE WHEN @IsEntityUsed = 1 THEN 'FCM.EntityID = fcv.EntityID' ELSE ' 0 = 0' END;
	SET @IsPatientClassUsedSQL = CASE WHEN @IsPatientClassUsed = 1 THEN 'FCM.PatientClassID = fcv.PatientClassID' ELSE ' 0 = 0' END;

	DECLARE @ChunkEndID INT = -1;
	DECLARE @LastUpdatedID INT = @ChunkEndID -1;
	WHILE @ChunkEndID > @LastUpdatedID
	BEGIN
		BEGIN TRANSACTION;			  
				
		SET @LastUpdatedID = @ChunkEndID;
		
		SELECT TOP ( @ChunkCount ) @ChunkEndID = ChargeVolumeID
		FROM #recordsToProcess
		WHERE ChargeVolumeID > @ChunkEndID
		ORDER BY ChargeVolumeID;
		
		EXEC('
		UPDATE fcv
		SET
			-- Updating the prices for ChargeVolumeDollarsBudget 
			fcv.TargetPrice01 = ISNULL(FCM.' + @ChargeRateMonth01 + ', 0),
			fcv.TargetPrice02 = ISNULL(FCM.' + @ChargeRateMonth02 + ', 0),
			fcv.TargetPrice03 = ISNULL(FCM.' + @ChargeRateMonth03 + ', 0),
			fcv.TargetPrice04 = ISNULL(FCM.' + @ChargeRateMonth04 + ', 0),
			fcv.TargetPrice05 = ISNULL(FCM.' + @ChargeRateMonth05 + ', 0),
			fcv.TargetPrice06 = ISNULL(FCM.' + @ChargeRateMonth06 + ', 0),
			fcv.TargetPrice07 = ISNULL(FCM.' + @ChargeRateMonth07 + ', 0),
			fcv.TargetPrice08 = ISNULL(FCM.' + @ChargeRateMonth08 + ', 0),
			fcv.TargetPrice09 = ISNULL(FCM.' + @ChargeRateMonth09 + ', 0),
			fcv.TargetPrice10 = ISNULL(FCM.' + @ChargeRateMonth10 + ', 0),
			fcv.TargetPrice11 = ISNULL(FCM.' + @ChargeRateMonth11 + ', 0),
			fcv.TargetPrice12 = ISNULL(FCM.' + @ChargeRateMonth12 + ', 0),
			fcv.BudgetPrice01 = ISNULL(FCM.' + @ChargeRateMonth01 + ', 0),
			fcv.BudgetPrice02 = ISNULL(FCM.' + @ChargeRateMonth02 + ', 0),
			fcv.BudgetPrice03 = ISNULL(FCM.' + @ChargeRateMonth03 + ', 0),
			fcv.BudgetPrice04 = ISNULL(FCM.' + @ChargeRateMonth04 + ', 0),
			fcv.BudgetPrice05 = ISNULL(FCM.' + @ChargeRateMonth05 + ', 0),
			fcv.BudgetPrice06 = ISNULL(FCM.' + @ChargeRateMonth06 + ', 0),
			fcv.BudgetPrice07 = ISNULL(FCM.' + @ChargeRateMonth07 + ', 0),
			fcv.BudgetPrice08 = ISNULL(FCM.' + @ChargeRateMonth08 + ', 0),
			fcv.BudgetPrice09 = ISNULL(FCM.' + @ChargeRateMonth09 + ', 0),
			fcv.BudgetPrice10 = ISNULL(FCM.' + @ChargeRateMonth10 + ', 0),
			fcv.BudgetPrice11 = ISNULL(FCM.' + @ChargeRateMonth11 + ', 0),
			fcv.BudgetPrice12 = ISNULL(FCM.' + @ChargeRateMonth12 + ', 0)
		FROM fp.ChargeVolume fcv
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID
			LEFT JOIN [fp].[FactChargeMaster] FCM 
				ON  FCM.BudgetConfigID = fcv.BudgetConfigID 
				AND FCM.ChargeCodeID = fcv.ChargeCodeID
				AND FCM.TimeClassID = 2
				AND ' + @IsEntityUsedSQL + '
				AND ' + @IsPatientClassUsedSQL + '
		WHERE fcv.BudgetConfigID = ' + @BudgetConfigID + '
			AND fcv.ChargeVolumeID > ' + @LastUpdatedID + '
            AND fcv.ChargeVolumeID <= ' + @ChunkEndID + '
			AND (
				fcv.TargetPrice01 != ISNULL(FCM.' + @ChargeRateMonth01 + ', 0) OR
				fcv.TargetPrice02 != ISNULL(FCM.' + @ChargeRateMonth02 + ', 0) OR
				fcv.TargetPrice03 != ISNULL(FCM.' + @ChargeRateMonth03 + ', 0) OR
				fcv.TargetPrice04 != ISNULL(FCM.' + @ChargeRateMonth04 + ', 0) OR
				fcv.TargetPrice05 != ISNULL(FCM.' + @ChargeRateMonth05 + ', 0) OR
				fcv.TargetPrice06 != ISNULL(FCM.' + @ChargeRateMonth06 + ', 0) OR
				fcv.TargetPrice07 != ISNULL(FCM.' + @ChargeRateMonth07 + ', 0) OR
				fcv.TargetPrice08 != ISNULL(FCM.' + @ChargeRateMonth08 + ', 0) OR
				fcv.TargetPrice09 != ISNULL(FCM.' + @ChargeRateMonth09 + ', 0) OR
				fcv.TargetPrice10 != ISNULL(FCM.' + @ChargeRateMonth10 + ', 0) OR
				fcv.TargetPrice11 != ISNULL(FCM.' + @ChargeRateMonth11 + ', 0) OR
				fcv.TargetPrice12 != ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) OR
				fcv.BudgetPrice01 != ISNULL(FCM.' + @ChargeRateMonth01 + ', 0) OR
				fcv.BudgetPrice02 != ISNULL(FCM.' + @ChargeRateMonth02 + ', 0) OR
				fcv.BudgetPrice03 != ISNULL(FCM.' + @ChargeRateMonth03 + ', 0) OR
				fcv.BudgetPrice04 != ISNULL(FCM.' + @ChargeRateMonth04 + ', 0) OR
				fcv.BudgetPrice05 != ISNULL(FCM.' + @ChargeRateMonth05 + ', 0) OR
				fcv.BudgetPrice06 != ISNULL(FCM.' + @ChargeRateMonth06 + ', 0) OR
				fcv.BudgetPrice07 != ISNULL(FCM.' + @ChargeRateMonth07 + ', 0) OR
				fcv.BudgetPrice08 != ISNULL(FCM.' + @ChargeRateMonth08 + ', 0) OR
				fcv.BudgetPrice09 != ISNULL(FCM.' + @ChargeRateMonth09 + ', 0) OR
				fcv.BudgetPrice10 != ISNULL(FCM.' + @ChargeRateMonth10 + ', 0) OR
				fcv.BudgetPrice11 != ISNULL(FCM.' + @ChargeRateMonth11 + ', 0) OR
				fcv.BudgetPrice12 != ISNULL(FCM.' + @ChargeRateMonth12 + ', 0)
			)
		');		
				 
		COMMIT TRANSACTION;
	END
	
	PRINT 'Processing Projection'
	
	DECLARE @SelectClause NVARCHAR(MAX) = '',
			@WhereClause NVARCHAR(MAX) = '',
			@MonthsLoaded INT = (SELECT MonthsLoaded FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID);
	
	-- To whom is reading this, yes I am sure you hate this, and yes I am aware, but I don't know what else to do here really. Especially since we can't really do the same FOR loop like in other procs due to needing the price variable from above.
	-- The point of this is to generate the update for the months not loaded only. The months loaded prices are not used and not relevent for projection because we pull dollars from the actuals for projection months loaded, therefore the price from the charge master
	-- does not impact the months loaded at all as they came from history.
	IF (1 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice01 = ISNULL(FCM.' + @ChargeRateMonth01 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice01 != ISNULL(FCM.' + @ChargeRateMonth01 + ', 0) OR ';		
	END

	IF (2 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice02 = ISNULL(FCM.' + @ChargeRateMonth02 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice02 != ISNULL(FCM.' + @ChargeRateMonth02 + ', 0) OR ';		
	END

	IF (3 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice03 = ISNULL(FCM.' + @ChargeRateMonth03 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice03 != ISNULL(FCM.' + @ChargeRateMonth03 + ', 0) OR ';
	END

	IF (4 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice04 = ISNULL(FCM.' + @ChargeRateMonth04 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice04 != ISNULL(FCM.' + @ChargeRateMonth04 + ', 0) OR ';		
	END

	IF (5 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice05 = ISNULL(FCM.' + @ChargeRateMonth05 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice05 != ISNULL(FCM.' + @ChargeRateMonth05 + ', 0) OR ';
	END

	IF (6 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice06 = ISNULL(FCM.' + @ChargeRateMonth06 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice06 != ISNULL(FCM.' + @ChargeRateMonth06 + ', 0) OR ';
	END

	IF (7 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice07 = ISNULL(FCM.' + @ChargeRateMonth07 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice07 != ISNULL(FCM.' + @ChargeRateMonth07 + ', 0) OR ';
	END

	IF (8 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice08 = ISNULL(FCM.' + @ChargeRateMonth08 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice08 != ISNULL(FCM.' + @ChargeRateMonth08 + ', 0) OR ';
	END

	IF (9 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice09 = ISNULL(FCM.' + @ChargeRateMonth09 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice09 != ISNULL(FCM.' + @ChargeRateMonth09 + ', 0) OR ';
	END

	IF (10 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice10 = ISNULL(FCM.' + @ChargeRateMonth10 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice10 != ISNULL(FCM.' + @ChargeRateMonth10 + ', 0) OR ';
	END

	IF (11 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice11 = ISNULL(FCM.' + @ChargeRateMonth11 + ', 0), ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice11 != ISNULL(FCM.' + @ChargeRateMonth11 + ', 0) OR ';
	END

	IF (12 > @MonthsLoaded)
	BEGIN
		SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice12 = ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) ';	
		SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice12 != ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) ';
	END

	SET @ChunkEndID = -1;
	SET @LastUpdatedID = @ChunkEndID -1;
	WHILE @ChunkEndID > @LastUpdatedID
	BEGIN
		BEGIN TRANSACTION;			  
				
		SET @LastUpdatedID = @ChunkEndID;
		
		SELECT TOP ( @ChunkCount ) @ChunkEndID = ChargeVolumeID
		FROM #recordsToProcess
		WHERE ChargeVolumeID > @ChunkEndID
		ORDER BY ChargeVolumeID;
		
		EXEC('
		UPDATE fcv
		SET
			-- Updating the prices for ChargeVolumeDollarsProjection 
			' + @SelectClause + '
		FROM fp.ChargeVolume fcv
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID
			LEFT JOIN [fp].[FactChargeMaster] FCM 
				ON  FCM.BudgetConfigID = fcv.BudgetConfigID 
				AND FCM.ChargeCodeID = fcv.ChargeCodeID
				AND FCM.TimeClassID = 12				
				AND ' + @IsEntityUsedSQL + '
				AND ' + @IsPatientClassUsedSQL + '
		WHERE fcv.BudgetConfigID = ' + @BudgetConfigID + '
			AND fcv.ChargeVolumeID > ' + @LastUpdatedID + '
        	AND fcv.ChargeVolumeID <= ' + @ChunkEndID + '
			AND (' + @WhereClause + ')
		');		
		 
		COMMIT TRANSACTION;
	END
	
END
GO


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

-- fp.procChargeBudgetStampOff
CREATE       PROCEDURE [fp].[procChargeBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
    /*******************************************************************************
    ** Change History
    ********************************************************************************
    ** CID  Date        Author  WI              Description
    ** 1    01-31-2023  MY      JAZZ-48962      Initial Creation
    ** 2    02-21-2023  MY      JAZZ-49484      Update logic to roll up data
    ** 3    03-28-2023  BK      JAZZ-51558      Update to use new table structure
    ** 4    01-03-2024  MZ      JAZZ-65385      Added Target TimeClass
	** 5	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
    *******************************************************************************/

		-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)
	
	-- Clear out existing records for the selected FiscalYear and Budgeted Time Class
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) FROM [int].[FactCDM] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
	
   
    --- Charge Units
	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
		D.DepartmentID,
		D.DepartmentCode,
		CC.ChargeCodeID,
		CC.ChargeCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		PAT.PatientClassID,
		PAT.Code AS [PatientClassCode],
		SL.ServiceLineID AS ServiceLineID,
		SL.Code AS ServiceLine,
		AG.AgeCohortID AS AgeCohortID,
		AG.Code AS AgeCohort,
		MS.MedicalSurgicalID AS MedicalSurgicalID,
		MS.Code AS MedSurg,
		UT.UnitTypeID,
		UT.Name AS [UnitType],
		Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		-- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL
		-- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. 
		SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value
		FROM (
			SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, 
				SUM(BudgetAdjusted01) AS BudgetAdjusted01, SUM(BudgetAdjusted02) AS BudgetAdjusted02, SUM(BudgetAdjusted03) AS BudgetAdjusted03, 
				SUM(BudgetAdjusted04) AS BudgetAdjusted04, SUM(BudgetAdjusted05) AS BudgetAdjusted05, SUM(BudgetAdjusted06) AS BudgetAdjusted06, 
				SUM(BudgetAdjusted07) AS BudgetAdjusted07, SUM(BudgetAdjusted08) AS BudgetAdjusted08, SUM(BudgetAdjusted09) AS BudgetAdjusted09, 
				SUM(BudgetAdjusted10) AS BudgetAdjusted10, SUM(BudgetAdjusted11) AS BudgetAdjusted11, SUM(BudgetAdjusted12) AS BudgetAdjusted12
			FROM fp.ChargeVolume cv 
			WHERE cv.BudgetConfigID = @BudgetConfigID
				AND cv.UnitTypeID = 145
			GROUP BY EntityID, 
				DepartmentID, 
				ServiceLineID, 
				PatientClassID, 
				AgeCohortID, 
				MedicalSurgicalID, 
				ChargeCodeID, 
				UnitTypeID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID
		INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID
		INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID
		INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID
		INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID 
	UNION ALL 
	-- Charge Dollars --- 
	-- NOTE: Currently this logic is not working properly for when (SELECT IsDollarsRemovedFromCharges FROM fp.BudgetConfig) = 0, as dollars are on FactChargeVolume in this case.
	SELECT
		D.DepartmentID,
		D.DepartmentCode,
		CC.ChargeCodeID,
		CC.ChargeCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		PAT.PatientClassID,
		PAT.Code AS [PatientClassCode],
		SL.ServiceLineID AS ServiceLineID,
		SL.Code AS ServiceLine,
		AG.AgeCohortID AS AgeCohortID,
		AG.Code AS AgeCohort,
		MS.MedicalSurgicalID AS MedicalSurgicalID,
		MS.Code AS MedSurg,
		UT.UnitTypeID,
		UT.Name AS [UnitType],
		Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		-- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL
		-- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. 
		SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value
		FROM (
			SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,  
				SUM(BudgetDollarsAdjusted01) AS BudgetDollarsAdjusted01, SUM(BudgetDollarsAdjusted02) AS BudgetDollarsAdjusted02, SUM(BudgetDollarsAdjusted03) AS BudgetDollarsAdjusted03, 
				SUM(BudgetDollarsAdjusted04) AS BudgetDollarsAdjusted04, SUM(BudgetDollarsAdjusted05) AS BudgetDollarsAdjusted05, SUM(BudgetDollarsAdjusted06) AS BudgetDollarsAdjusted06, 
				SUM(BudgetDollarsAdjusted07) AS BudgetDollarsAdjusted07, SUM(BudgetDollarsAdjusted08) AS BudgetDollarsAdjusted08, SUM(BudgetDollarsAdjusted09) AS BudgetDollarsAdjusted09, 
				SUM(BudgetDollarsAdjusted10) AS BudgetDollarsAdjusted10, SUM(BudgetDollarsAdjusted11) AS BudgetDollarsAdjusted11, SUM(BudgetDollarsAdjusted12) AS BudgetDollarsAdjusted12
			FROM fp.ChargeVolume cv 
			WHERE cv.BudgetConfigID = @BudgetConfigID
			GROUP BY EntityID, 
				DepartmentID, 
				ServiceLineID, 
				PatientClassID, 
				AgeCohortID, 
				MedicalSurgicalID, 
				ChargeCodeID, 
				UnitTypeID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (BudgetDollarsAdjusted01, BudgetDollarsAdjusted02, BudgetDollarsAdjusted03, BudgetDollarsAdjusted04, BudgetDollarsAdjusted05, BudgetDollarsAdjusted06, BudgetDollarsAdjusted07, BudgetDollarsAdjusted08, BudgetDollarsAdjusted09, BudgetDollarsAdjusted10, BudgetDollarsAdjusted11, BudgetDollarsAdjusted12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetDollarsAdjusted', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID
		INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID
		INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID
		INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID
		INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID
		INNER JOIN [fw].[DimDepartment] D on D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = 34 -- Charge Dollars
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
END
GO


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

-- fp.procChargeProjectionStampOff
CREATE     PROCEDURE [fp].[procChargeProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
    /*******************************************************************************
    ** Change History
    ********************************************************************************
    ** CID  Date        Author  WI              Description
    ** 1    11-09-2023  AO      JAZZ-62128      Initial Creation
    ** 2    01-03-2024  MZ      JAZZ-65385      Added Target TimeClass 
    ** 3    01-24-2024  MZ      JAZZ-64527      Fix Months Loaded
    ** 4    03-18-2024  MZ      JAZZ-68428      Deleting by Chunks & removed HistoryItemGUID parameter
    ** 5    04-03-2024  MZ      JAZZ-70053      Fix Month Loaded excluding logic
    *******************************************************************************/

		-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

   	-- Clear out existing records for the selected FiscalYear and Projected Time Class
	-- and all months if months loaded included otherwise only months NOT loaded will be cleared
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) c FROM [int].[FactCDM] c
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = c.FiscalMonthID
		WHERE c.FiscalYearID = @FiscalYear
			AND c.TimeClassID = @TargetTimeClassID
			AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded)
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

    --- Charge Units
	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
		D.DepartmentID,
		D.DepartmentCode,
		CC.ChargeCodeID,
		CC.ChargeCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		PAT.PatientClassID,
		PAT.Code AS [PatientClassCode],
		SL.ServiceLineID AS ServiceLineID,
		SL.Code AS ServiceLine,
		AG.AgeCohortID AS AgeCohortID,
		AG.Code AS AgeCohort,
		MS.MedicalSurgicalID AS MedicalSurgicalID,
		MS.Code AS MedSurg,
		UT.UnitTypeID,
		UT.Name AS [UnitType],
		Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		-- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL
		-- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. 
		SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value
		FROM (
			SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, 
				SUM(ProjectionAdjusted01) AS ProjectionAdjusted01, SUM(ProjectionAdjusted02) AS ProjectionAdjusted02, SUM(ProjectionAdjusted03) AS ProjectionAdjusted03, 
				SUM(ProjectionAdjusted04) AS ProjectionAdjusted04, SUM(ProjectionAdjusted05) AS ProjectionAdjusted05, SUM(ProjectionAdjusted06) AS ProjectionAdjusted06, 
				SUM(ProjectionAdjusted07) AS ProjectionAdjusted07, SUM(ProjectionAdjusted08) AS ProjectionAdjusted08, SUM(ProjectionAdjusted09) AS ProjectionAdjusted09, 
				SUM(ProjectionAdjusted10) AS ProjectionAdjusted10, SUM(ProjectionAdjusted11) AS ProjectionAdjusted11, SUM(ProjectionAdjusted12) AS ProjectionAdjusted12
			FROM fp.ChargeVolume cv 
			WHERE cv.BudgetConfigID = @BudgetConfigID
				AND cv.UnitTypeID = 145
			GROUP BY EntityID, 
				DepartmentID, 
				ServiceLineID, 
				PatientClassID, 
				AgeCohortID, 
				MedicalSurgicalID, 
				ChargeCodeID, 
				UnitTypeID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID
		INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID
		INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID
		INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID
		INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID 
		AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded)
	UNION ALL 
	-- Charge Dollars --- 
	-- NOTE: Currently this logic is not working properly for when (SELECT IsDollarsRemovedFromCharges FROM fp.BudgetConfig) = 0, as dollars are on FactChargeVolume in this case.
	SELECT
		D.DepartmentID,
		D.DepartmentCode,
		CC.ChargeCodeID,
		CC.ChargeCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		PAT.PatientClassID,
		PAT.Code AS [PatientClassCode],
		SL.ServiceLineID AS ServiceLineID,
		SL.Code AS ServiceLine,
		AG.AgeCohortID AS AgeCohortID,
		AG.Code AS AgeCohort,
		MS.MedicalSurgicalID AS MedicalSurgicalID,
		MS.Code AS MedSurg,
		UT.UnitTypeID,
		UT.Name AS [UnitType],
		Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		-- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL
		-- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. 
		SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value
		FROM (
			SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID,  
				SUM(ProjectionDollarsAdjusted01) AS ProjectionDollarsAdjusted01, SUM(ProjectionDollarsAdjusted02) AS ProjectionDollarsAdjusted02, SUM(ProjectionDollarsAdjusted03) AS ProjectionDollarsAdjusted03, 
				SUM(ProjectionDollarsAdjusted04) AS ProjectionDollarsAdjusted04, SUM(ProjectionDollarsAdjusted05) AS ProjectionDollarsAdjusted05, SUM(ProjectionDollarsAdjusted06) AS ProjectionDollarsAdjusted06, 
				SUM(ProjectionDollarsAdjusted07) AS ProjectionDollarsAdjusted07, SUM(ProjectionDollarsAdjusted08) AS ProjectionDollarsAdjusted08, SUM(ProjectionDollarsAdjusted09) AS ProjectionDollarsAdjusted09, 
				SUM(ProjectionDollarsAdjusted10) AS ProjectionDollarsAdjusted10, SUM(ProjectionDollarsAdjusted11) AS ProjectionDollarsAdjusted11, SUM(ProjectionDollarsAdjusted12) AS ProjectionDollarsAdjusted12
			FROM fp.ChargeVolume cv 
			WHERE cv.BudgetConfigID = @BudgetConfigID
			GROUP BY EntityID, 
				DepartmentID, 
				ServiceLineID, 
				PatientClassID, 
				AgeCohortID, 
				MedicalSurgicalID, 
				ChargeCodeID, 
				UnitTypeID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (ProjectionDollarsAdjusted01, ProjectionDollarsAdjusted02, ProjectionDollarsAdjusted03, ProjectionDollarsAdjusted04, ProjectionDollarsAdjusted05, ProjectionDollarsAdjusted06, ProjectionDollarsAdjusted07, ProjectionDollarsAdjusted08, ProjectionDollarsAdjusted09, ProjectionDollarsAdjusted10, ProjectionDollarsAdjusted11, ProjectionDollarsAdjusted12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionDollarsAdjusted', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID
		INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID
		INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID
		INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID
		INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID
		INNER JOIN [fw].[DimDepartment] D on D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = 34 -- Charge Dollars
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
		AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded)
END
GO


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

-- fp.procChargeVolumeApplySpread
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2020-03-11  MY          JAZZ-16618      Add Unit Targeting Check for IsCVReportRefreshRequired
** 2 	2022-08-09  JB  		JAZZ-23177		Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 3	2023-03-06	MY			JAZZ-48307		Update charges adjustment to support data model changes
*********************************************************************/
CREATE   PROCEDURE [fp].[procChargeVolumeApplySpread]
  @BudgetConfigID INT,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable;
	IF OBJECT_ID('tempdb..#chargeVolumeIDs') IS NOT NULL DROP TABLE #chargeVolumeIDs;
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;

	DECLARE @typeIdUnits INT = 145;

	CREATE TABLE #filterTable (ChargeVolumeID INT PRIMARY KEY CLUSTERED);
	CREATE TABLE #chargeVolumeIDs (ChargeVolumeID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

   	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #filterTable (ChargeVolumeID)
		SELECT DISTINCT basis.ChargeVolumeID
		FROM [fp].[ChargeVolume] basis
			INNER JOIN [fp].[viewChargeVolumeSpreads] spread 
				ON spread.BudgetConfigID = basis.BudgetConfigID 
				AND spread.DepartmentID = basis.DepartmentID 
				AND spread.ChargeCodeID = basis.ChargeCodeID
				AND spread.PatientClassID = basis.PatientClassID
				AND spread.AgeCohortID = basis.AgeCohortID
				AND spread.MedicalSurgicalID = basis.MedicalSurgicalID
				AND spread.ServiceLineID = basis.ServiceLineID
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID
		WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = @typeIdUnits AND basis.BudgetLockType <> 1
	END 
	ELSE BEGIN
		INSERT INTO #filterTable (ChargeVolumeID)
		SELECT DISTINCT basis.ChargeVolumeID
		FROM [fp].[ChargeVolume] basis
			INNER JOIN [fp].[viewChargeVolumeSpreads] spread 
				ON spread.BudgetConfigID = basis.BudgetConfigID 
				AND spread.DepartmentID = basis.DepartmentID 
				AND spread.ChargeCodeID = basis.ChargeCodeID
				AND spread.PatientClassID = basis.PatientClassID
				AND spread.AgeCohortID = basis.AgeCohortID
				AND spread.MedicalSurgicalID = basis.MedicalSurgicalID
				AND spread.ServiceLineID = basis.ServiceLineID
		WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = @typeIdUnits AND basis.BudgetLockType <> 1
	END


	UPDATE fcv
	SET 
		BudgetLockType = 6, 
		BudgetLockFlag = 1,
		BudgetAdjusted01 = CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8)),
		BudgetAdjusted02 = 
			CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END,
		BudgetAdjusted03 = 
			CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END,
		BudgetAdjusted04 = 
			CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END,
		BudgetAdjusted05 = 
			CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END,
		BudgetAdjusted06 = 
			CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END,
		BudgetAdjusted07 = 
			CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END,
		BudgetAdjusted08 = 
			CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END,
		BudgetAdjusted09 = 
			CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END,
		BudgetAdjusted10 = 
			CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END,
		BudgetAdjusted11 = 
			CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END,
		BudgetAdjusted12 = 
			CASE WHEN SpreadPercentage12 != 0
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
	OUTPUT 
	    INSERTED.ChargeVolumeID
	INTO
	    #chargeVolumeIDs (ChargeVolumeID)
	FROM [fp].[ChargeVolume] fcv
		INNER JOIN #filterTable tmp on fcv.ChargeVolumeID = tmp.ChargeVolumeID
		INNER JOIN [fp].[viewChargeVolumeSpreads] charsp
			ON charsp.BudgetConfigID = fcv.BudgetConfigID
				AND charsp.DepartmentID = fcv.DepartmentID 
				AND charsp.ChargeCodeID = fcv.ChargeCodeID
				AND charsp.PatientClassID = fcv.PatientClassID
				AND charsp.AgeCohortID = fcv.AgeCohortID
				AND charsp.MedicalSurgicalID = fcv.MedicalSurgicalID
				AND charsp.ServiceLineID = fcv.ServiceLineID
	WHERE charsp.IsInactive = 0
		AND (
			BudgetAdjusted01 != CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8))
			OR BudgetAdjusted02 != 
				CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
			OR BudgetAdjusted03 != 
				CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
			OR BudgetAdjusted04 != 
				CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
			OR BudgetAdjusted05 != 
				CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
			OR BudgetAdjusted06 != 
				CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
			OR BudgetAdjusted07 != 
				CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
			OR BudgetAdjusted08 != 
				CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
			OR BudgetAdjusted09 != 
				CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
			OR BudgetAdjusted10 != 
				CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
			OR BudgetAdjusted11 != 
				CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
			OR BudgetAdjusted12 != 
				CASE WHEN SpreadPercentage12 != 0
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
			OR BudgetLockType != 6
			OR BudgetLockFlag != 1
		)

END;
GO


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

-- fp.procChargeVolumeCopyNewItems
CREATE   PROCEDURE [fp].[procChargeVolumeCopyNewItems] 
	@SourceBudgetConfigID INT,
	@SourceEntityGroupConfigID INT,
	@BudgetConfigID INT,
	@EntityGroupConfigID INT 
AS 
BEGIN
/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   		Description
	 ** 1 	 2021-06-28  NT		 JAZZ-21664 Add missing provider dimensions
	 ** 2	 2022-09-01	 JB		 JAZZ-32095	Remove Payor and PayorGroupID from joins.
	 ** 3	 2023-05-04	 BW		 JAZZ-54095	Updated for new data model
	 ** 4	 2023-06-01	 AO		 JAZZ-55827 Excluded Add Provider records
	 *************************************************************/	
INSERT INTO [fp].[ChargeVolume] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, UnitTypeID, AgeCohortID, ChargeCodeID, AddDate,
	MedicalSurgicalID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID,
	PerformingProviderSpecialtyID, BillingCPTID,
	SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
	SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
	InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
	InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
	IsNew)
SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, UnitTypeID, AgeCohortID, ChargeCodeID, AddDate,
	MedicalSurgicalID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, 
	PerformingProviderSpecialtyID, BillingCPTID,
	SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
	SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
	InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
	InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
	IsNew
FROM [fp].[ChargeVolume]
LEFT JOIN [fp].[AddProviderSummary] ON ServiceProviderID = ProviderID
WHERE BudgetConfigID = @SourceBudgetConfigID 
	  AND EntityGroupConfigID = @SourceEntityGroupConfigID 
	  AND IsNew = 1 
	  AND ProviderID IS NULL

END
GO


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

-- fp.procClearBenefitDrivers
CREATE PROC [fp].[procClearBenefitDrivers]
	@EntityGroupConfigID INT,
	@TimeClassID INT,
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY

 AS
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 *************************************************************/
	 
	CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int)
	INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID)
	SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)


	IF (@TimeClassID = 2)
	BEGIN
			
		UPDATE budg
		SET
			AdjustedValue01 = 0, AdjustedValue02 = 0, AdjustedValue03 = 0, AdjustedValue04 = 0, AdjustedValue05 = 0, AdjustedValue06 = 0,
		    AdjustedValue07 = 0, AdjustedValue08 = 0, AdjustedValue09 = 0, AdjustedValue10 = 0, AdjustedValue11 = 0, AdjustedValue12 = 0,
			FlexedValue01 = 0, FlexedValue02 = 0, FlexedValue03 = 0, FlexedValue04 = 0, FlexedValue05 = 0, FlexedValue06 = 0,
		    FlexedValue07 = 0, FlexedValue08 = 0, FlexedValue09 = 0, FlexedValue10 = 0, FlexedValue11 = 0, FlexedValue12 = 0
		FROM [fp].[FactBenefits] ben
			INNER JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = ben.DepartmentID or ft.DepartmentID is null) 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND UnitTypeID IN (144, 169) -- FTEs and Salaries
			AND (ft.BudgetPhaseID IS NULL OR budg.BudgetPhaseID = ft.BudgetPhaseID)
			
	END ELSE BEGIN
		
		UPDATE proj
		SET
			proj.AdjustedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE 0 END,
			proj.AdjustedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE 0 END,
			proj.AdjustedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE 0 END,
			proj.AdjustedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE 0 END,
			proj.AdjustedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE 0 END,
			proj.AdjustedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE 0 END,
			proj.AdjustedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE 0 END,
			proj.AdjustedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE 0 END,
			proj.AdjustedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE 0 END,
			proj.AdjustedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE 0 END,
			proj.AdjustedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE 0 END,
			proj.AdjustedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE 0 END,
			proj.FlexedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE 0 END,
			proj.FlexedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE 0 END,
			proj.FlexedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE 0 END,
			proj.FlexedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE 0 END,
			proj.FlexedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE 0 END,
			proj.FlexedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE 0 END,
			proj.FlexedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE 0 END,
			proj.FlexedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE 0 END,
			proj.FlexedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE 0 END,
			proj.FlexedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE 0 END,
			proj.FlexedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE 0 END,
			proj.FlexedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE 0 END		
		FROM [fp].[FactBenefits] ben
			INNER JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = ben.DepartmentID or ft.DepartmentID is null) 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND UnitTypeID IN (144, 169) -- FTEs and Salaries
			AND (ft.BudgetPhaseID IS NULL OR proj.BudgetPhaseID = ft.BudgetPhaseID)
	
	END
GO


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

-- fp.procClearBenefitDrivers_InitialValue
CREATE PROC [fp].[procClearBenefitDrivers_InitialValue]
	@EntityGroupConfigID INT,
	@TimeClassID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY

 AS
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 *************************************************************/
	 
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)


	IF (@TimeClassID = 2)
	BEGIN
			
		UPDATE tbl
		SET
			InitialBudget01 = 0, InitialBudget02 = 0, InitialBudget03 = 0, InitialBudget04 = 0, InitialBudget05 = 0, InitialBudget06 = 0,
		    InitialBudget07 = 0, InitialBudget08 = 0, InitialBudget09 = 0, InitialBudget10 = 0, InitialBudget11 = 0, InitialBudget12 = 0
		FROM [fp].[FactBenefits] tbl
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = tbl.DepartmentID or ft.DepartmentID is null)
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND UnitTypeID IN (144, 169) -- FTEs and Salaries
			
	END ELSE BEGIN
					
		DECLARE @MonthsLoaded INT	
		SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = @EntityGroupConfigID
		
		UPDATE tbl
		SET
			InitialProjection01 = CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE 0 END,
			InitialProjection02 = CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE 0 END,
			InitialProjection03 = CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE 0 END,
			InitialProjection04 = CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE 0 END,
			InitialProjection05 = CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE 0 END,
			InitialProjection06 = CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE 0 END,
			InitialProjection07 = CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE 0 END,
			InitialProjection08 = CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE 0 END,
			InitialProjection09 = CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE 0 END,
			InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE 0 END,
			InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE 0 END,
			InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE 0 END
		FROM [fp].[FactBenefits] tbl
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = tbl.DepartmentID or ft.DepartmentID is null)
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND UnitTypeID IN (144, 169) -- FTEs and Salaries
	
	END
GO


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

-- fp.procClearChangeHistory
/************************************************************** 
** Change History  
************************************************************** 
** CID  Date        Author  WI			Description 
** 1    2018-10-10  IP      B-20922		Added using source dimensionality to ClearChangeHistory   
** 2    2018-10-19  GF      B-20922		Fix additional filter handling 
** 3    2018-10-23  IP      B-20922		Made additional refactoring 
** 4    2020-01-12  MY      B-25963		Fixing all of the above
** 5    2020-07-24  BK      B-26717		Add targeting for Service Line Encounters
** 6    2020-12-07  MY      X-XXXXX		Increased precision for delete setting to allow larger setting
** 7    2022-09-19  BK      JAZZ-42503  Add ProviderID to targeting for Service Line Encounters
** 8    2023-02-15  BW      JAZZ-48306  Update base table name for new data model - Service Line Encounters
** 9    2023-08-11	AO		JAZZ-57724	Fixed base table name for Reimbursement GL
** 10   2023-08-11	AO		JAZZ-57724	Fixed base table name for Reimbursement GL
** 11   2024-01-02	MY		JAZZ-64770	Fix Restructure Overwrite
*************************************************************/
CREATE   PROCEDURE [fp].[procClearChangeHistory] (
	@Direction VARCHAR(250)-- Benefits/ChargeVolume/GeneralLedger/Staffing/Statistics/ServiceLineEncounter/Reimbursement/ReimbursementGeneralLedger
	,@BudgetConfigID INT
	,@AdditionalFilter VARCHAR(max) = '1=1'
	,@iterationRowCount INT = 100000
	,@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
	,@isDebug BIT = 0
	)
AS
BEGIN
	DECLARE @isFilterPresent BIT = CASE WHEN (SELECT COUNT(*) FROM @SourceDimensionality) >= 1 THEN 1 ELSE 0 END;
	DECLARE @sqlCommand NVARCHAR(MAX)
	DECLARE @tableType VARCHAR(10) = CASE WHEN (@Direction IN ('ServiceLineEncounter', 'ChargeVolume', 'GeneralLedger', 'ReimbursementGeneralLedger', 'Staffing')) THEN '' ELSE 'Fact' END;

	DECLARE @FilterLogic NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN '
		CREATE TABLE #FilteringTable (
			DepartmentID INT,
			INDEX ix_1 NONCLUSTERED (DepartmentID)
		)
		INSERT INTO #FilteringTable (DepartmentID)
		SELECT DepartmentID
		FROM @SourceDimensionality' ELSE '' END;

	DECLARE @FilterJoin NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN 'INNER JOIN #FilteringTable ft on ft.DepartmentID = res.DepartmentID' ELSE '' END;

	IF @Direction = 'ServiceLineEncounter' AND @isFilterPresent = 1 BEGIN
		SET @FilterLogic = '
		CREATE TABLE #FilteringTable (
			EntityID INT, ServiceLineID INT, ProviderID INT,
			INDEX ix_1 NONCLUSTERED (EntityID)
		)
		INSERT INTO #FilteringTable (EntityID, ServiceLineID, ProviderID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID, map.ProviderID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map
		INNER JOIN @SourceDimensionality ft on map.DepartmentID = ft.DepartmentID
		WHERE map.BudgetConfigID =  ' + CAST(@BudgetConfigID AS VARCHAR) + '; '

		SET @FilterJoin = 'INNER JOIN #FilteringTable ft on ft.EntityID = res.EntityID AND ft.ServiceLineID = res.ServiceLineID AND ft.ProviderID = res.ProviderID'
	END

	IF (@isFilterPresent = 0)
	BEGIN
		SET @sqlCommand = '
			DECLARE @Rowcount INT = 1
			WHILE @Rowcount > 0
			BEGIN
				DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch 
				FROM [fp].[' + @Direction + 'ChangeHistory] ch 
				WHERE BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + CASE 
				WHEN @AdditionalFilter = '1=1'
					THEN ''
				ELSE ' AND ' + @AdditionalFilter
				END + '
			  SET @Rowcount = @@ROWCOUNT
			END
		'
	END ELSE BEGIN
		SET @sqlCommand = @FilterLogic + 
		'
			SELECT Ch.' + @Direction + 'ID 
			INTO #DeleteIDs 
			FROM [fp].[' + @tableType + @Direction + '] res
				' + @FilterJoin + '
				INNER JOIN [fp].[' + @Direction + 'ChangeHistory] ch ON ch.' + @Direction + 'ID = res.' + @Direction + 'ID
			WHERE res.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10))  + CASE 
				WHEN @AdditionalFilter = '1=1'
					THEN ''
				ELSE ' AND ' + @AdditionalFilter
				END + '
			CREATE CLUSTERED INDEX idx_DeleteIDs on #DeleteIDs (' + @Direction + 'ID)
			DECLARE @Rowcount INT = 1
			WHILE @Rowcount > 0
			BEGIN
				DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch 
				FROM [fp].[' + @Direction + 'ChangeHistory] ch 
					INNER JOIN #DeleteIDs D ON ch.' + @Direction + 'ID = D.' + @Direction + 'ID
				WHERE ch.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + '
			  SET @Rowcount = @@ROWCOUNT
			END
		'
	END

	IF @isDebug = 1
		PRINT @sqlCommand
	ELSE
		EXECUTE sp_executesql @sqlCommand
			,N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY'
			,@SourceDimensionality = @SourceDimensionality
END
GO


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

-- fp.procClearChargeInvalidReimbursement
/**************************************************************  
** Change History  
**************************************************************  
** CID  Date		Author	WI		   Description  
** 1	2023-05-12  MY		JAZZ-54661 Initial  
** 2	2024-01-11  AO		JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config   
** 3	2024-02-16  MD		JAZZ-67663 Make reimbursement charges stop clearing out on CV update  
** 4	2024-02-28  MD		JAZZ-68291 Add targeting to update  
*************************************************************/  
CREATE     PROCEDURE [fp].[procClearChargeInvalidReimbursement]  
 @BudgetConfigID INT,  
 @IsReimbursementGLEnabled BIT = 0,   
 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,  
 @IsDebug BIT = 0   
AS  
BEGIN   
  
 DECLARE @IsMedicalSurgicalUsed BIT = 0,  
   @IsMsdrgUsed BIT = 0,  
   @IsCptUsed BIT = 0,  
   @IsUBRevCodeUsed BIT = 0;  
  
 SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END  
 FROM fp.SectionSetup ss   
   INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID   
 WHERE bc.BudgetConfigID = @BudgetConfigID   
   AND ss.PlanSectionID = 7 -- Reimbursement   
   AND ss.SubSectionID = 6 -- Reimbursement - Charges   
   AND ss.LevelID = 'MedicalSurgicalID'  
  
 SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END  
 FROM fp.SectionSetup ss   
   INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID   
 WHERE bc.BudgetConfigID = @BudgetConfigID   
   AND ss.PlanSectionID = 7 -- Reimbursement   
   AND ss.SubSectionID = 6 -- Reimbursement - Charges   
   AND ss.LevelID = 'MSDRGID'  
  
 SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END  
 FROM fp.SectionSetup ss   
   INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID   
 WHERE bc.BudgetConfigID = @BudgetConfigID   
   AND ss.PlanSectionID = 7 -- Reimbursement   
   AND ss.SubSectionID = 6 -- Reimbursement - Charges   
   AND ss.LevelID = 'PrimaryCPTID'  
  
 SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END  
 FROM fp.SectionSetup ss   
   INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID   
 WHERE bc.BudgetConfigID = @BudgetConfigID   
   AND ss.PlanSectionID = 7 -- Reimbursement   
   AND ss.SubSectionID = 6 -- Reimbursement - Charges   
   AND ss.LevelID = 'UBRevCodeID'  
     
 -- Clean up old tables (and so SSMS is happy)  
 IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;  
 IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges;  
 IF OBJECT_ID('tempdb..#invalidReimbursementIds') IS NOT NULL DROP TABLE #invalidReimbursementIds;  
   
 CREATE TABLE #invalidReimbursementIds (ReimbursementChargesID INT);  
  
 CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);  
 INSERT INTO #ChargeVolumeDepartments (DepartmentID)  
 SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)  
  
 CREATE TABLE #factReimbursementCharges (  
  BudgetConfigID INT,  
  EntityGroupConfigID INT,  
  EntityID INT,  
  PatientClassID INT,  
  ServiceLineID INT,  
  ServiceLineRollupID INT,  
  MedicalSurgicalID INT,  
  PayorID INT,  
  PayorGroupID INT,  
  MSDRGID INT,  
  PrimaryCPTID INT,  
  UBRevCodeID INT  
 )  
  
 -- If the filter is empty, passing in all to avoid a bunch of duplicate statements    
 IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)  
 BEGIN  
  INSERT INTO #ChargeVolumeDepartments (DepartmentID)  
  SELECT DISTINCT DepartmentID   
  FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)  
  WHERE BudgetConfigID  = @BudgetConfigID   
 END  
  
 SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID,   
  CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID,   
  CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID,   
  CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,  
  CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID  
 INTO #reimbursementTargeting  
 FROM fp.ChargeVolume cv   
  INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID  
  INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID  
 WHERE cv.BudgetConfigID = @BudgetConfigID  
    
 -- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well.  
 -- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup  
 INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID,   
  MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID)  
 SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID,   
  CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID,    
  sd.PayorID, sd.PayorGroupID,   
  CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID,   
  CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,  
  CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID  
 FROM fp.ChargeVolume cv   
  INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID  
  INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID  
  INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID   
         AND cv.PatientClassID = sd.PatientClassID  
         AND cv.ServiceLineID = sd.ServiceLineID  
   AND cv.AgeCohortID = sd.AgeCohortID  
         AND cv.MedicalSurgicalID = sd.MedicalSurgicalID  
         AND cv.MSDRGID = sd.MSDRGID  
         AND cv.PrimaryCPTID = sd.CPTID  
         AND cv.ServiceProviderID = sd.ProviderID  
         AND cv.EntityGroupConfigID = sd.EntityGroupConfigID  
 WHERE cv.BudgetConfigID = @BudgetConfigID  
  
 UNION  
  
 SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID,   
  CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID,   
  0 AS PayorID, 0 AS PayorGroupID,  
  CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID,   
  CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,  
  CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID  
 FROM fp.ChargeVolume cv   
  INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID  
  INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID  
  LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID   
         AND cv.PatientClassID = sd.PatientClassID  
         AND cv.ServiceLineID = sd.ServiceLineID  
   AND cv.AgeCohortID = sd.AgeCohortID  
         AND cv.MedicalSurgicalID = sd.MedicalSurgicalID  
         AND cv.MSDRGID = sd.MSDRGID  
         AND cv.PrimaryCPTID = sd.CPTID  
         AND cv.ServiceProviderID = sd.ProviderID  
         AND cv.EntityGroupConfigID = sd.EntityGroupConfigID  
  LEFT JOIN #factReimbursementCharges tmp ON   
   cv.BudgetConfigID = tmp.BudgetConfigID  
   AND cv.EntityGroupConfigID = tmp.EntityGroupConfigID  
   AND cv.EntityID = tmp.EntityID  
   AND cv.PatientClassID = tmp.PatientClassID  
   AND cv.ServiceLineID = tmp.ServiceLineID  
   AND cv.MedicalSurgicalID = tmp.MedicalSurgicalID  
   AND tmp.PayorID = 0  
   AND tmp.PayorGroupID = 0  
   AND cv.MSDRGID = tmp.MSDRGID  
   AND cv.PrimaryCPTID = tmp.PrimaryCPTID  
   AND cv.UBRevCodeID = tmp.UBRevCodeID  
 WHERE cv.BudgetConfigID = @BudgetConfigID  
  AND sd.EntityID IS NULL  
  AND tmp.BudgetConfigID IS NULL -- Ensure that we didn't already add the 0 PayorID/0 PayorGroupID  
  
 IF (@IsDebug = 1)  
 BEGIN  
  SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments  
  SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID],  
    [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID]  
  FROM #factReimbursementCharges  
 END ELSE  
 BEGIN  
  
  -- Set everything to 0 where it's in Reimbursement but not in Charges    
  UPDATE frc  
  SET  
   InitialBudgetChargeDollars01 = 0,  
   InitialBudgetChargeDollars02 = 0,  
   InitialBudgetChargeDollars03 = 0,  
   InitialBudgetChargeDollars04 = 0,  
   InitialBudgetChargeDollars05 = 0,  
   InitialBudgetChargeDollars06 = 0,  
   InitialBudgetChargeDollars07 = 0,  
   InitialBudgetChargeDollars08 = 0,  
   InitialBudgetChargeDollars09 = 0,  
   InitialBudgetChargeDollars10 = 0,  
   InitialBudgetChargeDollars11 = 0,  
   InitialBudgetChargeDollars12 = 0,  
  
   InitialBudgetNetAsPercentOfCharge01 = 0,  
   InitialBudgetNetAsPercentOfCharge02 = 0,  
   InitialBudgetNetAsPercentOfCharge03 = 0,  
   InitialBudgetNetAsPercentOfCharge04 = 0,  
   InitialBudgetNetAsPercentOfCharge05 = 0,  
   InitialBudgetNetAsPercentOfCharge06 = 0,  
   InitialBudgetNetAsPercentOfCharge07 = 0,  
   InitialBudgetNetAsPercentOfCharge08 = 0,  
   InitialBudgetNetAsPercentOfCharge09 = 0,  
   InitialBudgetNetAsPercentOfCharge10 = 0,  
   InitialBudgetNetAsPercentOfCharge11 = 0,  
   InitialBudgetNetAsPercentOfCharge12 = 0,  
  
   InitialBudgetNetPerDiem01 = 0,  
   InitialBudgetNetPerDiem02 = 0,  
   InitialBudgetNetPerDiem03 = 0,  
   InitialBudgetNetPerDiem04 = 0,  
   InitialBudgetNetPerDiem05 = 0,  
   InitialBudgetNetPerDiem06 = 0,  
   InitialBudgetNetPerDiem07 = 0,  
   InitialBudgetNetPerDiem08 = 0,  
   InitialBudgetNetPerDiem09 = 0,  
   InitialBudgetNetPerDiem10 = 0,  
   InitialBudgetNetPerDiem11 = 0,  
   InitialBudgetNetPerDiem12 = 0,  
  
   InitialProjectionChargeDollars01 = 0,  
   InitialProjectionChargeDollars02 = 0,  
   InitialProjectionChargeDollars03 = 0,  
   InitialProjectionChargeDollars04 = 0,  
   InitialProjectionChargeDollars05 = 0,  
   InitialProjectionChargeDollars06 = 0,  
   InitialProjectionChargeDollars07 = 0,  
   InitialProjectionChargeDollars08 = 0,  
   InitialProjectionChargeDollars09 = 0,  
   InitialProjectionChargeDollars10 = 0,  
   InitialProjectionChargeDollars11 = 0,  
   InitialProjectionChargeDollars12 = 0,  
  
   InitialProjectionNetAsPercentOfCharge01 = 0,  
   InitialProjectionNetAsPercentOfCharge02 = 0,  
   InitialProjectionNetAsPercentOfCharge03 = 0,  
   InitialProjectionNetAsPercentOfCharge04 = 0,  
   InitialProjectionNetAsPercentOfCharge05 = 0,  
   InitialProjectionNetAsPercentOfCharge06 = 0,  
   InitialProjectionNetAsPercentOfCharge07 = 0,  
   InitialProjectionNetAsPercentOfCharge08 = 0,  
   InitialProjectionNetAsPercentOfCharge09 = 0,  
   InitialProjectionNetAsPercentOfCharge10 = 0,  
   InitialProjectionNetAsPercentOfCharge11 = 0,  
   InitialProjectionNetAsPercentOfCharge12 = 0,  
  
   InitialProjectionNetPerDiem01 = 0,  
   InitialProjectionNetPerDiem02 = 0,  
   InitialProjectionNetPerDiem03 = 0,  
   InitialProjectionNetPerDiem04 = 0,  
   InitialProjectionNetPerDiem05 = 0,  
   InitialProjectionNetPerDiem06 = 0,  
   InitialProjectionNetPerDiem07 = 0,  
   InitialProjectionNetPerDiem08 = 0,  
   InitialProjectionNetPerDiem09 = 0,  
   InitialProjectionNetPerDiem10 = 0,  
   InitialProjectionNetPerDiem11 = 0,  
   InitialProjectionNetPerDiem12 = 0     
  OUTPUT   
         INSERTED.ReimbursementChargesID  
     INTO  
         #invalidReimbursementIds (ReimbursementChargesID)   
  FROM fp.FactReimbursementCharges frc 
  INNER JOIN #reimbursementTargeting rt ON
	rt.BudgetConfigID = frc.BudgetConfigID
	AND rt.EntityGroupConfigID = frc.EntityGroupConfigID
	AND rt.EntityID = frc.EntityID
	AND rt.PatientClassID = frc.PatientClassID
	AND rt.ServiceLineID = frc.ServiceLineID
	AND rt.ServiceLineRollupID = frc.ServiceLineRollupID
	AND rt.MedicalSurgicalID = frc.MedicalSurgicalID
	AND rt.MSDRGID = frc.MSDRGID
	AND rt.PrimaryCPTID = frc.PrimaryCPTID
	AND rt.UBRevCodeID = frc.UBRevCodeID
   LEFT JOIN #factReimbursementCharges tmp ON   
    frc.BudgetConfigID = tmp.BudgetConfigID  
    AND frc.EntityGroupConfigID = tmp.EntityGroupConfigID  
    AND frc.EntityID = tmp.EntityID  
    AND frc.PatientClassID = tmp.PatientClassID  
    AND frc.ServiceLineID = tmp.ServiceLineID  
    AND frc.ServiceLineRollupID = tmp.ServiceLineRollupID  
    AND frc.MedicalSurgicalID = tmp.MedicalSurgicalID  
    AND frc.PayorID = tmp.PayorID  
    AND frc.PayorGroupID = tmp.PayorGroupID  
    AND frc.MSDRGID = tmp.MSDRGID  
    AND frc.PrimaryCPTID = tmp.PrimaryCPTID  
    AND frc.UBRevCodeID = tmp.UBRevCodeID  
   LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID  
   LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = frc.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID  
  WHERE frc.BudgetConfigID = @BudgetConfigID  
   AND ((tmp.BudgetConfigID IS NULL)  
   OR (@IsReimbursementGLEnabled = 1 AND ((bc.DefaultReimbursementNetRevenueModelID <> 1 AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 1)) OR rnrm.NetRevenueModelID <> 1)))    
   --JAZZ-67663 - Commenting out for now because CV updates are incorrectly zeroing out reimbursement SLE data.  
   --OR @IsReimbursementGLEnabled = 0   
  
  UPDATE fcrb  
  SET  
   LockType = 0,  
   LockFlag = 0,  
  
   AdjustedChargeDollars01 = 0,  
   AdjustedChargeDollars02 = 0,  
   AdjustedChargeDollars03 = 0,  
   AdjustedChargeDollars04 = 0,  
   AdjustedChargeDollars05 = 0,  
   AdjustedChargeDollars06 = 0,  
   AdjustedChargeDollars07 = 0,  
   AdjustedChargeDollars08 = 0,  
   AdjustedChargeDollars09 = 0,  
   AdjustedChargeDollars10 = 0,  
   AdjustedChargeDollars11 = 0,  
   AdjustedChargeDollars12 = 0,  
  
   AdjustedNetAsPercentOfCharge01 = 0,  
   AdjustedNetAsPercentOfCharge02 = 0,  
   AdjustedNetAsPercentOfCharge03 = 0,  
   AdjustedNetAsPercentOfCharge04 = 0,  
   AdjustedNetAsPercentOfCharge05 = 0,  
   AdjustedNetAsPercentOfCharge06 = 0,  
   AdjustedNetAsPercentOfCharge07 = 0,  
   AdjustedNetAsPercentOfCharge08 = 0,  
   AdjustedNetAsPercentOfCharge09 = 0,  
   AdjustedNetAsPercentOfCharge10 = 0,  
   AdjustedNetAsPercentOfCharge11 = 0,  
   AdjustedNetAsPercentOfCharge12 = 0,  
  
   AdjustedNetPerDiem01 = 0,  
   AdjustedNetPerDiem02 = 0,  
   AdjustedNetPerDiem03 = 0,  
   AdjustedNetPerDiem04 = 0,  
   AdjustedNetPerDiem05 = 0,  
   AdjustedNetPerDiem06 = 0,  
   AdjustedNetPerDiem07 = 0,  
   AdjustedNetPerDiem08 = 0,  
   AdjustedNetPerDiem09 = 0,  
   AdjustedNetPerDiem10 = 0,  
   AdjustedNetPerDiem11 = 0,  
   AdjustedNetPerDiem12 = 0  
  FROM fp.FactReimbursementChargesBudget fcrb  
   INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementChargesID = fcrb.ReimbursementChargesID  
  
  UPDATE fcrb  
  SET  
   LockType = 0,  
   LockFlag = 0,  
  
   AdjustedChargeDollars01 = 0,  
   AdjustedChargeDollars02 = 0,  
   AdjustedChargeDollars03 = 0,  
   AdjustedChargeDollars04 = 0,  
   AdjustedChargeDollars05 = 0,  
   AdjustedChargeDollars06 = 0,  
   AdjustedChargeDollars07 = 0,  
   AdjustedChargeDollars08 = 0,  
   AdjustedChargeDollars09 = 0,  
   AdjustedChargeDollars10 = 0,  
   AdjustedChargeDollars11 = 0,  
   AdjustedChargeDollars12 = 0,  
  
   AdjustedNetAsPercentOfCharge01 = 0,  
   AdjustedNetAsPercentOfCharge02 = 0,  
   AdjustedNetAsPercentOfCharge03 = 0,  
   AdjustedNetAsPercentOfCharge04 = 0,  
   AdjustedNetAsPercentOfCharge05 = 0,  
   AdjustedNetAsPercentOfCharge06 = 0,  
   AdjustedNetAsPercentOfCharge07 = 0,  
   AdjustedNetAsPercentOfCharge08 = 0,  
   AdjustedNetAsPercentOfCharge09 = 0,  
   AdjustedNetAsPercentOfCharge10 = 0,  
   AdjustedNetAsPercentOfCharge11 = 0,  
   AdjustedNetAsPercentOfCharge12 = 0,  
  
   AdjustedNetPerDiem01 = 0,  
   AdjustedNetPerDiem02 = 0,  
   AdjustedNetPerDiem03 = 0,  
   AdjustedNetPerDiem04 = 0,  
   AdjustedNetPerDiem05 = 0,  
   AdjustedNetPerDiem06 = 0,  
   AdjustedNetPerDiem07 = 0,  
   AdjustedNetPerDiem08 = 0,  
   AdjustedNetPerDiem09 = 0,  
   AdjustedNetPerDiem10 = 0,  
   AdjustedNetPerDiem11 = 0,  
   AdjustedNetPerDiem12 = 0  
  FROM fp.FactReimbursementChargesProjection fcrb  
   INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementChargesID = fcrb.ReimbursementChargesID  
     
  UPDATE fcrb  
  SET  
   PriorYearActualChargeDollars01 = 0,  
   PriorYearActualChargeDollars02 = 0,  
   PriorYearActualChargeDollars03 = 0,  
   PriorYearActualChargeDollars04 = 0,  
   PriorYearActualChargeDollars05 = 0,  
   PriorYearActualChargeDollars06 = 0,  
   PriorYearActualChargeDollars07 = 0,  
   PriorYearActualChargeDollars08 = 0,  
   PriorYearActualChargeDollars09 = 0,  
   PriorYearActualChargeDollars10 = 0,  
   PriorYearActualChargeDollars11 = 0,  
   PriorYearActualChargeDollars12 = 0,  
  
   ActualYTDChargeDollars01 = 0,  
   ActualYTDChargeDollars02 = 0,  
   ActualYTDChargeDollars03 = 0,  
   ActualYTDChargeDollars04 = 0,  
   ActualYTDChargeDollars05 = 0,  
   ActualYTDChargeDollars06 = 0,  
   ActualYTDChargeDollars07 = 0,  
   ActualYTDChargeDollars08 = 0,  
   ActualYTDChargeDollars09 = 0,  
   ActualYTDChargeDollars10 = 0,  
   ActualYTDChargeDollars11 = 0,  
   ActualYTDChargeDollars12 = 0,  
  
   CurrentYearBudgetChargeDollars01 = 0,  
   CurrentYearBudgetChargeDollars02 = 0,  
   CurrentYearBudgetChargeDollars03 = 0,  
   CurrentYearBudgetChargeDollars04 = 0,  
   CurrentYearBudgetChargeDollars05 = 0,  
   CurrentYearBudgetChargeDollars06 = 0,  
   CurrentYearBudgetChargeDollars07 = 0,  
   CurrentYearBudgetChargeDollars08 = 0,  
   CurrentYearBudgetChargeDollars09 = 0,  
   CurrentYearBudgetChargeDollars10 = 0,  
   CurrentYearBudgetChargeDollars11 = 0,  
   CurrentYearBudgetChargeDollars12 = 0,  
  
   CurrentYearBudgetChargeUnits01 = 0,  
   CurrentYearBudgetChargeUnits02 = 0,  
   CurrentYearBudgetChargeUnits03 = 0,  
   CurrentYearBudgetChargeUnits04 = 0,  
   CurrentYearBudgetChargeUnits05 = 0,  
   CurrentYearBudgetChargeUnits06 = 0,  
   CurrentYearBudgetChargeUnits07 = 0,  
   CurrentYearBudgetChargeUnits08 = 0,  
   CurrentYearBudgetChargeUnits09 = 0,  
   CurrentYearBudgetChargeUnits10 = 0,  
   CurrentYearBudgetChargeUnits11 = 0,  
   CurrentYearBudgetChargeUnits12 = 0,  
  
   PriorYearActualNetAsPercentOfCharge01 = 0,  
   PriorYearActualNetAsPercentOfCharge02 = 0,  
   PriorYearActualNetAsPercentOfCharge03 = 0,  
   PriorYearActualNetAsPercentOfCharge04 = 0,  
   PriorYearActualNetAsPercentOfCharge05 = 0,  
   PriorYearActualNetAsPercentOfCharge06 = 0,  
   PriorYearActualNetAsPercentOfCharge07 = 0,  
   PriorYearActualNetAsPercentOfCharge08 = 0,  
   PriorYearActualNetAsPercentOfCharge09 = 0,  
   PriorYearActualNetAsPercentOfCharge10 = 0,  
   PriorYearActualNetAsPercentOfCharge11 = 0,  
   PriorYearActualNetAsPercentOfCharge12 = 0,  
  
   ActualYTDNetAsPercentOfCharge01 = 0,  
   ActualYTDNetAsPercentOfCharge02 = 0,  
   ActualYTDNetAsPercentOfCharge03 = 0,  
   ActualYTDNetAsPercentOfCharge04 = 0,  
   ActualYTDNetAsPercentOfCharge05 = 0,  
   ActualYTDNetAsPercentOfCharge06 = 0,  
   ActualYTDNetAsPercentOfCharge07 = 0,  
   ActualYTDNetAsPercentOfCharge08 = 0,  
   ActualYTDNetAsPercentOfCharge09 = 0,  
   ActualYTDNetAsPercentOfCharge10 = 0,  
   ActualYTDNetAsPercentOfCharge11 = 0,  
   ActualYTDNetAsPercentOfCharge12 = 0,  
  
   CurrentYearBudgetNetAsPercentOfCharge01 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge02 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge03 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge04 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge05 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge06 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge07 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge08 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge09 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge10 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge11 = 0,  
   CurrentYearBudgetNetAsPercentOfCharge12 = 0,  
  
   PriorYearActualNetPerDiem01 = 0,  
   PriorYearActualNetPerDiem02 = 0,  
   PriorYearActualNetPerDiem03 = 0,  
   PriorYearActualNetPerDiem04 = 0,  
   PriorYearActualNetPerDiem05 = 0,  
   PriorYearActualNetPerDiem06 = 0,  
   PriorYearActualNetPerDiem07 = 0,  
   PriorYearActualNetPerDiem08 = 0,  
   PriorYearActualNetPerDiem09 = 0,  
   PriorYearActualNetPerDiem10 = 0,  
   PriorYearActualNetPerDiem11 = 0,  
   PriorYearActualNetPerDiem12 = 0,  
  
   ActualYTDNetPerDiem01 = 0,  
   ActualYTDNetPerDiem02 = 0,  
   ActualYTDNetPerDiem03 = 0,  
   ActualYTDNetPerDiem04 = 0,     ActualYTDNetPerDiem05 = 0,  
   ActualYTDNetPerDiem06 = 0,  
   ActualYTDNetPerDiem07 = 0,  
   ActualYTDNetPerDiem08 = 0,  
   ActualYTDNetPerDiem09 = 0,  
   ActualYTDNetPerDiem10 = 0,  
   ActualYTDNetPerDiem11 = 0,  
   ActualYTDNetPerDiem12 = 0,  
  
   CurrentYearBudgetNetPerDiem01 = 0,  
   CurrentYearBudgetNetPerDiem02 = 0,  
   CurrentYearBudgetNetPerDiem03 = 0,  
   CurrentYearBudgetNetPerDiem04 = 0,  
   CurrentYearBudgetNetPerDiem05 = 0,  
   CurrentYearBudgetNetPerDiem06 = 0,  
   CurrentYearBudgetNetPerDiem07 = 0,  
   CurrentYearBudgetNetPerDiem08 = 0,  
   CurrentYearBudgetNetPerDiem09 = 0,  
   CurrentYearBudgetNetPerDiem10 = 0,  
   CurrentYearBudgetNetPerDiem11 = 0,  
   CurrentYearBudgetNetPerDiem12 = 0  
  FROM fp.FactReimbursementChargesHistory fcrb  
   INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementChargesID = fcrb.ReimbursementChargesID  
 END  
END
GO


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

-- fp.procClearEncountersInvalidReimbursement
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI           Description
** 1    2023-05-12  MY      JAZZ-54661   Initial
** 2    2023-11-15  BK      JAZZ-62974   Update for Entity and ServiceLines that do not exist in fp.ChargeVolume
** 3    2024-01-11	AO      JAZZ-64530	 Data transfer for SLE is based on selected Model in Plan Config 
** 4    2024-02-16	MD      JAZZ-67663	 Make reimbursement encounters stop clearing out on SLE spread
** 5    2024-02-28	MD      JAZZ-68291	 Add targeting to update 
*************************************************************/
CREATE     PROCEDURE [fp].[procClearEncountersInvalidReimbursement]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	DECLARE @IsMedicalSurgicalUsed BIT,
			@IsMsdrgUsed BIT,
			@IsCptUsed BIT

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'PrimaryCPTID'

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters;
	IF OBJECT_ID('tempdb..#encounterTargeting') IS NOT NULL DROP TABLE #encounterTargeting;
	IF OBJECT_ID('tempdb..#invalidReimbursementIds') IS NOT NULL DROP TABLE #invalidReimbursementIds;
	
	CREATE TABLE #invalidReimbursementIds (ReimbursementEncounterID INT);

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT);

	IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED)
			INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
		UNION
		SELECT DISTINCT sle.EntityID, sle.ServiceLineID 
		FROM fp.ServiceLineEncounter sle LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID 
		WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL
		
	END ELSE 
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED)
		WHERE map.BudgetConfigID  = @BudgetConfigID	
	END
		
	SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		sle.PayorID, sle.PayorGroupID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID
	INTO #factReimbursementEncounters
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
	WHERE sle.BudgetConfigID = @BudgetConfigID

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#encounterTargeting', EntityID, ServiceLineID FROM #encounterTargeting
		SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID
		FROM #factReimbursementEncounters sle
	END ELSE
	BEGIN
		
		-- Set everything to 0 where it's in Reimbursement but not in Charges		
		UPDATE frc
		SET
			InitialBudgetEncounters01 = 0,
			InitialBudgetEncounters02 = 0,
			InitialBudgetEncounters03 = 0,
			InitialBudgetEncounters04 = 0,
			InitialBudgetEncounters05 = 0,
			InitialBudgetEncounters06 = 0,
			InitialBudgetEncounters07 = 0,
			InitialBudgetEncounters08 = 0,
			InitialBudgetEncounters09 = 0,
			InitialBudgetEncounters10 = 0,
			InitialBudgetEncounters11 = 0,
			InitialBudgetEncounters12 = 0,

			InitialBudgetNetPerEncounter01 = 0,
			InitialBudgetNetPerEncounter02 = 0,
			InitialBudgetNetPerEncounter03 = 0,
			InitialBudgetNetPerEncounter04 = 0,
			InitialBudgetNetPerEncounter05 = 0,
			InitialBudgetNetPerEncounter06 = 0,
			InitialBudgetNetPerEncounter07 = 0,
			InitialBudgetNetPerEncounter08 = 0,
			InitialBudgetNetPerEncounter09 = 0,
			InitialBudgetNetPerEncounter10 = 0,
			InitialBudgetNetPerEncounter11 = 0,
			InitialBudgetNetPerEncounter12 = 0,

			InitialProjectionEncounters01 = 0,
			InitialProjectionEncounters02 = 0,
			InitialProjectionEncounters03 = 0,
			InitialProjectionEncounters04 = 0,
			InitialProjectionEncounters05 = 0,
			InitialProjectionEncounters06 = 0,
			InitialProjectionEncounters07 = 0,
			InitialProjectionEncounters08 = 0,
			InitialProjectionEncounters09 = 0,
			InitialProjectionEncounters10 = 0,
			InitialProjectionEncounters11 = 0,
			InitialProjectionEncounters12 = 0,

			InitialProjectionNetPerEncounter01 = 0,
			InitialProjectionNetPerEncounter02 = 0,
			InitialProjectionNetPerEncounter03 = 0,
			InitialProjectionNetPerEncounter04 = 0,
			InitialProjectionNetPerEncounter05 = 0,
			InitialProjectionNetPerEncounter06 = 0,
			InitialProjectionNetPerEncounter07 = 0,
			InitialProjectionNetPerEncounter08 = 0,
			InitialProjectionNetPerEncounter09 = 0,
			InitialProjectionNetPerEncounter10 = 0,
			InitialProjectionNetPerEncounter11 = 0,
			InitialProjectionNetPerEncounter12 = 0	
		OUTPUT 
	        INSERTED.ReimbursementEncounterID
	    INTO
	        #invalidReimbursementIds (ReimbursementEncounterID) 
		FROM fp.FactReimbursementEncounter frc
			INNER JOIN #encounterTargeting et on frc.EntityID = et.EntityID and frc.ServiceLineID = et.ServiceLineID
			LEFT JOIN #factReimbursementEncounters tmp ON 
				frc.BudgetConfigID = tmp.BudgetConfigID
				AND frc.EntityGroupConfigID = tmp.EntityGroupConfigID
				AND frc.EntityID = tmp.EntityID
				AND frc.PatientClassID = tmp.PatientClassID
				AND frc.ServiceLineID = tmp.ServiceLineID
				AND frc.ServiceLineRollupID = tmp.ServiceLineRollupID
				AND frc.MedicalSurgicalID = tmp.MedicalSurgicalID
				AND frc.PayorID = tmp.PayorID
				AND frc.PayorGroupID = tmp.PayorGroupID
				AND frc.MSDRGID = tmp.MSDRGID
				AND frc.CPTID = tmp.CPTID
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = frc.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE frc.BudgetConfigID = @BudgetConfigID
			AND ((tmp.BudgetConfigID IS NULL)			
			OR (@IsReimbursementGLEnabled = 1 AND ((bc.DefaultReimbursementNetRevenueModelID <> 1 AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 1)) OR rnrm.NetRevenueModelID <> 1)))		
			--JAZZ-67663 - Commenting out for now because SLE spreads are incorrectly zeroing out reimbursement SLE data.
			--OR @IsReimbursementGLEnabled = 0 

		UPDATE fcrb
		SET
			LockType = 0,
			LockFlag = 0,

			AdjustedEncounters01 = 0,
			AdjustedEncounters02 = 0,
			AdjustedEncounters03 = 0,
			AdjustedEncounters04 = 0,
			AdjustedEncounters05 = 0,
			AdjustedEncounters06 = 0,
			AdjustedEncounters07 = 0,
			AdjustedEncounters08 = 0,
			AdjustedEncounters09 = 0,
			AdjustedEncounters10 = 0,
			AdjustedEncounters11 = 0,
			AdjustedEncounters12 = 0,

			AdjustedNetPerEncounterValue01 = 0,
			AdjustedNetPerEncounterValue02 = 0,
			AdjustedNetPerEncounterValue03 = 0,
			AdjustedNetPerEncounterValue04 = 0,
			AdjustedNetPerEncounterValue05 = 0,
			AdjustedNetPerEncounterValue06 = 0,
			AdjustedNetPerEncounterValue07 = 0,
			AdjustedNetPerEncounterValue08 = 0,
			AdjustedNetPerEncounterValue09 = 0,
			AdjustedNetPerEncounterValue10 = 0,
			AdjustedNetPerEncounterValue11 = 0,
			AdjustedNetPerEncounterValue12 = 0

		FROM fp.FactReimbursementEncounterBudget fcrb
			INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementEncounterID = fcrb.ReimbursementEncounterID

		UPDATE fcrb
		SET
			LockType = 0,
			LockFlag = 0,

			AdjustedEncounters01 = 0,
			AdjustedEncounters02 = 0,
			AdjustedEncounters03 = 0,
			AdjustedEncounters04 = 0,
			AdjustedEncounters05 = 0,
			AdjustedEncounters06 = 0,
			AdjustedEncounters07 = 0,
			AdjustedEncounters08 = 0,
			AdjustedEncounters09 = 0,
			AdjustedEncounters10 = 0,
			AdjustedEncounters11 = 0,
			AdjustedEncounters12 = 0,

			AdjustedNetPerEncounterValue01 = 0,
			AdjustedNetPerEncounterValue02 = 0,
			AdjustedNetPerEncounterValue03 = 0,
			AdjustedNetPerEncounterValue04 = 0,
			AdjustedNetPerEncounterValue05 = 0,
			AdjustedNetPerEncounterValue06 = 0,
			AdjustedNetPerEncounterValue07 = 0,
			AdjustedNetPerEncounterValue08 = 0,
			AdjustedNetPerEncounterValue09 = 0,
			AdjustedNetPerEncounterValue10 = 0,
			AdjustedNetPerEncounterValue11 = 0,
			AdjustedNetPerEncounterValue12 = 0

		FROM fp.FactReimbursementEncounterProjection fcrb
			INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementEncounterID = fcrb.ReimbursementEncounterID

		UPDATE fcrb
		SET
			PriorYearActualEncounters01 = 0,
			PriorYearActualEncounters02 = 0,
			PriorYearActualEncounters03 = 0,
			PriorYearActualEncounters04 = 0,
			PriorYearActualEncounters05 = 0,
			PriorYearActualEncounters06 = 0,
			PriorYearActualEncounters07 = 0,
			PriorYearActualEncounters08 = 0,
			PriorYearActualEncounters09 = 0,
			PriorYearActualEncounters10 = 0,
			PriorYearActualEncounters11 = 0,
			PriorYearActualEncounters12 = 0,

			ActualYTDEncounters01 = 0,
			ActualYTDEncounters02 = 0,
			ActualYTDEncounters03 = 0,
			ActualYTDEncounters04 = 0,
			ActualYTDEncounters05 = 0,
			ActualYTDEncounters06 = 0,
			ActualYTDEncounters07 = 0,
			ActualYTDEncounters08 = 0,
			ActualYTDEncounters09 = 0,
			ActualYTDEncounters10 = 0,
			ActualYTDEncounters11 = 0,
			ActualYTDEncounters12 = 0,

			CurrentYearBudgetEncounters01 = 0,
			CurrentYearBudgetEncounters02 = 0,
			CurrentYearBudgetEncounters03 = 0,
			CurrentYearBudgetEncounters04 = 0,
			CurrentYearBudgetEncounters05 = 0,
			CurrentYearBudgetEncounters06 = 0,
			CurrentYearBudgetEncounters07 = 0,
			CurrentYearBudgetEncounters08 = 0,
			CurrentYearBudgetEncounters09 = 0,
			CurrentYearBudgetEncounters10 = 0,
			CurrentYearBudgetEncounters11 = 0,
			CurrentYearBudgetEncounters12 = 0,

			PriorYearActualNetPerEncounterValue01 = 0,
			PriorYearActualNetPerEncounterValue02 = 0,
			PriorYearActualNetPerEncounterValue03 = 0,
			PriorYearActualNetPerEncounterValue04 = 0,
			PriorYearActualNetPerEncounterValue05 = 0,
			PriorYearActualNetPerEncounterValue06 = 0,
			PriorYearActualNetPerEncounterValue07 = 0,
			PriorYearActualNetPerEncounterValue08 = 0,
			PriorYearActualNetPerEncounterValue09 = 0,
			PriorYearActualNetPerEncounterValue10 = 0,
			PriorYearActualNetPerEncounterValue11 = 0,
			PriorYearActualNetPerEncounterValue12 = 0,

			ActualYTDNetPerEncounterValue01 = 0,
			ActualYTDNetPerEncounterValue02 = 0,
			ActualYTDNetPerEncounterValue03 = 0,
			ActualYTDNetPerEncounterValue04 = 0,
			ActualYTDNetPerEncounterValue05 = 0,
			ActualYTDNetPerEncounterValue06 = 0,
			ActualYTDNetPerEncounterValue07 = 0,
			ActualYTDNetPerEncounterValue08 = 0,
			ActualYTDNetPerEncounterValue09 = 0,
			ActualYTDNetPerEncounterValue10 = 0,
			ActualYTDNetPerEncounterValue11 = 0,
			ActualYTDNetPerEncounterValue12 = 0,

			CurrentYearNetPerEncounterBudget01 = 0,
			CurrentYearNetPerEncounterBudget02 = 0,
			CurrentYearNetPerEncounterBudget03 = 0,
			CurrentYearNetPerEncounterBudget04 = 0,
			CurrentYearNetPerEncounterBudget05 = 0,
			CurrentYearNetPerEncounterBudget06 = 0,
			CurrentYearNetPerEncounterBudget07 = 0,
			CurrentYearNetPerEncounterBudget08 = 0,
			CurrentYearNetPerEncounterBudget09 = 0,
			CurrentYearNetPerEncounterBudget10 = 0,
			CurrentYearNetPerEncounterBudget11 = 0,
			CurrentYearNetPerEncounterBudget12 = 0

		FROM fp.FactReimbursementEncounterHistory fcrb
			INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementEncounterID = fcrb.ReimbursementEncounterID

	END
END
GO


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

-- fp.procClearGeneralLedgerInvalidReimbursement
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2023-07-10	AO		JAZZ-57493	Initial
** 2	2023-08-07	MZ		JAZZ-55099	Fix targeting
** 3	2024-01-03	AO		JAZZ-65384  Data transfer for GL is based on selected Model in Plan Config 
** 4	2024-03-05	AO		JAZZ-68696	Fix targeting clear
*************************************************************/
CREATE     PROCEDURE [fp].[procClearGeneralLedgerInvalidReimbursement]
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#GeneralLedgerDepartments') IS NOT NULL DROP TABLE #GeneralLedgerDepartments;
	IF OBJECT_ID('tempdb..#ReimbursementGeneralLedger') IS NOT NULL DROP TABLE #ReimbursementGeneralLedger;
	IF OBJECT_ID('tempdb..#invalidReimbursementGeneralLedgerIds') IS NOT NULL DROP TABLE #invalidReimbursementGeneralLedgerIds;
	IF OBJECT_ID('tempdb..#ReimbursementTargeting') IS NOT NULL DROP TABLE #ReimbursementTargeting;

	DECLARE @Revenue INT = 1;
	DECLARE @Deduction INT = 4;

	CREATE TABLE #invalidReimbursementGeneralLedgerIds (ReimbursementGeneralLedgerID INT);

	CREATE TABLE #GeneralLedgerDepartments (DepartmentID INT);
	INSERT INTO #GeneralLedgerDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #ReimbursementTargeting (EntityID INT);
	
	CREATE TABLE #ReimbursementGeneralLedger (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT,
		PatientClassID INT,
		PayorGroupID INT
	)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	-- We need to target EntityID as ReimbursementGL doesn't have DepartmentID
	IF EXISTS(SELECT 1 FROM #GeneralLedgerDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ReimbursementTargeting (EntityID)
		SELECT DISTINCT EntityID
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)
			INNER JOIN #GeneralLedgerDepartments d ON gl.DepartmentID = d.DepartmentID
		WHERE gl.BudgetConfigID  = @BudgetConfigID	
	END ELSE 
	BEGIN
		INSERT INTO #ReimbursementTargeting (EntityID)
		SELECT DISTINCT EntityID
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)
		WHERE gl.BudgetConfigID  = @BudgetConfigID	
	END

		
	INSERT INTO #ReimbursementGeneralLedger (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, PayorGroupID)
	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.PatientClassID, a.OBPayorGroupID AS PayorGroupID
	FROM fp.GeneralLedger gl 
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
		INNER JOIN #ReimbursementTargeting targeting ON gl.EntityID = targeting.EntityID
	WHERE gl.BudgetConfigID = @BudgetConfigID
		AND (gl.APEModelSectionID = @Revenue OR (gl.APEModelSectionID = @Deduction AND a.OBModelSectionName = 'Deductions - Reimbursement'))

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#GeneralLedgerDepartments', DepartmentID FROM #GeneralLedgerDepartments
		SELECT '#ReimbursementTargeting', EntityID FROM #ReimbursementTargeting
		SELECT '#ReimbursementGeneralLedger', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [PayorGroupID]
		FROM #ReimbursementGeneralLedger
	END ELSE
	BEGIN


	UPDATE rgl
	SET
		InitialBudget01 = 0,
		InitialBudget02 = 0,
		InitialBudget03 = 0,
		InitialBudget04 = 0,
		InitialBudget05 = 0,
		InitialBudget06 = 0,
		InitialBudget07 = 0,
		InitialBudget08 = 0,
		InitialBudget09 = 0,
		InitialBudget10 = 0,
		InitialBudget11 = 0,
		InitialBudget12 = 0,

		InitialProjection01 = 0,
		InitialProjection02 = 0,
		InitialProjection03 = 0,
		InitialProjection04 = 0,
		InitialProjection05 = 0,
		InitialProjection06 = 0,
		InitialProjection07 = 0,
		InitialProjection08 = 0,
		InitialProjection09 = 0,
		InitialProjection10 = 0,
		InitialProjection11 = 0,
		InitialProjection12 = 0,

		InitialBudgetNetAsPercentOfCharge01 = 0,
		InitialBudgetNetAsPercentOfCharge02 = 0,
		InitialBudgetNetAsPercentOfCharge03 = 0,
		InitialBudgetNetAsPercentOfCharge04 = 0,
		InitialBudgetNetAsPercentOfCharge05 = 0,
		InitialBudgetNetAsPercentOfCharge06 = 0,
		InitialBudgetNetAsPercentOfCharge07 = 0,
		InitialBudgetNetAsPercentOfCharge08 = 0,
		InitialBudgetNetAsPercentOfCharge09 = 0,
		InitialBudgetNetAsPercentOfCharge10 = 0,
		InitialBudgetNetAsPercentOfCharge11 = 0,
		InitialBudgetNetAsPercentOfCharge12 = 0,

		InitialProjectionNetAsPercentOfCharge01 = 0,
		InitialProjectionNetAsPercentOfCharge02 = 0,
		InitialProjectionNetAsPercentOfCharge03 = 0,
		InitialProjectionNetAsPercentOfCharge04 = 0,
		InitialProjectionNetAsPercentOfCharge05 = 0,
		InitialProjectionNetAsPercentOfCharge06 = 0,
		InitialProjectionNetAsPercentOfCharge07 = 0,
		InitialProjectionNetAsPercentOfCharge08 = 0,
		InitialProjectionNetAsPercentOfCharge09 = 0,
		InitialProjectionNetAsPercentOfCharge10 = 0,
		InitialProjectionNetAsPercentOfCharge11 = 0,
		InitialProjectionNetAsPercentOfCharge12 = 0,

		TargetAdjusted01 = 0,
		TargetAdjusted02 = 0,
		TargetAdjusted03 = 0,
		TargetAdjusted04 = 0,
		TargetAdjusted05 = 0,
		TargetAdjusted06 = 0,
		TargetAdjusted07 = 0,
		TargetAdjusted08 = 0,
		TargetAdjusted09 = 0,
		TargetAdjusted10 = 0,
		TargetAdjusted11 = 0,
		TargetAdjusted12 = 0,

		TargetAdjustedNetAsPercentOfCharge01 = 0,
		TargetAdjustedNetAsPercentOfCharge02 = 0,
		TargetAdjustedNetAsPercentOfCharge03 = 0,
		TargetAdjustedNetAsPercentOfCharge04 = 0,
		TargetAdjustedNetAsPercentOfCharge05 = 0,
		TargetAdjustedNetAsPercentOfCharge06 = 0,
		TargetAdjustedNetAsPercentOfCharge07 = 0,
		TargetAdjustedNetAsPercentOfCharge08 = 0,
		TargetAdjustedNetAsPercentOfCharge09 = 0,
		TargetAdjustedNetAsPercentOfCharge10 = 0,
		TargetAdjustedNetAsPercentOfCharge11 = 0,
		TargetAdjustedNetAsPercentOfCharge12 = 0,

		BudgetAdjusted01 = 0,
		BudgetAdjusted02 = 0,
		BudgetAdjusted03 = 0,
		BudgetAdjusted04 = 0,
		BudgetAdjusted05 = 0,
		BudgetAdjusted06 = 0,
		BudgetAdjusted07 = 0,
		BudgetAdjusted08 = 0,
		BudgetAdjusted09 = 0,
		BudgetAdjusted10 = 0,
		BudgetAdjusted11 = 0,
		BudgetAdjusted12 = 0,

		BudgetAdjustedNetAsPercentOfCharge01 = 0,
		BudgetAdjustedNetAsPercentOfCharge02 = 0,
		BudgetAdjustedNetAsPercentOfCharge03 = 0,
		BudgetAdjustedNetAsPercentOfCharge04 = 0,
		BudgetAdjustedNetAsPercentOfCharge05 = 0,
		BudgetAdjustedNetAsPercentOfCharge06 = 0,
		BudgetAdjustedNetAsPercentOfCharge07 = 0,
		BudgetAdjustedNetAsPercentOfCharge08 = 0,
		BudgetAdjustedNetAsPercentOfCharge09 = 0,
		BudgetAdjustedNetAsPercentOfCharge10 = 0,
		BudgetAdjustedNetAsPercentOfCharge11 = 0,
		BudgetAdjustedNetAsPercentOfCharge12 = 0,

		ProjectionAdjusted01 = 0,
		ProjectionAdjusted02 = 0,
		ProjectionAdjusted03 = 0,
		ProjectionAdjusted04 = 0,
		ProjectionAdjusted05 = 0,
		ProjectionAdjusted06 = 0,
		ProjectionAdjusted07 = 0,
		ProjectionAdjusted08 = 0,
		ProjectionAdjusted09 = 0,
		ProjectionAdjusted10 = 0,
		ProjectionAdjusted11 = 0,
		ProjectionAdjusted12 = 0,

		ProjectionAdjustedNetAsPercentOfCharge01 = 0,
		ProjectionAdjustedNetAsPercentOfCharge02 = 0,
		ProjectionAdjustedNetAsPercentOfCharge03 = 0,
		ProjectionAdjustedNetAsPercentOfCharge04 = 0,
		ProjectionAdjustedNetAsPercentOfCharge05 = 0,
		ProjectionAdjustedNetAsPercentOfCharge06 = 0,
		ProjectionAdjustedNetAsPercentOfCharge07 = 0,
		ProjectionAdjustedNetAsPercentOfCharge08 = 0,
		ProjectionAdjustedNetAsPercentOfCharge09 = 0,
		ProjectionAdjustedNetAsPercentOfCharge10 = 0,
		ProjectionAdjustedNetAsPercentOfCharge11 = 0,
		ProjectionAdjustedNetAsPercentOfCharge12 = 0,

		BudgetLockType = 0,
		BudgetLockFlag = 0,
		
		TargetLockType = 0,
		TargetLockFlag = 0,
		
		ProjectionLockType = 0, 
		ProjectionLockFlag = 0
	OUTPUT 
		INSERTED.ReimbursementGeneralLedgerID
	INTO
		#invalidReimbursementGeneralLedgerIds (ReimbursementGeneralLedgerID) 
	FROM fp.ReimbursementGeneralLedger rgl
		LEFT JOIN #ReimbursementGeneralLedger tmp ON 
			rgl.BudgetConfigID = tmp.BudgetConfigID
			AND rgl.EntityGroupConfigID = tmp.EntityGroupConfigID
			AND rgl.EntityID = tmp.EntityID
			AND rgl.PatientClassID = tmp.PatientClassID
			AND rgl.PayorGroupID = tmp.PayorGroupID
		INNER JOIN #ReimbursementTargeting targeting ON
			targeting.EntityID = rgl.EntityID
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
		LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = targeting.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE rgl.BudgetConfigID = @BudgetConfigID
		AND ((tmp.BudgetConfigID IS NULL AND targeting.EntityID IS NOT NULL)
		OR ((bc.DefaultReimbursementNetRevenueModelID <> 2 AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 2)) 
				OR rnrm.NetRevenueModelID <> 2))

	UPDATE rglh
	SET
		PriorYearActualValue01 = 0,
		PriorYearActualValue02 = 0,
		PriorYearActualValue03 = 0,
		PriorYearActualValue04 = 0,
		PriorYearActualValue05 = 0,
		PriorYearActualValue06 = 0,
		PriorYearActualValue07 = 0,
		PriorYearActualValue08 = 0,
		PriorYearActualValue09 = 0,
		PriorYearActualValue10 = 0,
		PriorYearActualValue11 = 0,
		PriorYearActualValue12 = 0,
		PriorYearActualValueNetAsPercentOfCharge01 = 0,
		PriorYearActualValueNetAsPercentOfCharge02 = 0,
		PriorYearActualValueNetAsPercentOfCharge03 = 0,
		PriorYearActualValueNetAsPercentOfCharge04 = 0,
		PriorYearActualValueNetAsPercentOfCharge05 = 0,
		PriorYearActualValueNetAsPercentOfCharge06 = 0,
		PriorYearActualValueNetAsPercentOfCharge07 = 0,
		PriorYearActualValueNetAsPercentOfCharge08 = 0,
		PriorYearActualValueNetAsPercentOfCharge09 = 0,
		PriorYearActualValueNetAsPercentOfCharge10 = 0,
		PriorYearActualValueNetAsPercentOfCharge11 = 0,
		PriorYearActualValueNetAsPercentOfCharge12 = 0
	FROM fp.ReimbursementGeneralLedgerHistory rglh
		INNER JOIN #invalidReimbursementGeneralLedgerIds inv ON inv.ReimbursementGeneralLedgerID = rglh.ReimbursementGeneralLedgerID
	END
END
GO


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

-- fp.procClearReportCache
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2020-03-11  MY          JAZZ-16618      Initial
** 2    2020-08-31  MY          JAZZ-42472      Added Regular Reporting Sources
** 3    2022-10-24  MD          JAZZ-32897      Added reimbursement reporting table
** 4    2024-04-11	DM			  JAZZ-70189      Added historical table for GL and delete GL data by condition
** 5    2024-07-04	DM          JAZZ-70314      Added historical table for Staffing and delete Staffing data by condition
** 6    2024-07-16	YR          JAZZ-70315      Added historical table for Statistics and delete Statistics data by condition
** 7    2024-12-05	NH          JAZZ-78230      Added Adjustment History reporting table
*********************************************************************/
CREATE       PROCEDURE [fp].[procClearReportCache](
	@IsActiveConfigChanged BIT
)
WITH RECOMPILE
AS
BEGIN
	-- when reporting plan is changed we only handle GL, Staffing and Statistic data for now
	DELETE frgl
	FROM fp.FactReportGeneralLedger frgl
	INNER JOIN fp.BudgetConfig bc
	  ON bc.BudgetConfigID = frgl.BudgetConfigID
	WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1

	DELETE frglh
	FROM fp.FactReportGeneralLedgerHistory frglh
	INNER JOIN fp.BudgetConfig bc
	  ON bc.BudgetConfigID = frglh.BudgetConfigID
	WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1
	
	DELETE frs
	FROM fp.FactReportStaffing frs
	INNER JOIN fp.BudgetConfig bc
	  ON bc.BudgetConfigID = frs.BudgetConfigID
	WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1

	DELETE frsh
	FROM fp.FactReportStaffingHistory frsh
	INNER JOIN fp.BudgetConfig bc
	  ON bc.BudgetConfigID = frsh.BudgetConfigID
	WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1

	DELETE frst
	FROM fp.FactReportStatistics frst
	INNER JOIN fp.BudgetConfig bc
	  ON bc.BudgetConfigID = frst.BudgetConfigID
	WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1

	DELETE frsth
	FROM fp.FactReportStatisticsHistory frsth
	INNER JOIN fp.BudgetConfig bc
	  ON bc.BudgetConfigID = frsth.BudgetConfigID
	WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1
	
	-- This proc is used to clear out the report tables in the event of the active or reporting configuration changing. 
	-- This is required for nightly run reports so that they can completely refresh data.
	IF(@IsActiveConfigChanged = 1)
	BEGIN
		-- These are done nightly, but also don't do deletes so we need to wipe them on active configuration change.
		TRUNCATE TABLE fp.FactReportChargeVolume
		TRUNCATE TABLE fp.FactReportEncounter
		TRUNCATE TABLE fp.FactReportEncounterHistory
		TRUNCATE TABLE fp.FactReportChargeToStatisticsCrosswalk
		TRUNCATE TABLE fp.FactReportChargeToStatisticsCrosswalkHistory
		TRUNCATE TABLE fp.FactReportReimbursement
		TRUNCATE TABLE fp.FactReportAdjustmentHistory
	END
END;
GO


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

-- fp.procClearSpreadChangeHistory
/************************************************************** 
** Change History  
************************************************************** 
** CID  Date        Author  WI			Description 
** 1	2023-12-08  MY      JAZZ-63890	Initial 
** 2	2024-01-02  MY      JAZZ-64770	Upgrade to Restructure 
*************************************************************/
CREATE   PROCEDURE [fp].[procClearSpreadChangeHistory] (
	@Direction VARCHAR(250),
	@BudgetConfigID INT,
	@AdditionalFilter VARCHAR(max) = '1 = 1',
	@iterationRowCount INT = 100000,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@isDebug BIT = 0
)
AS
BEGIN
	DECLARE @isFilterPresent BIT = CASE WHEN (SELECT COUNT(*) FROM @SourceDimensionality) >= 1 THEN 1 ELSE 0 END;
	DECLARE @sqlCommand NVARCHAR(MAX)
	DECLARE @tableType VARCHAR(10) = CASE WHEN (@Direction IN ('ServiceLineEncounter', 'ChargeVolume', 'GeneralLedger', 'ReimbursementGeneralLedger', 'Staffing')) THEN '' ELSE 'Fact' END;

	DECLARE @FilterLogic NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN '
		CREATE TABLE #FilteringTable (
			DepartmentID INT,
			INDEX ix_1 NONCLUSTERED (DepartmentID)
		)
		INSERT INTO #FilteringTable (DepartmentID)
		SELECT DepartmentID
		FROM @SourceDimensionality' ELSE '' END;

	DECLARE @FilterJoin NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN 'INNER JOIN #FilteringTable ft on ft.DepartmentID = res.DepartmentID' ELSE '' END;

	IF @Direction = 'ServiceLineEncounter' AND @isFilterPresent = 1 BEGIN
		SET @FilterLogic = '
		CREATE TABLE #FilteringTable (
			EntityID INT, ServiceLineID INT, ProviderID INT,
			INDEX ix_1 NONCLUSTERED (EntityID)
		)
		INSERT INTO #FilteringTable (EntityID, ServiceLineID, ProviderID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID, map.ProviderID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map
			INNER JOIN @SourceDimensionality ft on map.DepartmentID = ft.DepartmentID
		WHERE map.BudgetConfigID =  ' + CAST(@BudgetConfigID AS VARCHAR) + '; '

		SET @FilterJoin = 'INNER JOIN #FilteringTable ft on ft.EntityID = res.EntityID AND ft.ServiceLineID = res.ServiceLineID AND ft.ProviderID = res.ProviderID'
	END

	IF (@isFilterPresent = 0)
	BEGIN
		SET @sqlCommand = '
			DECLARE @Rowcount INT = 1
			WHILE @Rowcount > 0
			BEGIN
				DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch 
				FROM [fp].[' + @Direction + 'SpreadsChangeHistory] ch 
				WHERE BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + CASE 
				WHEN @AdditionalFilter = '1=1'
					THEN ''
				ELSE ' AND ' + @AdditionalFilter
				END + '
			  SET @Rowcount = @@ROWCOUNT
			END
		'
	END ELSE BEGIN
		SET @sqlCommand = @FilterLogic + 
		'
			SELECT Ch.' + @Direction + 'ID 
			INTO #DeleteIDs 
			FROM [fp].[' + @tableType + @Direction + '] res
				' + @FilterJoin + '
				INNER JOIN [fp].[' + @Direction + 'SpreadsChangeHistory] ch ON ch.' + @Direction + 'ID = res.' + @Direction + 'ID
			WHERE res.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10))  + CASE 
				WHEN @AdditionalFilter = '1=1'
					THEN ''
				ELSE ' AND ' + @AdditionalFilter
				END + '
			CREATE CLUSTERED INDEX idx_DeleteIDs on #DeleteIDs (' + @Direction + 'ID)
			DECLARE @Rowcount INT = 1
			WHILE @Rowcount > 0
			BEGIN
				DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch 
				FROM [fp].[' + @Direction + 'SpreadsChangeHistory] ch 
					INNER JOIN #DeleteIDs D ON ch.' + @Direction + 'ID = D.' + @Direction + 'ID
				WHERE ch.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + '
			  SET @Rowcount = @@ROWCOUNT
			END
		'
	END

	IF @isDebug = 1
		PRINT @sqlCommand
	ELSE
		EXECUTE sp_executesql @sqlCommand
			,N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY'
			,@SourceDimensionality = @SourceDimensionality
END
GO


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

-- fp.procCopyBenefitsToGeneralLedger
CREATE   PROC [fp].[procCopyBenefitsToGeneralLedger]
	@BudgetConfigID INT,
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 WITH RECOMPILE
 AS
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI				Description
	 ** 1 	 2019-03-26  IP  	 B-22466		Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2 	 2020-08-04	 NN      JAZZ-133		Remove NULL checks to JOINS and drop temp table
	 ** 3 	 2023-08-10	 MY      JAZZ-58216		Update to new structure
	 ** 4 	 2023-11-21	 MD      JAZZ-64023		Add in month 12 check for target and budget
	 ** 5 	 2024-01-11	 MY      JAZZ-65544		Budget values for Benefits Accounts are overwritten
	 *************************************************************/
	
	exec [dbo].[procSysDropTempTable] '#FilterByDepartment'
	exec [dbo].[procSysDropTempTable] '#BudgetPhase'
	 
	CREATE TABLE #FilterByDepartment (DepartmentID INT, BudgetPhaseID INT)
	INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID)
	SELECT DepartmentID, BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- Add both BudgetPhaseIDs to #BudgetPhase  
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID IS NOT NULL)
	BEGIN
		CREATE TABLE #BudgetPhase (BudgetPhaseID tinyint)
		INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3
	END
	
	-- If the FilterByDepartment is empty, add all departmentIds to avoid duplication of entire proc		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID)
		SELECT DISTINCT DepartmentID, BudgetPhaseID
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
			OUTER APPLY #BudgetPhase bp
		WHERE BudgetConfigID = @BudgetConfigID	
		
		DELETE #FilterByDepartment WHERE DepartmentID IS NULL	
	END	
	
	--If BudgetPhaseID is null, but Dept is present update the table
	ELSE IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID IS NULL)
	BEGIN		
		INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID)
		SELECT DepartmentID, bp.BudgetPhaseID 
		FROM #FilterByDepartment dd WITH (READUNCOMMITTED)
			OUTER APPLY #BudgetPhase bp	

		DELETE #FilterByDepartment WHERE BudgetPhaseID IS NULL
	END 
	
	DECLARE @CrosswalkTarget BIT = CASE WHEN EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID = 2) THEN 1 ELSE 0 END
	DECLARE @CrosswalkBudgetOrProjection BIT = CASE WHEN EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID = 3) THEN 1 ELSE 0 END	
		
	IF (@CrosswalkTarget = 1)
	BEGIN

		UPDATE gl
		SET
			gl.TargetAdjusted01 = benBudg.AdjustedValue01,
			gl.TargetAdjusted02 = benBudg.AdjustedValue02,
			gl.TargetAdjusted03 = benBudg.AdjustedValue03,
			gl.TargetAdjusted04 = benBudg.AdjustedValue04,
			gl.TargetAdjusted05 = benBudg.AdjustedValue05,
			gl.TargetAdjusted06 = benBudg.AdjustedValue06,
			gl.TargetAdjusted07 = benBudg.AdjustedValue07,
			gl.TargetAdjusted08 = benBudg.AdjustedValue08,
			gl.TargetAdjusted09 = benBudg.AdjustedValue09,
			gl.TargetAdjusted10 = benBudg.AdjustedValue10,
			gl.TargetAdjusted11 = benBudg.AdjustedValue11,
			gl.TargetAdjusted12 = benBudg.AdjustedValue12,
			gl.TargetLockFlag = 1,
			gl.TargetLockType = 2
		FROM [fp].[GeneralLedger] gl with (readuncommitted)
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID
			INNER JOIN [fp].[FactBenefits] ben with (readuncommitted)
				ON gl.BudgetConfigID = ben.BudgetConfigID
				AND gl.EntityGroupConfigID = ben.EntityGroupConfigID
				AND gl.DepartmentID = ben.DepartmentID
				AND gl.AccountID = ben.AccountID
				AND ben.UnitTypeID = 34
				AND gl.FinancialReportingID = ben.FinancialReportingID
				AND gl.EntityID = ben.EntityID
			INNER JOIN [fp].[FactBenefitsBudget] benBudg ON ben.BenefitsID = benBudg.BenefitsID	AND benBudg.BudgetPhaseID = 2
		WHERE 1 = 1
			AND ft.BudgetPhaseID = 2
			AND gl.APEModelSectionID = 5
			AND gl.VariabilityID = 2
			AND gl.BudgetConfigID = @BudgetConfigID
			AND (gl.TargetAdjusted01 != benBudg.AdjustedValue01 OR
				 gl.TargetAdjusted02 != benBudg.AdjustedValue02 OR
				 gl.TargetAdjusted03 != benBudg.AdjustedValue03 OR
				 gl.TargetAdjusted04 != benBudg.AdjustedValue04 OR
				 gl.TargetAdjusted05 != benBudg.AdjustedValue05 OR
				 gl.TargetAdjusted06 != benBudg.AdjustedValue06 OR
				 gl.TargetAdjusted07 != benBudg.AdjustedValue07 OR
				 gl.TargetAdjusted08 != benBudg.AdjustedValue08 OR
				 gl.TargetAdjusted09 != benBudg.AdjustedValue09 OR
				 gl.TargetAdjusted10 != benBudg.AdjustedValue10 OR
				 gl.TargetAdjusted11 != benBudg.AdjustedValue11 OR
				 gl.TargetAdjusted12 != benBudg.AdjustedValue12 OR
				 gl.TargetLockFlag != 1 OR
				 gl.TargetLockType != 2)		 	

	END

	IF (@CrosswalkBudgetOrProjection = 1)
	BEGIN
		
		UPDATE gl
		SET
			gl.BudgetAdjusted01 = benBudg.AdjustedValue01,
			gl.BudgetAdjusted02 = benBudg.AdjustedValue02,
			gl.BudgetAdjusted03 = benBudg.AdjustedValue03,
			gl.BudgetAdjusted04 = benBudg.AdjustedValue04,
			gl.BudgetAdjusted05 = benBudg.AdjustedValue05,
			gl.BudgetAdjusted06 = benBudg.AdjustedValue06,
			gl.BudgetAdjusted07 = benBudg.AdjustedValue07,
			gl.BudgetAdjusted08 = benBudg.AdjustedValue08,
			gl.BudgetAdjusted09 = benBudg.AdjustedValue09,
			gl.BudgetAdjusted10 = benBudg.AdjustedValue10,
			gl.BudgetAdjusted11 = benBudg.AdjustedValue11,
			gl.BudgetAdjusted12 = benBudg.AdjustedValue12,
			gl.BudgetLockFlag = 1,
			gl.BudgetLockType = 2,
			gl.ProjectionAdjusted01 = CASE WHEN @MonthsLoaded < 1  THEN benProj.AdjustedValue01 ELSE gl.ProjectionAdjusted01 END,
			gl.ProjectionAdjusted02 = CASE WHEN @MonthsLoaded < 2  THEN benProj.AdjustedValue02 ELSE gl.ProjectionAdjusted02 END,
			gl.ProjectionAdjusted03 = CASE WHEN @MonthsLoaded < 3  THEN benProj.AdjustedValue03 ELSE gl.ProjectionAdjusted03 END,
			gl.ProjectionAdjusted04 = CASE WHEN @MonthsLoaded < 4  THEN benProj.AdjustedValue04 ELSE gl.ProjectionAdjusted04 END,
			gl.ProjectionAdjusted05 = CASE WHEN @MonthsLoaded < 5  THEN benProj.AdjustedValue05 ELSE gl.ProjectionAdjusted05 END,
			gl.ProjectionAdjusted06 = CASE WHEN @MonthsLoaded < 6  THEN benProj.AdjustedValue06 ELSE gl.ProjectionAdjusted06 END,
			gl.ProjectionAdjusted07 = CASE WHEN @MonthsLoaded < 7  THEN benProj.AdjustedValue07 ELSE gl.ProjectionAdjusted07 END,
			gl.ProjectionAdjusted08 = CASE WHEN @MonthsLoaded < 8  THEN benProj.AdjustedValue08 ELSE gl.ProjectionAdjusted08 END,
			gl.ProjectionAdjusted09 = CASE WHEN @MonthsLoaded < 9  THEN benProj.AdjustedValue09 ELSE gl.ProjectionAdjusted09 END,
			gl.ProjectionAdjusted10 = CASE WHEN @MonthsLoaded < 10 THEN benProj.AdjustedValue10 ELSE gl.ProjectionAdjusted10 END,
			gl.ProjectionAdjusted11 = CASE WHEN @MonthsLoaded < 11 THEN benProj.AdjustedValue11 ELSE gl.ProjectionAdjusted11 END,
			gl.ProjectionAdjusted12 = CASE WHEN @MonthsLoaded < 12 THEN benProj.AdjustedValue12 ELSE gl.ProjectionAdjusted12 END,
			gl.ProjectionLockFlag = 1,
			gl.ProjectionLockType = 2
		FROM [fp].[GeneralLedger] gl with (readuncommitted)
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID
			INNER JOIN [fp].[FactBenefits] ben with (readuncommitted)
				ON gl.BudgetConfigID = ben.BudgetConfigID
				AND gl.EntityGroupConfigID = ben.EntityGroupConfigID
				AND gl.DepartmentID = ben.DepartmentID
				AND gl.AccountID = ben.AccountID
				AND ben.UnitTypeID = 34
				AND gl.FinancialReportingID = ben.FinancialReportingID
				AND gl.EntityID = ben.EntityID
			INNER JOIN [fp].[FactBenefitsBudget] benBudg ON ben.BenefitsID = benBudg.BenefitsID	AND benBudg.BudgetPhaseID = 3
			INNER JOIN [fp].[FactBenefitsProjection] benProj ON ben.BenefitsID = benProj.BenefitsID	AND benProj.BudgetPhaseID = 3
		WHERE 1 = 1
			AND ft.BudgetPhaseID = 3
			AND gl.APEModelSectionID = 5
			AND gl.VariabilityID = 2
			AND gl.BudgetConfigID = @BudgetConfigID
			AND (
				 
				 gl.BudgetAdjusted01 != benBudg.AdjustedValue01 OR
				 gl.BudgetAdjusted02 != benBudg.AdjustedValue02 OR
				 gl.BudgetAdjusted03 != benBudg.AdjustedValue03 OR
				 gl.BudgetAdjusted04 != benBudg.AdjustedValue04 OR
				 gl.BudgetAdjusted05 != benBudg.AdjustedValue05 OR
				 gl.BudgetAdjusted06 != benBudg.AdjustedValue06 OR
				 gl.BudgetAdjusted07 != benBudg.AdjustedValue07 OR
				 gl.BudgetAdjusted08 != benBudg.AdjustedValue08 OR
				 gl.BudgetAdjusted09 != benBudg.AdjustedValue09 OR
				 gl.BudgetAdjusted10 != benBudg.AdjustedValue10 OR
				 gl.BudgetAdjusted11 != benBudg.AdjustedValue11 OR
				 gl.BudgetAdjusted12 != benBudg.AdjustedValue12 OR
				 gl.BudgetLockFlag != 1 OR
				 gl.BudgetLockType != 2 OR
				 gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded < 1  THEN benProj.AdjustedValue01 ELSE gl.ProjectionAdjusted01 END OR
				 gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded < 2  THEN benProj.AdjustedValue02 ELSE gl.ProjectionAdjusted02 END OR
				 gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded < 3  THEN benProj.AdjustedValue03 ELSE gl.ProjectionAdjusted03 END OR
				 gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded < 4  THEN benProj.AdjustedValue04 ELSE gl.ProjectionAdjusted04 END OR
				 gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded < 5  THEN benProj.AdjustedValue05 ELSE gl.ProjectionAdjusted05 END OR
				 gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded < 6  THEN benProj.AdjustedValue06 ELSE gl.ProjectionAdjusted06 END OR
				 gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded < 7  THEN benProj.AdjustedValue07 ELSE gl.ProjectionAdjusted07 END OR
				 gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded < 8  THEN benProj.AdjustedValue08 ELSE gl.ProjectionAdjusted08 END OR
				 gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded < 9  THEN benProj.AdjustedValue09 ELSE gl.ProjectionAdjusted09 END OR
				 gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded < 10 THEN benProj.AdjustedValue10 ELSE gl.ProjectionAdjusted10 END OR
				 gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded < 11 THEN benProj.AdjustedValue11 ELSE gl.ProjectionAdjusted11 END OR
				 gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded < 12 THEN benProj.AdjustedValue12 ELSE gl.ProjectionAdjusted12 END OR
				 gl.ProjectionLockFlag != 1 OR
				 gl.ProjectionLockType != 2
		)

	END

	-- Lock any fixed cells that need to be locked
	UPDATE gl
	SET
		TargetLockFlag = 1,
		TargetLockType = 2,
		BudgetLockFlag = 1,
		BudgetLockType = 2,
		ProjectionLockFlag = 1,
		ProjectionLockType = 2
	FROM [fp].[GeneralLedger] gl
		INNER JOIN (SELECT DISTINCT DepartmentID FROM #FilterByDepartment) ft on ft.DepartmentID = gl.DepartmentID 
	WHERE gl.BudgetConfigID = @BudgetConfigID
		AND gl.APEModelSectionID = 5
		AND gl.VariabilityID = 1
		AND (TargetLockFlag = 0 OR BudgetLockFlag = 0 OR ProjectionLockFlag = 0)
GO


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

-- fp.procCopyBenefitsToGeneralLedger_Initial
CREATE   PROC [fp].[procCopyBenefitsToGeneralLedger_Initial]
	@BudgetConfigID INT,
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 WITH RECOMPILE
 AS

	/*************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1    2023-08-22  MY      JAZZ-59505	Initial Creation
	*************************************************************/
	
	exec [dbo].[procSysDropTempTable] '#FilterByDepartment'
	exec [dbo].[procSysDropTempTable] '#BudgetPhase'
	 
	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the FilterByDepartment is empty, add all departmentIds to avoid duplication of entire proc		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID = @BudgetConfigID	
		
		DELETE #FilterByDepartment WHERE DepartmentID IS NULL	
	END	
	
	-- Update the baseline values
	UPDATE gl
	SET
		gl.InitialBudget01 = ben.InitialBudget01,
		gl.InitialBudget02 = ben.InitialBudget02,
		gl.InitialBudget03 = ben.InitialBudget03,
		gl.InitialBudget04 = ben.InitialBudget04,
		gl.InitialBudget05 = ben.InitialBudget05,
		gl.InitialBudget06 = ben.InitialBudget06,
		gl.InitialBudget07 = ben.InitialBudget07,
		gl.InitialBudget08 = ben.InitialBudget08,
		gl.InitialBudget09 = ben.InitialBudget09,
		gl.InitialBudget10 = ben.InitialBudget10,
		gl.InitialBudget11 = ben.InitialBudget11,
		gl.InitialBudget12 = ben.InitialBudget12,
		
		gl.InitialProjection01 = CASE WHEN @MonthsLoaded < 1 THEN ben.InitialProjection01 ELSE gl.InitialProjection01 END,
		gl.InitialProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ben.InitialProjection02 ELSE gl.InitialProjection02 END,
		gl.InitialProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ben.InitialProjection03 ELSE gl.InitialProjection03 END,
		gl.InitialProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ben.InitialProjection04 ELSE gl.InitialProjection04 END,
		gl.InitialProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ben.InitialProjection05 ELSE gl.InitialProjection05 END,
		gl.InitialProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ben.InitialProjection06 ELSE gl.InitialProjection06 END,
		gl.InitialProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ben.InitialProjection07 ELSE gl.InitialProjection07 END,
		gl.InitialProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ben.InitialProjection08 ELSE gl.InitialProjection08 END,
		gl.InitialProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ben.InitialProjection09 ELSE gl.InitialProjection09 END,
		gl.InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ben.InitialProjection10 ELSE gl.InitialProjection10 END,
		gl.InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ben.InitialProjection11 ELSE gl.InitialProjection11 END,
		gl.InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN ben.InitialProjection12 ELSE gl.InitialProjection12 END
	FROM [fp].[GeneralLedger] gl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID
		INNER JOIN [fp].[FactBenefits] ben with (readuncommitted)
			ON gl.BudgetConfigID = ben.BudgetConfigID
			AND gl.EntityGroupConfigID = ben.EntityGroupConfigID
			AND gl.DepartmentID = ben.DepartmentID
			AND gl.AccountID = ben.AccountID
			AND ben.UnitTypeID = 34
			AND gl.FinancialReportingID = ben.FinancialReportingID
			AND gl.EntityID = ben.EntityID
	WHERE 1 = 1
		AND gl.VariabilityID = 2
		AND gl.BudgetConfigID = @BudgetConfigID
		AND (gl.InitialBudget01 != ben.InitialBudget01 OR
			 gl.InitialBudget02 != ben.InitialBudget02 OR
			 gl.InitialBudget03 != ben.InitialBudget03 OR
			 gl.InitialBudget04 != ben.InitialBudget04 OR
			 gl.InitialBudget05 != ben.InitialBudget05 OR
			 gl.InitialBudget06 != ben.InitialBudget06 OR
			 gl.InitialBudget07 != ben.InitialBudget07 OR
			 gl.InitialBudget08 != ben.InitialBudget08 OR
			 gl.InitialBudget09 != ben.InitialBudget09 OR
			 gl.InitialBudget10 != ben.InitialBudget10 OR
			 gl.InitialBudget11 != ben.InitialBudget11 OR
			 gl.InitialBudget12 != ben.InitialBudget12 OR
			 gl.InitialProjection01 != CASE WHEN @MonthsLoaded < 1 THEN ben.InitialProjection01 ELSE gl.InitialProjection01 END OR
			 gl.InitialProjection02 != CASE WHEN @MonthsLoaded < 2 THEN ben.InitialProjection02 ELSE gl.InitialProjection02 END OR
			 gl.InitialProjection03 != CASE WHEN @MonthsLoaded < 3 THEN ben.InitialProjection03 ELSE gl.InitialProjection03 END OR
			 gl.InitialProjection04 != CASE WHEN @MonthsLoaded < 4 THEN ben.InitialProjection04 ELSE gl.InitialProjection04 END OR
			 gl.InitialProjection05 != CASE WHEN @MonthsLoaded < 5 THEN ben.InitialProjection05 ELSE gl.InitialProjection05 END OR
			 gl.InitialProjection06 != CASE WHEN @MonthsLoaded < 6 THEN ben.InitialProjection06 ELSE gl.InitialProjection06 END OR
			 gl.InitialProjection07 != CASE WHEN @MonthsLoaded < 7 THEN ben.InitialProjection07 ELSE gl.InitialProjection07 END OR
			 gl.InitialProjection08 != CASE WHEN @MonthsLoaded < 8 THEN ben.InitialProjection08 ELSE gl.InitialProjection08 END OR
			 gl.InitialProjection09 != CASE WHEN @MonthsLoaded < 9 THEN ben.InitialProjection09 ELSE gl.InitialProjection09 END OR
			 gl.InitialProjection10 != CASE WHEN @MonthsLoaded < 10 THEN ben.InitialProjection10 ELSE gl.InitialProjection10 END OR
			 gl.InitialProjection11 != CASE WHEN @MonthsLoaded < 11 THEN ben.InitialProjection11 ELSE gl.InitialProjection11 END OR
			 gl.InitialProjection12 != CASE WHEN @MonthsLoaded < 12 THEN ben.InitialProjection12 ELSE gl.InitialProjection12 END)
GO


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

-- fp.procCopyGlobalSpreadsFromOB
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1	2019-02-21  NL      B-22129		Created
** 1	2019-02-21  NL      B-22129		renamed GlobalSpread table
*************************************************************/
CREATE PROCEDURE [fp].[procCopyGlobalSpreadsFromOB]
	 @BudgetConfigID SMALLINT
WITH RECOMPILE
AS
BEGIN

	IF object_id('tempdb..#OBGlobalSpreads') IS NOT NULL 
	BEGIN
		DROP TABLE #OBGlobalSpreads
	END
	
 	CREATE TABLE #OBGlobalSpreads ([sortorder] [int] IDENTITY(3,1) NOT NULL, [Name] nvarchar(4000), 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), Total DECIMAL(19,4))

	INSERT INTO #OBGlobalSpreads([Name], [Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12], [Total])
	SELECT [Name], [Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12],
		   ([Month01] + [Month02] + [Month03] + [Month04] + [Month05] + [Month06] + [Month07] + [Month08] + [Month09] + [Month10] + [Month11] + [Month12]) AS Total
	FROM [clientob].[FactGlobalSpreads] 
	WHERE IsDeleted = 0 AND NOT (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)
	ORDER BY SpreadID

	INSERT INTO [fp].[GlobalSpread]([BudgetConfigID], [SpreadName], [SortOrder], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalSpreadValue])
	SELECT @BudgetConfigID, [Name], [sortorder], Month01/Total, Month02/Total, Month03/Total, Month04/Total, Month05/Total, Month06/Total, Month07/Total, Month08/Total, Month09/Total, Month10/Total, Month11/Total, Month12/Total, Total
	FROM #OBGlobalSpreads

END
GO


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

-- fp.procCreateGeneralLedgerSnapshot
CREATE   PROCEDURE [fp].[procCreateGeneralLedgerSnapshot] 
	@BudgetConfigID INT,
	@SnapshotID INT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    07-18-2024   MY        JAZZ-XXXXX  Initial Creation
	*************************************************************/

	INSERT INTO fp.GeneralLedgerSnapshot ([GeneralLedgerID], [SnapshotID],
		[BudgetConfigID],
		[EntityGroupConfigID],
		[EntityID],
		[DepartmentID],
		[AccountID],
		[FinancialReportingID],
		[VariabilityID],
		[APEModelSectionID],
		[AddDate],
		[IsNew],
		[FlexingTypeID],
		[ChangeHistoryGroupingGUID],
		[BudgetLockType],
		[BudgetLockFlag],
		[TargetLockType],
		[TargetLockFlag],
		[ProjectionLockType],
		[ProjectionLockFlag],
		[SampledBudget01],
		[SampledBudget02],
		[SampledBudget03],
		[SampledBudget04],
		[SampledBudget05],
		[SampledBudget06],
		[SampledBudget07],
		[SampledBudget08],
		[SampledBudget09],
		[SampledBudget10],
		[SampledBudget11],
		[SampledBudget12],
		[SampledProjection01],
		[SampledProjection02],
		[SampledProjection03],
		[SampledProjection04],
		[SampledProjection05],
		[SampledProjection06],
		[SampledProjection07],
		[SampledProjection08],
		[SampledProjection09],
		[SampledProjection10],
		[SampledProjection11],
		[SampledProjection12],
		[InitialBudget01],
		[InitialBudget02],
		[InitialBudget03],
		[InitialBudget04],
		[InitialBudget05],
		[InitialBudget06],
		[InitialBudget07],
		[InitialBudget08],
		[InitialBudget09],
		[InitialBudget10],
		[InitialBudget11],
		[InitialBudget12],
		[InitialProjection01],
		[InitialProjection02],
		[InitialProjection03],
		[InitialProjection04],
		[InitialProjection05],
		[InitialProjection06],
		[InitialProjection07],
		[InitialProjection08],
		[InitialProjection09],
		[InitialProjection10],
		[InitialProjection11],
		[InitialProjection12],
		[TargetAdjusted01],
		[TargetAdjusted02],
		[TargetAdjusted03],
		[TargetAdjusted04],
		[TargetAdjusted05],
		[TargetAdjusted06],
		[TargetAdjusted07],
		[TargetAdjusted08],
		[TargetAdjusted09],
		[TargetAdjusted10],
		[TargetAdjusted11],
		[TargetAdjusted12],
		[BudgetAdjusted01],
		[BudgetAdjusted02],
		[BudgetAdjusted03],
		[BudgetAdjusted04],
		[BudgetAdjusted05],
		[BudgetAdjusted06],
		[BudgetAdjusted07],
		[BudgetAdjusted08],
		[BudgetAdjusted09],
		[BudgetAdjusted10],
		[BudgetAdjusted11],
		[BudgetAdjusted12],
		[ProjectionAdjusted01],
		[ProjectionAdjusted02],
		[ProjectionAdjusted03],
		[ProjectionAdjusted04],
		[ProjectionAdjusted05],
		[ProjectionAdjusted06],
		[ProjectionAdjusted07],
		[ProjectionAdjusted08],
		[ProjectionAdjusted09],
		[ProjectionAdjusted10],
		[ProjectionAdjusted11],
		[ProjectionAdjusted12],
		[InitialBudgetDollarsPerUOS01],
		[InitialBudgetDollarsPerUOS02],
		[InitialBudgetDollarsPerUOS03],
		[InitialBudgetDollarsPerUOS04],
		[InitialBudgetDollarsPerUOS05],
		[InitialBudgetDollarsPerUOS06],
		[InitialBudgetDollarsPerUOS07],
		[InitialBudgetDollarsPerUOS08],
		[InitialBudgetDollarsPerUOS09],
		[InitialBudgetDollarsPerUOS10],
		[InitialBudgetDollarsPerUOS11],
		[InitialBudgetDollarsPerUOS12],
		[InitialProjectionDollarsPerUOS01],
		[InitialProjectionDollarsPerUOS02],
		[InitialProjectionDollarsPerUOS03],
		[InitialProjectionDollarsPerUOS04],
		[InitialProjectionDollarsPerUOS05],
		[InitialProjectionDollarsPerUOS06],
		[InitialProjectionDollarsPerUOS07],
		[InitialProjectionDollarsPerUOS08],
		[InitialProjectionDollarsPerUOS09],
		[InitialProjectionDollarsPerUOS10],
		[InitialProjectionDollarsPerUOS11],
		[InitialProjectionDollarsPerUOS12],
		[TargetDollarsPerUOSAdjusted01],
		[TargetDollarsPerUOSAdjusted02],
		[TargetDollarsPerUOSAdjusted03],
		[TargetDollarsPerUOSAdjusted04],
		[TargetDollarsPerUOSAdjusted05],
		[TargetDollarsPerUOSAdjusted06],
		[TargetDollarsPerUOSAdjusted07],
		[TargetDollarsPerUOSAdjusted08],
		[TargetDollarsPerUOSAdjusted09],
		[TargetDollarsPerUOSAdjusted10],
		[TargetDollarsPerUOSAdjusted11],
		[TargetDollarsPerUOSAdjusted12],
		[BudgetDollarsPerUOSAdjusted01],
		[BudgetDollarsPerUOSAdjusted02],
		[BudgetDollarsPerUOSAdjusted03],
		[BudgetDollarsPerUOSAdjusted04],
		[BudgetDollarsPerUOSAdjusted05],
		[BudgetDollarsPerUOSAdjusted06],
		[BudgetDollarsPerUOSAdjusted07],
		[BudgetDollarsPerUOSAdjusted08],
		[BudgetDollarsPerUOSAdjusted09],
		[BudgetDollarsPerUOSAdjusted10],
		[BudgetDollarsPerUOSAdjusted11],
		[BudgetDollarsPerUOSAdjusted12],
		[ProjectionDollarsPerUOSAdjusted01],
		[ProjectionDollarsPerUOSAdjusted02],
		[ProjectionDollarsPerUOSAdjusted03],
		[ProjectionDollarsPerUOSAdjusted04],
		[ProjectionDollarsPerUOSAdjusted05],
		[ProjectionDollarsPerUOSAdjusted06],
		[ProjectionDollarsPerUOSAdjusted07],
		[ProjectionDollarsPerUOSAdjusted08],
		[ProjectionDollarsPerUOSAdjusted09],
		[ProjectionDollarsPerUOSAdjusted10],
		[ProjectionDollarsPerUOSAdjusted11],
		[ProjectionDollarsPerUOSAdjusted12],
		[InitialBudgetPercentOfCharge01],
		[InitialBudgetPercentOfCharge02],
		[InitialBudgetPercentOfCharge03],
		[InitialBudgetPercentOfCharge04],
		[InitialBudgetPercentOfCharge05],
		[InitialBudgetPercentOfCharge06],
		[InitialBudgetPercentOfCharge07],
		[InitialBudgetPercentOfCharge08],
		[InitialBudgetPercentOfCharge09],
		[InitialBudgetPercentOfCharge10],
		[InitialBudgetPercentOfCharge11],
		[InitialBudgetPercentOfCharge12],
		[InitialProjectionPercentOfCharge01],
		[InitialProjectionPercentOfCharge02],
		[InitialProjectionPercentOfCharge03],
		[InitialProjectionPercentOfCharge04],
		[InitialProjectionPercentOfCharge05],
		[InitialProjectionPercentOfCharge06],
		[InitialProjectionPercentOfCharge07],
		[InitialProjectionPercentOfCharge08],
		[InitialProjectionPercentOfCharge09],
		[InitialProjectionPercentOfCharge10],
		[InitialProjectionPercentOfCharge11],
		[InitialProjectionPercentOfCharge12],
		[TargetPercentOfChargeAdjusted01],
		[TargetPercentOfChargeAdjusted02],
		[TargetPercentOfChargeAdjusted03],
		[TargetPercentOfChargeAdjusted04],
		[TargetPercentOfChargeAdjusted05],
		[TargetPercentOfChargeAdjusted06],
		[TargetPercentOfChargeAdjusted07],
		[TargetPercentOfChargeAdjusted08],
		[TargetPercentOfChargeAdjusted09],
		[TargetPercentOfChargeAdjusted10],
		[TargetPercentOfChargeAdjusted11],
		[TargetPercentOfChargeAdjusted12],
		[BudgetPercentOfChargeAdjusted01],
		[BudgetPercentOfChargeAdjusted02],
		[BudgetPercentOfChargeAdjusted03],
		[BudgetPercentOfChargeAdjusted04],
		[BudgetPercentOfChargeAdjusted05],
		[BudgetPercentOfChargeAdjusted06],
		[BudgetPercentOfChargeAdjusted07],
		[BudgetPercentOfChargeAdjusted08],
		[BudgetPercentOfChargeAdjusted09],
		[BudgetPercentOfChargeAdjusted10],
		[BudgetPercentOfChargeAdjusted11],
		[BudgetPercentOfChargeAdjusted12],
		[ProjectionPercentOfChargeAdjusted01],
		[ProjectionPercentOfChargeAdjusted02],
		[ProjectionPercentOfChargeAdjusted03],
		[ProjectionPercentOfChargeAdjusted04],
		[ProjectionPercentOfChargeAdjusted05],
		[ProjectionPercentOfChargeAdjusted06],
		[ProjectionPercentOfChargeAdjusted07],
		[ProjectionPercentOfChargeAdjusted08],
		[ProjectionPercentOfChargeAdjusted09],
		[ProjectionPercentOfChargeAdjusted10],
		[ProjectionPercentOfChargeAdjusted11],
		[ProjectionPercentOfChargeAdjusted12],
		[TargetPercentAdjustmentFactor01],
		[TargetPercentAdjustmentFactor02],
		[TargetPercentAdjustmentFactor03],
		[TargetPercentAdjustmentFactor04],
		[TargetPercentAdjustmentFactor05],
		[TargetPercentAdjustmentFactor06],
		[TargetPercentAdjustmentFactor07],
		[TargetPercentAdjustmentFactor08],
		[TargetPercentAdjustmentFactor09],
		[TargetPercentAdjustmentFactor10],
		[TargetPercentAdjustmentFactor11],
		[TargetPercentAdjustmentFactor12],
		[BudgetPercentAdjustmentFactor01],
		[BudgetPercentAdjustmentFactor02],
		[BudgetPercentAdjustmentFactor03],
		[BudgetPercentAdjustmentFactor04],
		[BudgetPercentAdjustmentFactor05],
		[BudgetPercentAdjustmentFactor06],
		[BudgetPercentAdjustmentFactor07],
		[BudgetPercentAdjustmentFactor08],
		[BudgetPercentAdjustmentFactor09],
		[BudgetPercentAdjustmentFactor10],
		[BudgetPercentAdjustmentFactor11],
		[BudgetPercentAdjustmentFactor12],
		[ProjectionPercentAdjustmentFactor01],
		[ProjectionPercentAdjustmentFactor02],
		[ProjectionPercentAdjustmentFactor03],
		[ProjectionPercentAdjustmentFactor04],
		[ProjectionPercentAdjustmentFactor05],
		[ProjectionPercentAdjustmentFactor06],
		[ProjectionPercentAdjustmentFactor07],
		[ProjectionPercentAdjustmentFactor08],
		[ProjectionPercentAdjustmentFactor09],
		[ProjectionPercentAdjustmentFactor10],
		[ProjectionPercentAdjustmentFactor11],
		[ProjectionPercentAdjustmentFactor12])
	SELECT 
		[GeneralLedgerID],
		@SnapshotID,
		[BudgetConfigID],
		[EntityGroupConfigID],
		[EntityID],
		[DepartmentID],
		[AccountID],
		[FinancialReportingID],
		[VariabilityID],
		[APEModelSectionID],
		[AddDate],
		[IsNew],
		[FlexingTypeID],
		[ChangeHistoryGroupingGUID],

		[BudgetLockType],
		[BudgetLockFlag],
		[TargetLockType],
		[TargetLockFlag],
		[ProjectionLockType],
		[ProjectionLockFlag],

		[SampledBudget01],
		[SampledBudget02],
		[SampledBudget03],
		[SampledBudget04],
		[SampledBudget05],
		[SampledBudget06],
		[SampledBudget07],
		[SampledBudget08],
		[SampledBudget09],
		[SampledBudget10],
		[SampledBudget11],
		[SampledBudget12],
		[SampledProjection01],
		[SampledProjection02],
		[SampledProjection03],
		[SampledProjection04],
		[SampledProjection05],
		[SampledProjection06],
		[SampledProjection07],
		[SampledProjection08],
		[SampledProjection09],
		[SampledProjection10],
		[SampledProjection11],
		[SampledProjection12],
		[InitialBudget01],
		[InitialBudget02],
		[InitialBudget03],
		[InitialBudget04],
		[InitialBudget05],
		[InitialBudget06],
		[InitialBudget07],
		[InitialBudget08],
		[InitialBudget09],
		[InitialBudget10],
		[InitialBudget11],
		[InitialBudget12],
		[InitialProjection01],
		[InitialProjection02],
		[InitialProjection03],
		[InitialProjection04],
		[InitialProjection05],
		[InitialProjection06],
		[InitialProjection07],
		[InitialProjection08],
		[InitialProjection09],
		[InitialProjection10],
		[InitialProjection11],
		[InitialProjection12],
		[TargetAdjusted01],
		[TargetAdjusted02],
		[TargetAdjusted03],
		[TargetAdjusted04],
		[TargetAdjusted05],
		[TargetAdjusted06],
		[TargetAdjusted07],
		[TargetAdjusted08],
		[TargetAdjusted09],
		[TargetAdjusted10],
		[TargetAdjusted11],
		[TargetAdjusted12],
		[BudgetAdjusted01],
		[BudgetAdjusted02],
		[BudgetAdjusted03],
		[BudgetAdjusted04],
		[BudgetAdjusted05],
		[BudgetAdjusted06],
		[BudgetAdjusted07],
		[BudgetAdjusted08],
		[BudgetAdjusted09],
		[BudgetAdjusted10],
		[BudgetAdjusted11],
		[BudgetAdjusted12],
		[ProjectionAdjusted01],
		[ProjectionAdjusted02],
		[ProjectionAdjusted03],
		[ProjectionAdjusted04],
		[ProjectionAdjusted05],
		[ProjectionAdjusted06],
		[ProjectionAdjusted07],
		[ProjectionAdjusted08],
		[ProjectionAdjusted09],
		[ProjectionAdjusted10],
		[ProjectionAdjusted11],
		[ProjectionAdjusted12],

		[InitialBudgetDollarsPerUOS01],
		[InitialBudgetDollarsPerUOS02],
		[InitialBudgetDollarsPerUOS03],
		[InitialBudgetDollarsPerUOS04],
		[InitialBudgetDollarsPerUOS05],
		[InitialBudgetDollarsPerUOS06],
		[InitialBudgetDollarsPerUOS07],
		[InitialBudgetDollarsPerUOS08],
		[InitialBudgetDollarsPerUOS09],
		[InitialBudgetDollarsPerUOS10],
		[InitialBudgetDollarsPerUOS11],
		[InitialBudgetDollarsPerUOS12],
		[InitialProjectionDollarsPerUOS01],
		[InitialProjectionDollarsPerUOS02],
		[InitialProjectionDollarsPerUOS03],
		[InitialProjectionDollarsPerUOS04],
		[InitialProjectionDollarsPerUOS05],
		[InitialProjectionDollarsPerUOS06],
		[InitialProjectionDollarsPerUOS07],
		[InitialProjectionDollarsPerUOS08],
		[InitialProjectionDollarsPerUOS09],
		[InitialProjectionDollarsPerUOS10],
		[InitialProjectionDollarsPerUOS11],
		[InitialProjectionDollarsPerUOS12],
		[TargetDollarsPerUOSAdjusted01],
		[TargetDollarsPerUOSAdjusted02],
		[TargetDollarsPerUOSAdjusted03],
		[TargetDollarsPerUOSAdjusted04],
		[TargetDollarsPerUOSAdjusted05],
		[TargetDollarsPerUOSAdjusted06],
		[TargetDollarsPerUOSAdjusted07],
		[TargetDollarsPerUOSAdjusted08],
		[TargetDollarsPerUOSAdjusted09],
		[TargetDollarsPerUOSAdjusted10],
		[TargetDollarsPerUOSAdjusted11],
		[TargetDollarsPerUOSAdjusted12],
		[BudgetDollarsPerUOSAdjusted01],
		[BudgetDollarsPerUOSAdjusted02],
		[BudgetDollarsPerUOSAdjusted03],
		[BudgetDollarsPerUOSAdjusted04],
		[BudgetDollarsPerUOSAdjusted05],
		[BudgetDollarsPerUOSAdjusted06],
		[BudgetDollarsPerUOSAdjusted07],
		[BudgetDollarsPerUOSAdjusted08],
		[BudgetDollarsPerUOSAdjusted09],
		[BudgetDollarsPerUOSAdjusted10],
		[BudgetDollarsPerUOSAdjusted11],
		[BudgetDollarsPerUOSAdjusted12],
		[ProjectionDollarsPerUOSAdjusted01],
		[ProjectionDollarsPerUOSAdjusted02],
		[ProjectionDollarsPerUOSAdjusted03],
		[ProjectionDollarsPerUOSAdjusted04],
		[ProjectionDollarsPerUOSAdjusted05],
		[ProjectionDollarsPerUOSAdjusted06],
		[ProjectionDollarsPerUOSAdjusted07],
		[ProjectionDollarsPerUOSAdjusted08],
		[ProjectionDollarsPerUOSAdjusted09],
		[ProjectionDollarsPerUOSAdjusted10],
		[ProjectionDollarsPerUOSAdjusted11],
		[ProjectionDollarsPerUOSAdjusted12],

		[InitialBudgetPercentOfCharge01],
		[InitialBudgetPercentOfCharge02],
		[InitialBudgetPercentOfCharge03],
		[InitialBudgetPercentOfCharge04],
		[InitialBudgetPercentOfCharge05],
		[InitialBudgetPercentOfCharge06],
		[InitialBudgetPercentOfCharge07],
		[InitialBudgetPercentOfCharge08],
		[InitialBudgetPercentOfCharge09],
		[InitialBudgetPercentOfCharge10],
		[InitialBudgetPercentOfCharge11],
		[InitialBudgetPercentOfCharge12],
		[InitialProjectionPercentOfCharge01],
		[InitialProjectionPercentOfCharge02],
		[InitialProjectionPercentOfCharge03],
		[InitialProjectionPercentOfCharge04],
		[InitialProjectionPercentOfCharge05],
		[InitialProjectionPercentOfCharge06],
		[InitialProjectionPercentOfCharge07],
		[InitialProjectionPercentOfCharge08],
		[InitialProjectionPercentOfCharge09],
		[InitialProjectionPercentOfCharge10],
		[InitialProjectionPercentOfCharge11],
		[InitialProjectionPercentOfCharge12],
		[TargetPercentOfChargeAdjusted01],
		[TargetPercentOfChargeAdjusted02],
		[TargetPercentOfChargeAdjusted03],
		[TargetPercentOfChargeAdjusted04],
		[TargetPercentOfChargeAdjusted05],
		[TargetPercentOfChargeAdjusted06],
		[TargetPercentOfChargeAdjusted07],
		[TargetPercentOfChargeAdjusted08],
		[TargetPercentOfChargeAdjusted09],
		[TargetPercentOfChargeAdjusted10],
		[TargetPercentOfChargeAdjusted11],
		[TargetPercentOfChargeAdjusted12],
		[BudgetPercentOfChargeAdjusted01],
		[BudgetPercentOfChargeAdjusted02],
		[BudgetPercentOfChargeAdjusted03],
		[BudgetPercentOfChargeAdjusted04],
		[BudgetPercentOfChargeAdjusted05],
		[BudgetPercentOfChargeAdjusted06],
		[BudgetPercentOfChargeAdjusted07],
		[BudgetPercentOfChargeAdjusted08],
		[BudgetPercentOfChargeAdjusted09],
		[BudgetPercentOfChargeAdjusted10],
		[BudgetPercentOfChargeAdjusted11],
		[BudgetPercentOfChargeAdjusted12],
		[ProjectionPercentOfChargeAdjusted01],
		[ProjectionPercentOfChargeAdjusted02],
		[ProjectionPercentOfChargeAdjusted03],
		[ProjectionPercentOfChargeAdjusted04],
		[ProjectionPercentOfChargeAdjusted05],
		[ProjectionPercentOfChargeAdjusted06],
		[ProjectionPercentOfChargeAdjusted07],
		[ProjectionPercentOfChargeAdjusted08],
		[ProjectionPercentOfChargeAdjusted09],
		[ProjectionPercentOfChargeAdjusted10],
		[ProjectionPercentOfChargeAdjusted11],
		[ProjectionPercentOfChargeAdjusted12],
				
		[TargetPercentAdjustmentFactor01],
		[TargetPercentAdjustmentFactor02],
		[TargetPercentAdjustmentFactor03],
		[TargetPercentAdjustmentFactor04],
		[TargetPercentAdjustmentFactor05],
		[TargetPercentAdjustmentFactor06],
		[TargetPercentAdjustmentFactor07],
		[TargetPercentAdjustmentFactor08],
		[TargetPercentAdjustmentFactor09],
		[TargetPercentAdjustmentFactor10],
		[TargetPercentAdjustmentFactor11],
		[TargetPercentAdjustmentFactor12],
		[BudgetPercentAdjustmentFactor01],
		[BudgetPercentAdjustmentFactor02],
		[BudgetPercentAdjustmentFactor03],
		[BudgetPercentAdjustmentFactor04],
		[BudgetPercentAdjustmentFactor05],
		[BudgetPercentAdjustmentFactor06],
		[BudgetPercentAdjustmentFactor07],
		[BudgetPercentAdjustmentFactor08],
		[BudgetPercentAdjustmentFactor09],
		[BudgetPercentAdjustmentFactor10],
		[BudgetPercentAdjustmentFactor11],
		[BudgetPercentAdjustmentFactor12],
		[ProjectionPercentAdjustmentFactor01],
		[ProjectionPercentAdjustmentFactor02],
		[ProjectionPercentAdjustmentFactor03],
		[ProjectionPercentAdjustmentFactor04],
		[ProjectionPercentAdjustmentFactor05],
		[ProjectionPercentAdjustmentFactor06],
		[ProjectionPercentAdjustmentFactor07],
		[ProjectionPercentAdjustmentFactor08],
		[ProjectionPercentAdjustmentFactor09],
		[ProjectionPercentAdjustmentFactor10],
		[ProjectionPercentAdjustmentFactor11],
		[ProjectionPercentAdjustmentFactor12]
	FROM [fp].[GeneralLedger]
	WHERE BudgetConfigID = @BudgetConfigID

	-- Need to update the number of adjustments in case when this processed vs when it was originally kicked off is different.
	DECLARE @NumberOfAdjustments INT;
	SET @NumberOfAdjustments = (
		SELECT COUNT(*) 
		FROM [fp].[viewUserViewGeneralLedgerAdjustments] gla
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = gla.BudgetConfigGUID
		WHERE bc.BudgetConfigID = @BudgetConfigID
	)

	-- Update the Date processed date
	UPDATE fp.BudgetSnapshot 
	SET DateProcessedUTC = GETUTCDATE(),
		AdjustmentsStampedOff = @NumberOfAdjustments
	WHERE SnapshotID = @SnapshotID

END
GO


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

-- fp.procCrosswalkChargeToGeneralLedger
CREATE   PROCEDURE [fp].[procCrosswalkChargeToGeneralLedger]
	 @EntityGroupConfigID INT,
	 @MonthsLoaded INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
 WITH RECOMPILE  
 AS
 	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  BLI            Description
	 ** 1 	 2021-03-10  BK  	 JAZZ-16331	    Create proc
	 ** 2 	 2021-10-05  MD  	 JAZZ-26615	    Add OPTION RECOMPILE
	 ** 3 	 2023-04-06  MD  	 JAZZ-52587	    Update for new data structure
	 ** 4 	 2023-04-21  BK  	 JAZZ------	    Performance improvement
	 ** 5 	 2023-08-04  BW  	 JAZZ-58151	    Update for new GL data structure
	 ** 6 	 2024-09-11  MY  	 JAZZ-75442	    GL Data is locked with locktype 3 with no crosswalk configured for chosen entity group
	 *************************************************************/
 BEGIN
 	
		
   IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
 	IF OBJECT_ID('tempdb..#CrosswalkRecords') IS NOT NULL DROP TABLE #CrosswalkRecords

	CREATE TABLE #CrosswalkRecords(DepartmentID INT, AccountID INT,
		TargetAdjusted01 DECIMAL(19,8), TargetAdjusted02 DECIMAL(19,8), TargetAdjusted03 DECIMAL(19,8), 
		TargetAdjusted04 DECIMAL(19,8), TargetAdjusted05 DECIMAL(19,8), TargetAdjusted06 DECIMAL(19,8), 
		TargetAdjusted07 DECIMAL(19,8), TargetAdjusted08 DECIMAL(19,8), TargetAdjusted09 DECIMAL(19,8), 
		TargetAdjusted10 DECIMAL(19,8), TargetAdjusted11 DECIMAL(19,8), TargetAdjusted12 DECIMAL(19,8),
		BudgetAdjusted01 DECIMAL(19,8), BudgetAdjusted02 DECIMAL(19,8), BudgetAdjusted03 DECIMAL(19,8), 
		BudgetAdjusted04 DECIMAL(19,8), BudgetAdjusted05 DECIMAL(19,8), BudgetAdjusted06 DECIMAL(19,8), 
		BudgetAdjusted07 DECIMAL(19,8), BudgetAdjusted08 DECIMAL(19,8), BudgetAdjusted09 DECIMAL(19,8), 
		BudgetAdjusted10 DECIMAL(19,8), BudgetAdjusted11 DECIMAL(19,8), BudgetAdjusted12 DECIMAL(19,8),
		ProjectionAdjusted01 DECIMAL(19,8), ProjectionAdjusted02 DECIMAL(19,8), ProjectionAdjusted03 DECIMAL(19,8), 
		ProjectionAdjusted04 DECIMAL(19,8), ProjectionAdjusted05 DECIMAL(19,8), ProjectionAdjusted06 DECIMAL(19,8), 
		ProjectionAdjusted07 DECIMAL(19,8), ProjectionAdjusted08 DECIMAL(19,8), ProjectionAdjusted09 DECIMAL(19,8), 
		ProjectionAdjusted10 DECIMAL(19,8), ProjectionAdjusted11 DECIMAL(19,8), ProjectionAdjusted12 DECIMAL(19,8)
	)								 
	
	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 
	BEGIN		
		INSERT INTO #CrosswalkRecords (DepartmentID, AccountID,
			TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06, 
			TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12,
			BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, 
			BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12,
			ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, 
			ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)
		SELECT DISTINCT config.DepartmentID, config.AccountID,
			SUM(TargetDollarsAdjusted01), SUM(TargetDollarsAdjusted02), SUM(TargetDollarsAdjusted03), 
			SUM(TargetDollarsAdjusted04), SUM(TargetDollarsAdjusted05), SUM(TargetDollarsAdjusted06), 
			SUM(TargetDollarsAdjusted07), SUM(TargetDollarsAdjusted08), SUM(TargetDollarsAdjusted09), 
			SUM(TargetDollarsAdjusted10), SUM(TargetDollarsAdjusted11), SUM(TargetDollarsAdjusted12),
			SUM(BudgetDollarsAdjusted01), SUM(BudgetDollarsAdjusted02), SUM(BudgetDollarsAdjusted03), 
			SUM(BudgetDollarsAdjusted04), SUM(BudgetDollarsAdjusted05), SUM(BudgetDollarsAdjusted06), 
			SUM(BudgetDollarsAdjusted07), SUM(BudgetDollarsAdjusted08), SUM(BudgetDollarsAdjusted09), 
			SUM(BudgetDollarsAdjusted10), SUM(BudgetDollarsAdjusted11), SUM(BudgetDollarsAdjusted12),
			SUM(ProjectionDollarsAdjusted01), SUM(ProjectionDollarsAdjusted02), SUM(ProjectionDollarsAdjusted03), 
			SUM(ProjectionDollarsAdjusted04), SUM(ProjectionDollarsAdjusted05), SUM(ProjectionDollarsAdjusted06), 
			SUM(ProjectionDollarsAdjusted07), SUM(ProjectionDollarsAdjusted08), SUM(ProjectionDollarsAdjusted09), 
			SUM(ProjectionDollarsAdjusted10), SUM(ProjectionDollarsAdjusted11), SUM(ProjectionDollarsAdjusted12)
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted)
			INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID
				AND config.ChargeCodeID = cv.ChargeCodeID
				AND config.PatientClassID = cv.PatientClassID
				AND config.EntityGroupConfigID = cv.EntityGroupConfigID
		WHERE config.EntityGroupConfigID = @EntityGroupConfigID 
			AND config.IsRecordDeleted = 0
			AND config.AccountID > 0
		GROUP BY config.DepartmentID, config.AccountID
	END
	ELSE
	BEGIN
		CREATE TABLE #FilterByDepartment (DepartmentID int)
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

		INSERT INTO #CrosswalkRecords (DepartmentID, AccountID,
			TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06, 
			TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12,
			BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, 
			BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12,
			ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, 
			ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)
		SELECT DISTINCT config.DepartmentID, config.AccountID,
			SUM(TargetDollarsAdjusted01), SUM(TargetDollarsAdjusted02), SUM(TargetDollarsAdjusted03), 
			SUM(TargetDollarsAdjusted04), SUM(TargetDollarsAdjusted05), SUM(TargetDollarsAdjusted06), 
			SUM(TargetDollarsAdjusted07), SUM(TargetDollarsAdjusted08), SUM(TargetDollarsAdjusted09), 
			SUM(TargetDollarsAdjusted10), SUM(TargetDollarsAdjusted11), SUM(TargetDollarsAdjusted12),
			SUM(BudgetDollarsAdjusted01), SUM(BudgetDollarsAdjusted02), SUM(BudgetDollarsAdjusted03), 
			SUM(BudgetDollarsAdjusted04), SUM(BudgetDollarsAdjusted05), SUM(BudgetDollarsAdjusted06), 
			SUM(BudgetDollarsAdjusted07), SUM(BudgetDollarsAdjusted08), SUM(BudgetDollarsAdjusted09), 
			SUM(BudgetDollarsAdjusted10), SUM(BudgetDollarsAdjusted11), SUM(BudgetDollarsAdjusted12),
			SUM(ProjectionDollarsAdjusted01), SUM(ProjectionDollarsAdjusted02), SUM(ProjectionDollarsAdjusted03), 
			SUM(ProjectionDollarsAdjusted04), SUM(ProjectionDollarsAdjusted05), SUM(ProjectionDollarsAdjusted06), 
			SUM(ProjectionDollarsAdjusted07), SUM(ProjectionDollarsAdjusted08), SUM(ProjectionDollarsAdjusted09), 
			SUM(ProjectionDollarsAdjusted10), SUM(ProjectionDollarsAdjusted11), SUM(ProjectionDollarsAdjusted12)
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted)
			INNER JOIN #FilterByDepartment ft ON config.DepartmentID = ft.DepartmentID
			INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID
				AND config.ChargeCodeID = cv.ChargeCodeID
				AND config.PatientClassID = cv.PatientClassID
				AND config.EntityGroupConfigID = cv.EntityGroupConfigID
		WHERE config.EntityGroupConfigID = @EntityGroupConfigID 
			AND config.IsRecordDeleted = 0
			AND config.AccountID > 0
		GROUP BY config.DepartmentID, config.AccountID

		DROP TABLE #FilterByDepartment

	END


	IF (@IsDebug = 0) 
	BEGIN
		UPDATE gl
			SET  
			    TargetAdjusted01 = xwalk.TargetAdjusted01 
				,TargetAdjusted02 = xwalk.TargetAdjusted02 
				,TargetAdjusted03 = xwalk.TargetAdjusted03 
				,TargetAdjusted04 = xwalk.TargetAdjusted04 
				,TargetAdjusted05 = xwalk.TargetAdjusted05 
				,TargetAdjusted06 = xwalk.TargetAdjusted06 
				,TargetAdjusted07 = xwalk.TargetAdjusted07 
				,TargetAdjusted08 = xwalk.TargetAdjusted08 
				,TargetAdjusted09 = xwalk.TargetAdjusted09 
				,TargetAdjusted10 = xwalk.TargetAdjusted10 
				,TargetAdjusted11 = xwalk.TargetAdjusted11 
				,TargetAdjusted12 = xwalk.TargetAdjusted12 
				,TargetLockType = 3
				,TargetLockFlag = 1
				,BudgetAdjusted01 = xwalk.BudgetAdjusted01 
				,BudgetAdjusted02 = xwalk.BudgetAdjusted02 
				,BudgetAdjusted03 = xwalk.BudgetAdjusted03 
				,BudgetAdjusted04 = xwalk.BudgetAdjusted04 
				,BudgetAdjusted05 = xwalk.BudgetAdjusted05 
				,BudgetAdjusted06 = xwalk.BudgetAdjusted06 
				,BudgetAdjusted07 = xwalk.BudgetAdjusted07 
				,BudgetAdjusted08 = xwalk.BudgetAdjusted08 
				,BudgetAdjusted09 = xwalk.BudgetAdjusted09 
				,BudgetAdjusted10 = xwalk.BudgetAdjusted10 
				,BudgetAdjusted11 = xwalk.BudgetAdjusted11 
				,BudgetAdjusted12 = xwalk.BudgetAdjusted12 
				,BudgetLockType = 3
				,BudgetLockFlag = 1
		FROM fp.GeneralLedger gl
			INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE 
			gl.VariabilityID = 2 
			AND gl.EntityGroupConfigID = @EntityGroupConfigID 
			AND (    
			  gl.TargetAdjusted01 != xwalk.TargetAdjusted01 
		   OR gl.TargetAdjusted02 != xwalk.TargetAdjusted02 
		   OR gl.TargetAdjusted03 != xwalk.TargetAdjusted03 
		   OR gl.TargetAdjusted04 != xwalk.TargetAdjusted04 
		   OR gl.TargetAdjusted05 != xwalk.TargetAdjusted05 
		   OR gl.TargetAdjusted06 != xwalk.TargetAdjusted06 
		   OR gl.TargetAdjusted07 != xwalk.TargetAdjusted07 
		   OR gl.TargetAdjusted08 != xwalk.TargetAdjusted08 
		   OR gl.TargetAdjusted09 != xwalk.TargetAdjusted09 
		   OR gl.TargetAdjusted10 != xwalk.TargetAdjusted10 
		   OR gl.TargetAdjusted11 != xwalk.TargetAdjusted11
		   OR gl.TargetAdjusted12 != xwalk.TargetAdjusted12 
		   OR gl.TargetLockFlag != 1 
		   OR gl.BudgetAdjusted01 != xwalk.BudgetAdjusted01 
		   OR gl.BudgetAdjusted02 != xwalk.BudgetAdjusted02 
		   OR gl.BudgetAdjusted03 != xwalk.BudgetAdjusted03 
		   OR gl.BudgetAdjusted04 != xwalk.BudgetAdjusted04 
		   OR gl.BudgetAdjusted05 != xwalk.BudgetAdjusted05 
		   OR gl.BudgetAdjusted06 != xwalk.BudgetAdjusted06 
		   OR gl.BudgetAdjusted07 != xwalk.BudgetAdjusted07 
		   OR gl.BudgetAdjusted08 != xwalk.BudgetAdjusted08 
		   OR gl.BudgetAdjusted09 != xwalk.BudgetAdjusted09 
		   OR gl.BudgetAdjusted10 != xwalk.BudgetAdjusted10 
		   OR gl.BudgetAdjusted11 != xwalk.BudgetAdjusted11
		   OR gl.BudgetAdjusted12 != xwalk.BudgetAdjusted12 
		   OR gl.BudgetLockFlag != 1 )


		UPDATE gl
			SET  
				TargetAdjusted01 = 0
				,TargetAdjusted02 = 0
				,TargetAdjusted03 = 0
				,TargetAdjusted04 = 0
				,TargetAdjusted05 = 0
				,TargetAdjusted06 = 0
				,TargetAdjusted07 = 0
				,TargetAdjusted08 = 0
				,TargetAdjusted09 = 0
				,TargetAdjusted10 = 0
				,TargetAdjusted11 = 0
				,TargetAdjusted12 = 0
				,TargetLockType = 3
				,TargetLockFlag = 1
				,BudgetAdjusted01 = 0
				,BudgetAdjusted02 = 0
				,BudgetAdjusted03 = 0
				,BudgetAdjusted04 = 0
				,BudgetAdjusted05 = 0
				,BudgetAdjusted06 = 0
				,BudgetAdjusted07 = 0
				,BudgetAdjusted08 = 0
				,BudgetAdjusted09 = 0
				,BudgetAdjusted10 = 0
				,BudgetAdjusted11 = 0
				,BudgetAdjusted12 = 0
				,BudgetLockType = 3
				,BudgetLockFlag = 1

		FROM fp.GeneralLedger gl
			INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE 
			gl.VariabilityID = 1 
			AND gl.EntityGroupConfigID = @EntityGroupConfigID
			AND (gl.TargetAdjusted01 != 0
				OR gl.TargetAdjusted02 != 0
				OR gl.TargetAdjusted03 != 0
				OR gl.TargetAdjusted04 != 0
				OR gl.TargetAdjusted05 != 0
				OR gl.TargetAdjusted06 != 0
				OR gl.TargetAdjusted07 != 0
				OR gl.TargetAdjusted08 != 0
				OR gl.TargetAdjusted09 != 0
				OR gl.TargetAdjusted10 != 0
				OR gl.TargetAdjusted11 != 0
				OR gl.TargetAdjusted12 != 0 
				OR gl.TargetLockFlag != 1
				OR gl.BudgetAdjusted01 != 0
				OR gl.BudgetAdjusted02 != 0
				OR gl.BudgetAdjusted03 != 0
				OR gl.BudgetAdjusted04 != 0
				OR gl.BudgetAdjusted05 != 0
				OR gl.BudgetAdjusted06 != 0
				OR gl.BudgetAdjusted07 != 0
				OR gl.BudgetAdjusted08 != 0
				OR gl.BudgetAdjusted09 != 0
				OR gl.BudgetAdjusted10 != 0
				OR gl.BudgetAdjusted11 != 0
				OR gl.BudgetAdjusted12 != 0 
				OR gl.BudgetLockFlag != 1
				)

		UPDATE gl
			SET  
				ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1  THEN gl.ProjectionAdjusted01 ELSE xwalk.ProjectionAdjusted01 END
				,ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2  THEN gl.ProjectionAdjusted02 ELSE xwalk.ProjectionAdjusted02 END
				,ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3  THEN gl.ProjectionAdjusted03 ELSE xwalk.ProjectionAdjusted03 END
				,ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4  THEN gl.ProjectionAdjusted04 ELSE xwalk.ProjectionAdjusted04 END
				,ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5  THEN gl.ProjectionAdjusted05 ELSE xwalk.ProjectionAdjusted05 END
				,ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6  THEN gl.ProjectionAdjusted06 ELSE xwalk.ProjectionAdjusted06 END
				,ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7  THEN gl.ProjectionAdjusted07 ELSE xwalk.ProjectionAdjusted07 END
				,ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8  THEN gl.ProjectionAdjusted08 ELSE xwalk.ProjectionAdjusted08 END
				,ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9  THEN gl.ProjectionAdjusted09 ELSE xwalk.ProjectionAdjusted09 END
				,ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE xwalk.ProjectionAdjusted10 END
				,ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE xwalk.ProjectionAdjusted11 END
				,ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE xwalk.ProjectionAdjusted12 END
				,ProjectionLockType = 3
				,ProjectionLockFlag = 1
		FROM fp.GeneralLedger gl
			INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE 
			gl.VariabilityID = 2 
			AND gl.EntityGroupConfigID = @EntityGroupConfigID
			AND (    
			  gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE xwalk.ProjectionAdjusted01 END
		   OR gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE xwalk.ProjectionAdjusted02 END
		   OR gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE xwalk.ProjectionAdjusted03 END
		   OR gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE xwalk.ProjectionAdjusted04 END
		   OR gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE xwalk.ProjectionAdjusted05 END
		   OR gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE xwalk.ProjectionAdjusted06 END
		   OR gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE xwalk.ProjectionAdjusted07 END
		   OR gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE xwalk.ProjectionAdjusted08 END
		   OR gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE xwalk.ProjectionAdjusted09 END
		   OR gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE xwalk.ProjectionAdjusted10 END
		   OR gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE xwalk.ProjectionAdjusted11 END
		   OR gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE xwalk.ProjectionAdjusted12 END
		   OR gl.ProjectionLockFlag != 1 )

		UPDATE gl
			SET  
				ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1  THEN gl.ProjectionAdjusted01 ELSE 0 END
				,ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2  THEN gl.ProjectionAdjusted02 ELSE 0 END
				,ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3  THEN gl.ProjectionAdjusted03 ELSE 0 END
				,ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4  THEN gl.ProjectionAdjusted04 ELSE 0 END
				,ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5  THEN gl.ProjectionAdjusted05 ELSE 0 END
				,ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6  THEN gl.ProjectionAdjusted06 ELSE 0 END
				,ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7  THEN gl.ProjectionAdjusted07 ELSE 0 END
				,ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8  THEN gl.ProjectionAdjusted08 ELSE 0 END
				,ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9  THEN gl.ProjectionAdjusted09 ELSE 0 END
				,ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END
				,ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END
				,ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END
				,ProjectionLockType = 3
				,ProjectionLockFlag = 1
		FROM fp.GeneralLedger gl
			INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE 
			gl.VariabilityID = 1 
			AND gl.EntityGroupConfigID = @EntityGroupConfigID 
			AND (    
			  gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END
		   OR gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END
		   OR gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END
		   OR gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END
		   OR gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END
		   OR gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END
		   OR gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END
		   OR gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END
		   OR gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END
		   OR gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END
		   OR gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END
		   OR gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END
		   OR gl.ProjectionLockFlag != 1 )

	END ELSE BEGIN
		SELECT 'RecordsToCrosswalk', * FROM #CrosswalkRecords
	END

 END;
GO


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

-- fp.procCrosswalkChargeToGeneralLedgerByPayorGroup
CREATE   PROCEDURE [fp].[procCrosswalkChargeToGeneralLedgerByPayorGroup]
	 @EntityGroupConfigID INT,
	 @MonthsLoaded INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @EntityID INT,
	 @IsDebug BIT = 0
WITH RECOMPILE
 AS
 	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  BLI            Description
	 ** 1 	 2021-09-21  MY  	 JAZZ-25836	    Initial
	 ** 2	 2021-11-18	 MY		 JAZZ-29482		Performance Tuning
	 ** 3	 2021-12-08	 MY		 JAZZ-30002		Add Batch Processing
	 ** 4	 2023-04-06	 MD		 JAZZ-52587		Update to support new CV data structure
	 ** 5	 2023-04-19	 MY		 JAZZ-53575		Improve performance on charge to GL crosswalk
	 ** 6	 6-15-2023   NT      JAZZ-56471		Add update statistics on #filterByDepartment on DBA's recommendation to improve performance
	 ** 7	 6-27-2023   MY      JAZZ-56923		Adding Service Line into the SLE to Charge payor mix calc
	 ** 8 	 2023-08-04  BW  	 JAZZ-58151	    Update for new GL data structure
	 ** 9 	 2023-04-11  MY  	 JAZZ-70660	    Update to leverage additional dimensions in mix table
	 ** 10 	 2024-09-12  MY  	 JAZZ-70741	    Update Charge to General Ledger Crosswalk Performance Improvement
	 ** 11 	 2024-12-05  MY  	 JAZZ-80511	    Implement performance improvements from ESC
	 *************************************************************/
 BEGIN
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
    IF OBJECT_ID('tempdb..#FilteredCrosswalkConfiguration') IS NOT NULL DROP TABLE #FilteredCrosswalkConfiguration
    IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount
    IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithAccount
 	IF OBJECT_ID('tempdb..#RecordsWithMixes') IS NOT NULL DROP TABLE #RecordsWithMixes
 	IF OBJECT_ID('tempdb..#RolledUpValues') IS NOT NULL DROP TABLE #RolledUpValues
 	IF OBJECT_ID('tempdb..#chargeVolumeEntities') IS NOT NULL DROP TABLE #chargeVolumeEntities

	DECLARE @SQL2 NVARCHAR(MAX); --esc-44799 MP

	-- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc
	DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value 
												FROM fp.viewBudgetConfigSetting setting
													INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID
													INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
													AND setting.Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0)
	-- JAZZ-70660: Adding Additional Dimensionality into the SLE to Charge payor mix calc
	DECLARE @IsAdditionalDimensionalityEnabled BIT = ISNULL((SELECT Value 
												FROM fp.viewBudgetConfigSetting setting
													INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID
													INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
													AND setting.Name = 'Enable Charge to General Ledger Crosswalk to Use Detailed Mix'), 0)

	-- This setting overrides the 'Enable ServiceLine level mix for Charge to GL Crosswalk' setting
	IF (@IsAdditionalDimensionalityEnabled = 1)
	BEGIN
		SET @IsServiceLineEnabled = 1;
	END

	CREATE TABLE #RolledUpValues(EntityID INT, DepartmentID INT, AccountID INT,
		Target01 DECIMAL(19,8), Target02 DECIMAL(19,8), Target03 DECIMAL(19,8), 
		Target04 DECIMAL(19,8), Target05 DECIMAL(19,8), Target06 DECIMAL(19,8), 
		Target07 DECIMAL(19,8), Target08 DECIMAL(19,8), Target09 DECIMAL(19,8), 
		Target10 DECIMAL(19,8), Target11 DECIMAL(19,8), Target12 DECIMAL(19,8),
		Budget01 DECIMAL(19,8), Budget02 DECIMAL(19,8), Budget03 DECIMAL(19,8), 
		Budget04 DECIMAL(19,8), Budget05 DECIMAL(19,8), Budget06 DECIMAL(19,8), 
		Budget07 DECIMAL(19,8), Budget08 DECIMAL(19,8), Budget09 DECIMAL(19,8), 
		Budget10 DECIMAL(19,8), Budget11 DECIMAL(19,8), Budget12 DECIMAL(19,8),
		Projection01 DECIMAL(19,8), Projection02 DECIMAL(19,8), Projection03 DECIMAL(19,8), 
		Projection04 DECIMAL(19,8), Projection05 DECIMAL(19,8), Projection06 DECIMAL(19,8), 
		Projection07 DECIMAL(19,8), Projection08 DECIMAL(19,8), Projection09 DECIMAL(19,8), 
		Projection10 DECIMAL(19,8), Projection11 DECIMAL(19,8), Projection12 DECIMAL(19,8), 
		--INDEX ix_RolledUpValues CLUSTERED (EntityID, DepartmentID, AccountID)
	)

	CREATE TABLE #mixTable (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT, 
		PatientClassID INT,
		ServiceLineID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		MSDRGID INT,
		CPTID INT,
		ProviderID INT,
		PayorID INT,
		PayorGroupID INT,
		BudgetMixPercentage DECIMAL(19, 8),
		ProjectionMixPercentage DECIMAL(19, 8)
		,INDEX BASE CLUSTERED (EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID)
	)

	CREATE TABLE #FilteredCrosswalkConfiguration
	(
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		DepartmentID INT,
		ChargeCodeID INT,
		PatientClassID INT,
		PayorGroupID INT,
		AccountID INT
	)	

	CREATE TABLE #DistinctCrosswalkConfiguration_WithoutAccount 
	(
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		DepartmentID INT,
		ChargeCodeID INT,
		PatientClassID INT,
		PayorGroupID INT
	)

	CREATE TABLE #DistinctCrosswalkConfiguration_WithAccount 
	(
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		DepartmentID INT,
		AccountID INT
	)

	SELECT DISTINCT EntityID AS ChargeVolumeEntityID, ServiceEntityID AS ServiceLineEncounterEntityID
	INTO #chargeVolumeEntities
	FROM fp.ChargeVolume
	WHERE EntityGroupConfigID = @EntityGroupConfigID
		AND EntityID = @EntityID

	IF (@IsAdditionalDimensionalityEnabled = 1)
	BEGIN
		INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID,
			MSDRGID, CPTID, ProviderID,	PayorID, PayorGroupID, ProjectionMixPercentage, BudgetMixPercentage)
		SELECT 
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID, 
			PatientClassID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			MSDRGID,
			CPTID,
			ProviderID,
			PayorID,
			PayorGroupID,
			ProjectionMixPercentage,
			BudgetMixPercentage	
		FROM fp.ServiceLineEncounterToChargePayorMix mix
			INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END ELSE BEGIN
		INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID,
			MSDRGID, CPTID, ProviderID,	PayorID, PayorGroupID, ProjectionMixPercentage,	BudgetMixPercentage)
		SELECT 
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID, 
			PatientClassID,
			CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE ServiceLineID END AS ServiceLineID,
			0 AS AgeCohortID,
			0 AS MedicalSurgicalID,
			0 AS MSDRGID,
			0 AS CPTID,
			0 AS ProviderID,
			0 AS PayorID,
			PayorGroupID,
			ProjectionMixPercentage,
			BudgetMixPercentage	
		FROM fp.viewServiceLineEncounterPayorGroupMix_Pivoted mix
			INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END

	UPDATE STATISTICS #mixTable; --esc-44799 MP

	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 
	BEGIN		
		INSERT INTO #FilteredCrosswalkConfiguration
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			config.DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID, 
			AccountID
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) 
			INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not
			AND IsRecordDeleted = 0

		INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID)
		SELECT DISTINCT
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			AccountID
		FROM #FilteredCrosswalkConfiguration fcc

		-- Filter to the distinct charge records so we don't duplicate charge records with the join.
		INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID
		FROM #FilteredCrosswalkConfiguration

		SET @SQL2 = '
		INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, Target01, Target02, Target03,
			Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12,
			Budget01, Budget02, Budget03,
			Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12,
			Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, 
			Projection10, Projection11, Projection12)
		SELECT DISTINCT 
			cv.EntityID, 
			cv.DepartmentID,
			config.AccountID,
			SUM(cv.TargetDollarsAdjusted01 * BudgetMixPercentage) AS Target01, 
			SUM(cv.TargetDollarsAdjusted02 * BudgetMixPercentage) AS Target02, 
			SUM(cv.TargetDollarsAdjusted03 * BudgetMixPercentage) AS Target03, 
			SUM(cv.TargetDollarsAdjusted04 * BudgetMixPercentage) AS Target04, 
			SUM(cv.TargetDollarsAdjusted05 * BudgetMixPercentage) AS Target05, 
			SUM(cv.TargetDollarsAdjusted06 * BudgetMixPercentage) AS Target06, 
			SUM(cv.TargetDollarsAdjusted07 * BudgetMixPercentage) AS Target07, 
			SUM(cv.TargetDollarsAdjusted08 * BudgetMixPercentage) AS Target08, 
			SUM(cv.TargetDollarsAdjusted09 * BudgetMixPercentage) AS Target09, 
			SUM(cv.TargetDollarsAdjusted10 * BudgetMixPercentage) AS Target10, 
			SUM(cv.TargetDollarsAdjusted11 * BudgetMixPercentage) AS Target11, 
			SUM(cv.TargetDollarsAdjusted12 * BudgetMixPercentage) AS Target12,
			SUM(cv.BudgetDollarsAdjusted01 * BudgetMixPercentage) AS Budget01, 
			SUM(cv.BudgetDollarsAdjusted02 * BudgetMixPercentage) AS Budget02, 
			SUM(cv.BudgetDollarsAdjusted03 * BudgetMixPercentage) AS Budget03, 
			SUM(cv.BudgetDollarsAdjusted04 * BudgetMixPercentage) AS Budget04, 
			SUM(cv.BudgetDollarsAdjusted05 * BudgetMixPercentage) AS Budget05, 
			SUM(cv.BudgetDollarsAdjusted06 * BudgetMixPercentage) AS Budget06, 
			SUM(cv.BudgetDollarsAdjusted07 * BudgetMixPercentage) AS Budget07, 
			SUM(cv.BudgetDollarsAdjusted08 * BudgetMixPercentage) AS Budget08, 
			SUM(cv.BudgetDollarsAdjusted09 * BudgetMixPercentage) AS Budget09, 
			SUM(cv.BudgetDollarsAdjusted10 * BudgetMixPercentage) AS Budget10, 
			SUM(cv.BudgetDollarsAdjusted11 * BudgetMixPercentage) AS Budget11, 
			SUM(cv.BudgetDollarsAdjusted12 * BudgetMixPercentage) AS Budget12,
			SUM(cv.ProjectionDollarsAdjusted01 * ProjectionMixPercentage) AS Projection01, 
			SUM(cv.ProjectionDollarsAdjusted02 * ProjectionMixPercentage) AS Projection02, 
			SUM(cv.ProjectionDollarsAdjusted03 * ProjectionMixPercentage) AS Projection03, 
			SUM(cv.ProjectionDollarsAdjusted04 * ProjectionMixPercentage) AS Projection04, 
			SUM(cv.ProjectionDollarsAdjusted05 * ProjectionMixPercentage) AS Projection05, 
			SUM(cv.ProjectionDollarsAdjusted06 * ProjectionMixPercentage) AS Projection06, 
			SUM(cv.ProjectionDollarsAdjusted07 * ProjectionMixPercentage) AS Projection07, 
			SUM(cv.ProjectionDollarsAdjusted08 * ProjectionMixPercentage) AS Projection08, 
			SUM(cv.ProjectionDollarsAdjusted09 * ProjectionMixPercentage) AS Projection09, 
			SUM(cv.ProjectionDollarsAdjusted10 * ProjectionMixPercentage) AS Projection10, 
			SUM(cv.ProjectionDollarsAdjusted11 * ProjectionMixPercentage) AS Projection11, 
			SUM(cv.ProjectionDollarsAdjusted12 * ProjectionMixPercentage) AS Projection12
		FROM fp.ChargeVolume cv 
			INNER JOIN #mixTable mix on 
					mix.PatientClassID = cv.PatientClassID
				AND mix.EntityID = cv.ServiceEntityID
				AND mix.EntityGroupConfigID = cv.EntityGroupConfigID'
				+ CASE WHEN @IsServiceLineEnabled=0 THEN '' ELSE '
				AND mix.ServiceLineID = cv.ServiceLineID' END
				+ CASE WHEN @IsAdditionalDimensionalityEnabled=0 THEN '' ELSE '
				AND mix.AgeCohortID = cv.AgeCohortID
				AND mix.MedicalSurgicalID = cv.MedicalSurgicalID
				AND mix.MSDRGID = cv.MSDRGID
				AND mix.CPTID = cv.PrimaryCPTID
				AND mix.ProviderID = cv.ServiceProviderID
				' END + '
			INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON
					dim.BudgetConfigID = cv.BudgetConfigID
				AND dim.EntityGroupConfigID = cv.EntityGroupConfigID
				AND dim.DepartmentID = cv.DepartmentID
				AND dim.ChargeCodeID = cv.ChargeCodeID
				AND dim.PatientClassID = cv.PatientClassID
				AND dim.PatientClassID = mix.PatientClassID
                AND dim.PayorGroupID = mix.PayorGroupID
			INNER JOIN #FilteredCrosswalkConfiguration config ON
					cv.DepartmentID = config.DepartmentID 
				AND cv.ChargeCodeID = config.ChargeCodeID
				AND mix.PatientClassID = config.PatientClassID
				AND mix.PayorGroupID = config.PayorGroupID
		WHERE cv.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(MAX)) + '
			AND cv.EntityID = ' + CAST(@EntityID AS VARCHAR(MAX)) + '
		GROUP BY cv.EntityID, 
			cv.DepartmentID, 
			AccountID
		OPTION (RECOMPILE);'

		EXEC (@SQL2); --esc-44799
	END
	ELSE
	BEGIN
		CREATE TABLE #FilterByDepartment (DepartmentID int)
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

		INSERT INTO #FilteredCrosswalkConfiguration
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			config.DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID, 
			AccountID
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) 
			INNER JOIN #FilterByDepartment dept ON config.DepartmentID = dept.DepartmentID
			INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not
			AND IsRecordDeleted = 0

		INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID)
		SELECT DISTINCT
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			AccountID
		FROM #FilteredCrosswalkConfiguration fcc

		-- Filter to the distinct charge records so we don't duplicate charge records with the join.
		INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID
		FROM #FilteredCrosswalkConfiguration

		SET @SQL2 = '
		INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, Target01, Target02, Target03,
			Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12,
			Budget01, Budget02, Budget03,
			Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12,
			Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, 
			Projection10, Projection11, Projection12)
		SELECT DISTINCT 
			cv.EntityID, 
			cv.DepartmentID,
			config.AccountID,
			SUM(cv.TargetDollarsAdjusted01 * BudgetMixPercentage) AS Target01, 
			SUM(cv.TargetDollarsAdjusted02 * BudgetMixPercentage) AS Target02, 
			SUM(cv.TargetDollarsAdjusted03 * BudgetMixPercentage) AS Target03, 
			SUM(cv.TargetDollarsAdjusted04 * BudgetMixPercentage) AS Target04, 
			SUM(cv.TargetDollarsAdjusted05 * BudgetMixPercentage) AS Target05, 
			SUM(cv.TargetDollarsAdjusted06 * BudgetMixPercentage) AS Target06, 
			SUM(cv.TargetDollarsAdjusted07 * BudgetMixPercentage) AS Target07, 
			SUM(cv.TargetDollarsAdjusted08 * BudgetMixPercentage) AS Target08, 
			SUM(cv.TargetDollarsAdjusted09 * BudgetMixPercentage) AS Target09, 
			SUM(cv.TargetDollarsAdjusted10 * BudgetMixPercentage) AS Target10, 
			SUM(cv.TargetDollarsAdjusted11 * BudgetMixPercentage) AS Target11, 
			SUM(cv.TargetDollarsAdjusted12 * BudgetMixPercentage) AS Target12,
			SUM(cv.BudgetDollarsAdjusted01 * BudgetMixPercentage) AS Budget01, 
			SUM(cv.BudgetDollarsAdjusted02 * BudgetMixPercentage) AS Budget02, 
			SUM(cv.BudgetDollarsAdjusted03 * BudgetMixPercentage) AS Budget03, 
			SUM(cv.BudgetDollarsAdjusted04 * BudgetMixPercentage) AS Budget04, 
			SUM(cv.BudgetDollarsAdjusted05 * BudgetMixPercentage) AS Budget05, 
			SUM(cv.BudgetDollarsAdjusted06 * BudgetMixPercentage) AS Budget06, 
			SUM(cv.BudgetDollarsAdjusted07 * BudgetMixPercentage) AS Budget07, 
			SUM(cv.BudgetDollarsAdjusted08 * BudgetMixPercentage) AS Budget08, 
			SUM(cv.BudgetDollarsAdjusted09 * BudgetMixPercentage) AS Budget09, 
			SUM(cv.BudgetDollarsAdjusted10 * BudgetMixPercentage) AS Budget10, 
			SUM(cv.BudgetDollarsAdjusted11 * BudgetMixPercentage) AS Budget11, 
			SUM(cv.BudgetDollarsAdjusted12 * BudgetMixPercentage) AS Budget12,
			SUM(cv.ProjectionDollarsAdjusted01 * ProjectionMixPercentage) AS Projection01, 
			SUM(cv.ProjectionDollarsAdjusted02 * ProjectionMixPercentage) AS Projection02, 
			SUM(cv.ProjectionDollarsAdjusted03 * ProjectionMixPercentage) AS Projection03, 
			SUM(cv.ProjectionDollarsAdjusted04 * ProjectionMixPercentage) AS Projection04, 
			SUM(cv.ProjectionDollarsAdjusted05 * ProjectionMixPercentage) AS Projection05, 
			SUM(cv.ProjectionDollarsAdjusted06 * ProjectionMixPercentage) AS Projection06, 
			SUM(cv.ProjectionDollarsAdjusted07 * ProjectionMixPercentage) AS Projection07, 
			SUM(cv.ProjectionDollarsAdjusted08 * ProjectionMixPercentage) AS Projection08, 
			SUM(cv.ProjectionDollarsAdjusted09 * ProjectionMixPercentage) AS Projection09, 
			SUM(cv.ProjectionDollarsAdjusted10 * ProjectionMixPercentage) AS Projection10, 
			SUM(cv.ProjectionDollarsAdjusted11 * ProjectionMixPercentage) AS Projection11, 
			SUM(cv.ProjectionDollarsAdjusted12 * ProjectionMixPercentage) AS Projection12
		FROM fp.ChargeVolume cv 
			INNER JOIN #mixTable mix on 
					mix.PatientClassID = cv.PatientClassID
				AND mix.EntityID = cv.ServiceEntityID
				AND mix.EntityGroupConfigID = cv.EntityGroupConfigID'
				+ CASE WHEN @IsServiceLineEnabled=0 THEN '' ELSE '
				AND mix.ServiceLineID = cv.ServiceLineID' END
				+ CASE WHEN @IsAdditionalDimensionalityEnabled=0 THEN '' ELSE '
				AND mix.AgeCohortID = cv.AgeCohortID
				AND mix.MedicalSurgicalID = cv.MedicalSurgicalID
				AND mix.MSDRGID = cv.MSDRGID
				AND mix.CPTID = cv.PrimaryCPTID
				AND mix.ProviderID = cv.ServiceProviderID
				' END + '
			INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON
					dim.BudgetConfigID = cv.BudgetConfigID
				AND dim.EntityGroupConfigID = cv.EntityGroupConfigID
				AND dim.DepartmentID = cv.DepartmentID
				AND dim.ChargeCodeID = cv.ChargeCodeID
				AND dim.PatientClassID = cv.PatientClassID
				AND dim.PatientClassID = mix.PatientClassID
                AND dim.PayorGroupID = mix.PayorGroupID
			INNER JOIN #FilteredCrosswalkConfiguration config ON
					cv.DepartmentID = config.DepartmentID 
				AND cv.ChargeCodeID = config.ChargeCodeID
				AND mix.PatientClassID = config.PatientClassID
				AND mix.PayorGroupID = config.PayorGroupID
		WHERE cv.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(MAX)) + '
			AND cv.EntityID = ' + CAST(@EntityID AS VARCHAR(MAX)) + '
		GROUP BY cv.EntityID, 
			cv.DepartmentID, 
			AccountID
		OPTION (RECOMPILE);'

		EXEC (@SQL2); --esc-44799
	END

	IF (@IsDebug = 0) 
	BEGIN
        IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
        IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount
 	    IF OBJECT_ID('tempdb..#RecordsToCrosswalk') IS NOT NULL DROP TABLE #RecordsToCrosswalk
		
		UPDATE gl
		SET 
			TargetAdjusted01 = xwalk.Target01,
			TargetAdjusted02 = xwalk.Target02,
			TargetAdjusted03 = xwalk.Target03,
			TargetAdjusted04 = xwalk.Target04,
			TargetAdjusted05 = xwalk.Target05,
			TargetAdjusted06 = xwalk.Target06,
			TargetAdjusted07 = xwalk.Target07,
			TargetAdjusted08 = xwalk.Target08,
			TargetAdjusted09 = xwalk.Target09,
			TargetAdjusted10 = xwalk.Target10,
			TargetAdjusted11 = xwalk.Target11,
			TargetAdjusted12 = xwalk.Target12,
			TargetLockFlag = 1,
			TargetLockType = 3,
			BudgetAdjusted01 = xwalk.Budget01,
			BudgetAdjusted02 = xwalk.Budget02,
			BudgetAdjusted03 = xwalk.Budget03,
			BudgetAdjusted04 = xwalk.Budget04,
			BudgetAdjusted05 = xwalk.Budget05,
			BudgetAdjusted06 = xwalk.Budget06,
			BudgetAdjusted07 = xwalk.Budget07,
			BudgetAdjusted08 = xwalk.Budget08,
			BudgetAdjusted09 = xwalk.Budget09,
			BudgetAdjusted10 = xwalk.Budget10,
			BudgetAdjusted11 = xwalk.Budget11,
			BudgetAdjusted12 = xwalk.Budget12,
			BudgetLockFlag = 1,
			BudgetLockType = 3
	FROM fp.GeneralLedger gl
		INNER JOIN #RolledUpValues xwalk ON 
				gl.DepartmentID = xwalk.DepartmentID
			AND gl.AccountID = xwalk.AccountID
	WHERE gl.VariabilityID = 2 
		AND gl.EntityGroupConfigID = @EntityGroupConfigID
		AND (
				   TargetAdjusted01 != xwalk.Target01
				OR TargetAdjusted02 != xwalk.Target02
				OR TargetAdjusted03 != xwalk.Target03
				OR TargetAdjusted04 != xwalk.Target04
				OR TargetAdjusted05 != xwalk.Target05
				OR TargetAdjusted06 != xwalk.Target06
				OR TargetAdjusted07 != xwalk.Target07
				OR TargetAdjusted08 != xwalk.Target08
				OR TargetAdjusted09 != xwalk.Target09
				OR TargetAdjusted10 != xwalk.Target10
				OR TargetAdjusted11 != xwalk.Target11
				OR TargetAdjusted12 != xwalk.Target12
				OR TargetLockFlag != 1
				OR TargetLockType != 3
				OR BudgetAdjusted01 != xwalk.Budget01
				OR BudgetAdjusted02 != xwalk.Budget02
				OR BudgetAdjusted03 != xwalk.Budget03
				OR BudgetAdjusted04 != xwalk.Budget04
				OR BudgetAdjusted05 != xwalk.Budget05
				OR BudgetAdjusted06 != xwalk.Budget06
				OR BudgetAdjusted07 != xwalk.Budget07
				OR BudgetAdjusted08 != xwalk.Budget08
				OR BudgetAdjusted09 != xwalk.Budget09
				OR BudgetAdjusted10 != xwalk.Budget10
				OR BudgetAdjusted11 != xwalk.Budget11
				OR BudgetAdjusted12 != xwalk.Budget12
				OR BudgetLockFlag != 1
				OR BudgetLockType != 3
			)

		DECLARE @i int = @MonthsLoaded + 1
		DECLARE @MonthsLoadedString CHAR(10)
		SELECT @MonthsLoadedString = CAST(@i as CHAR(2));

		DECLARE @sql varchar(max) = 'UPDATE gl SET '

		WHILE (@i <= 12)
		BEGIN 
			SET @sql = @sql + 'gl.ProjectionAdjusted' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = xwalk.Projection' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + CASE WHEN @i < 12 THEN ',' ELSE '' END
			SET @i = @i + 1
		END

		SET @sql = @sql + '
			, ProjectionLockFlag = 1
			, ProjectionLockType = 3
		FROM fp.GeneralLedger gl
			INNER JOIN #RolledUpValues xwalk ON 
				gl.DepartmentID = xwalk.DepartmentID
			AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 2
			AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + '
			AND (
				   (gl.ProjectionAdjusted01 != xwalk.Projection01 AND ' + @MonthsLoadedString + ' <= 1 )
				OR (gl.ProjectionAdjusted02 != xwalk.Projection02 AND ' + @MonthsLoadedString + ' <= 2 )   
				OR (gl.ProjectionAdjusted03 != xwalk.Projection03 AND ' + @MonthsLoadedString + ' <= 3 )   
				OR (gl.ProjectionAdjusted04 != xwalk.Projection04 AND ' + @MonthsLoadedString + ' <= 4 )   
				OR (gl.ProjectionAdjusted05 != xwalk.Projection05 AND ' + @MonthsLoadedString + ' <= 5 )   
				OR (gl.ProjectionAdjusted06 != xwalk.Projection06 AND ' + @MonthsLoadedString + ' <= 6 )   
				OR (gl.ProjectionAdjusted07 != xwalk.Projection07 AND ' + @MonthsLoadedString + ' <= 7 )   
				OR (gl.ProjectionAdjusted08 != xwalk.Projection08 AND ' + @MonthsLoadedString + ' <= 8 )   
				OR (gl.ProjectionAdjusted09 != xwalk.Projection09 AND ' + @MonthsLoadedString + ' <= 9 )   
				OR (gl.ProjectionAdjusted10 != xwalk.Projection10 AND ' + @MonthsLoadedString + ' <= 10 )   
				OR (gl.ProjectionAdjusted11 != xwalk.Projection11 AND ' + @MonthsLoadedString + ' <= 11 )   
				OR (gl.ProjectionAdjusted12 != xwalk.Projection12 AND ' + @MonthsLoadedString + ' <= 12 )   
				OR ProjectionLockFlag != 1
				OR ProjectionLockType != 3
			)
		'

		EXEC (@sql);

		-- We 0 out any fixed portion for these crosswalked value
		UPDATE gl
			SET  
				TargetAdjusted01 = 0,
				TargetAdjusted02 = 0,
				TargetAdjusted03 = 0,
				TargetAdjusted04 = 0,
				TargetAdjusted05 = 0,
				TargetAdjusted06 = 0,
				TargetAdjusted07 = 0,
				TargetAdjusted08 = 0,
				TargetAdjusted09 = 0,
				TargetAdjusted10 = 0,
				TargetAdjusted11 = 0,
				TargetAdjusted12 = 0,
				TargetLockFlag = 1,
				TargetLockType = 3,
				BudgetAdjusted01 = 0,
				BudgetAdjusted02 = 0,
				BudgetAdjusted03 = 0,
				BudgetAdjusted04 = 0,
				BudgetAdjusted05 = 0,
				BudgetAdjusted06 = 0,
				BudgetAdjusted07 = 0,
				BudgetAdjusted08 = 0,
				BudgetAdjusted09 = 0,
				BudgetAdjusted10 = 0,
				BudgetAdjusted11 = 0,
				BudgetAdjusted12 = 0,
				BudgetLockFlag = 1,
				BudgetLockType = 3
		FROM fp.GeneralLedger gl
			INNER JOIN #RolledUpValues xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 1 
			AND gl.EntityGroupConfigID = @EntityGroupConfigID
			AND (
					   TargetAdjusted01 != 0
					OR TargetAdjusted02 != 0
					OR TargetAdjusted03 != 0
					OR TargetAdjusted04 != 0
					OR TargetAdjusted05 != 0
					OR TargetAdjusted06 != 0
					OR TargetAdjusted07 != 0
					OR TargetAdjusted08 != 0
					OR TargetAdjusted09 != 0
					OR TargetAdjusted10 != 0
					OR TargetAdjusted11 != 0
					OR TargetAdjusted12 != 0
					OR TargetLockFlag != 1
					OR TargetLockType != 3
					OR BudgetAdjusted01 != 0
					OR BudgetAdjusted02 != 0
					OR BudgetAdjusted03 != 0
					OR BudgetAdjusted04 != 0
					OR BudgetAdjusted05 != 0
					OR BudgetAdjusted06 != 0
					OR BudgetAdjusted07 != 0
					OR BudgetAdjusted08 != 0
					OR BudgetAdjusted09 != 0
					OR BudgetAdjusted10 != 0
					OR BudgetAdjusted11 != 0
					OR BudgetAdjusted12 != 0
					OR BudgetLockFlag != 1
					OR BudgetLockType != 3
				)

		SET @i = @MonthsLoaded + 1;
		SET @sql = 'UPDATE gl SET '

		WHILE (@i <= 12)
		BEGIN 
			SET @sql = @sql + 'gl.ProjectionAdjusted' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = 0' + CASE WHEN @i < 12 THEN ',' ELSE '' END
			SET @i = @i+1
		END

		SET @sql = @sql + '
			, ProjectionLockFlag = 1
			, ProjectionLockType = 3
		FROM fp.GeneralLedger gl
			INNER JOIN #RolledUpValues xwalk ON 
				gl.DepartmentID = xwalk.DepartmentID
			AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 1
			AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + '
			AND (
				   (gl.ProjectionAdjusted01 != 0 AND ' + @MonthsLoadedString + ' <= 1 )
				OR (gl.ProjectionAdjusted02 != 0 AND ' + @MonthsLoadedString + ' <= 2 )   
				OR (gl.ProjectionAdjusted03 != 0 AND ' + @MonthsLoadedString + ' <= 3 )   
				OR (gl.ProjectionAdjusted04 != 0 AND ' + @MonthsLoadedString + ' <= 4 )   
				OR (gl.ProjectionAdjusted05 != 0 AND ' + @MonthsLoadedString + ' <= 5 )   
				OR (gl.ProjectionAdjusted06 != 0 AND ' + @MonthsLoadedString + ' <= 6 )   
				OR (gl.ProjectionAdjusted07 != 0 AND ' + @MonthsLoadedString + ' <= 7 )   
				OR (gl.ProjectionAdjusted08 != 0 AND ' + @MonthsLoadedString + ' <= 8 )   
				OR (gl.ProjectionAdjusted09 != 0 AND ' + @MonthsLoadedString + ' <= 9 )   
				OR (gl.ProjectionAdjusted10 != 0 AND ' + @MonthsLoadedString + ' <= 10 )   
				OR (gl.ProjectionAdjusted11 != 0 AND ' + @MonthsLoadedString + ' <= 11 )   
				OR (gl.ProjectionAdjusted12 != 0 AND ' + @MonthsLoadedString + ' <= 12 )   
				OR ProjectionLockFlag != 1
				OR ProjectionLockType != 3
			)
		'

		EXEC (@sql);

		IF (@IsAdditionalDimensionalityEnabled = 1)
		BEGIN
			-- Update records that do not have a corresponding mix. These are records with a configuration record, but not a corresponding match between Charges and the Encounter mix
			-- This can be for a few reasons, but one main reason is you have a config that does not directly map between the data (IE: It contains data in encounters and charges, however
			-- the specified Payor Group does not exist)
			UPDATE gl
			SET  
					TargetAdjusted01 = 0, TargetAdjusted02 = 0, TargetAdjusted03 = 0, TargetAdjusted04 = 0,	TargetAdjusted05 = 0, TargetAdjusted06 = 0,
					TargetAdjusted07 = 0, TargetAdjusted08 = 0, TargetAdjusted09 = 0, TargetAdjusted10 = 0, TargetAdjusted11 = 0, TargetAdjusted12 = 0,
					BudgetAdjusted01 = 0, BudgetAdjusted02 = 0, BudgetAdjusted03 = 0, BudgetAdjusted04 = 0, BudgetAdjusted05 = 0, BudgetAdjusted06 = 0,
					BudgetAdjusted07 = 0, BudgetAdjusted08 = 0,	BudgetAdjusted09 = 0, BudgetAdjusted10 = 0,	BudgetAdjusted11 = 0, BudgetAdjusted12 = 0,
					TargetLockFlag = 1,
					TargetLockType = 3,
					BudgetLockFlag = 1,
					BudgetLockType = 3
			FROM fp.GeneralLedger gl
				INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID
					AND gl.EntityGroupConfigID = config.EntityGroupConfigID
					AND gl.DepartmentID = config.DepartmentID
					AND gl.AccountID = config.AccountID
				LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID
					AND roll.DepartmentID = gl.DepartmentID
					AND roll.AccountID = gl.AccountID
			WHERE 1 = 1
				AND gl.EntityGroupConfigID = @EntityGroupConfigID
				AND gl.FlexingTypeID = 4 -- Charge to GL Crosswalk
				AND roll.AccountID IS NULL -- We only want records that are configured, but falled out of the value calc above
				AND (
						   TargetAdjusted01 != 0 OR TargetAdjusted02 != 0 OR TargetAdjusted03 != 0 OR TargetAdjusted04 != 0	OR TargetAdjusted05 != 0 OR TargetAdjusted06 != 0
						OR TargetAdjusted07 != 0 OR TargetAdjusted08 != 0 OR TargetAdjusted09 != 0 OR TargetAdjusted10 != 0 OR TargetAdjusted11 != 0 OR TargetAdjusted12 != 0
						OR BudgetAdjusted01 != 0 OR BudgetAdjusted02 != 0 OR BudgetAdjusted03 != 0 OR BudgetAdjusted04 != 0 OR BudgetAdjusted05 != 0 OR BudgetAdjusted06 != 0
						OR BudgetAdjusted07 != 0 OR BudgetAdjusted08 != 0 OR BudgetAdjusted09 != 0 OR BudgetAdjusted10 != 0	OR BudgetAdjusted11 != 0 OR BudgetAdjusted12 != 0
						OR TargetLockFlag != 1
						OR TargetLockType != 3
						OR BudgetLockFlag != 1
						OR BudgetLockType != 3
					)

			SET @i = @MonthsLoaded + 1;
			SET @sql = 'UPDATE gl SET '

			WHILE (@i <= 12)
			BEGIN 
				SET @sql = @sql + 'gl.ProjectionAdjusted' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i as varchar(2)) + ' = 0' + CASE WHEN @i<12 THEN ',' ELSE '' END
				SET @i = @i+1
			END

			SET @sql = @sql + '
				, ProjectionLockFlag = 1
				, ProjectionLockType = 3
			FROM fp.GeneralLedger gl
				INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID
					AND gl.EntityGroupConfigID = config.EntityGroupConfigID
					AND gl.DepartmentID = config.DepartmentID
					AND gl.AccountID = config.AccountID
				LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID
					AND roll.DepartmentID = gl.DepartmentID
					AND roll.AccountID = gl.AccountID
			WHERE 1 = 1
				AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + '
				AND gl.FlexingTypeID = 4 -- Charge to GL Crosswalk
				AND roll.AccountID IS NULL -- We only want records that are configured, but falled out of the value calc above
				AND (
					   (gl.ProjectionAdjusted01 != 0 AND ' + @MonthsLoadedString + ' <= 1 )
					OR (gl.ProjectionAdjusted02 != 0 AND ' + @MonthsLoadedString + ' <= 2 )   
					OR (gl.ProjectionAdjusted03 != 0 AND ' + @MonthsLoadedString + ' <= 3 )   
					OR (gl.ProjectionAdjusted04 != 0 AND ' + @MonthsLoadedString + ' <= 4 )   
					OR (gl.ProjectionAdjusted05 != 0 AND ' + @MonthsLoadedString + ' <= 5 )   
					OR (gl.ProjectionAdjusted06 != 0 AND ' + @MonthsLoadedString + ' <= 6 )   
					OR (gl.ProjectionAdjusted07 != 0 AND ' + @MonthsLoadedString + ' <= 7 )   
					OR (gl.ProjectionAdjusted08 != 0 AND ' + @MonthsLoadedString + ' <= 8 )   
					OR (gl.ProjectionAdjusted09 != 0 AND ' + @MonthsLoadedString + ' <= 9 )   
					OR (gl.ProjectionAdjusted10 != 0 AND ' + @MonthsLoadedString + ' <= 10 )   
					OR (gl.ProjectionAdjusted11 != 0 AND ' + @MonthsLoadedString + ' <= 11 )   
					OR (gl.ProjectionAdjusted12 != 0 AND ' + @MonthsLoadedString + ' <= 12 )   
					OR ProjectionLockFlag != 1
					OR ProjectionLockType != 3
				)
			'

			EXEC (@sql);
		END
	END ELSE BEGIN
		SELECT '@IsServiceLineEnabled', @IsServiceLineEnabled
		SELECT '@IsAdditionalDimensionalityEnabled', @IsAdditionalDimensionalityEnabled
		SELECT '#mixTable', * FROM #mixTable
		SELECT '#DistinctCrosswalkConfiguration_WithAccount', * FROM #DistinctCrosswalkConfiguration_WithAccount
		SELECT '#DistinctCrosswalkConfiguration_WithoutAccount', * FROM #DistinctCrosswalkConfiguration_WithoutAccount
		SELECT '#RolledUpValues', * FROM #RolledUpValues
	END		
 END;
GO


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

-- fp.procCrosswalkChargeToGeneralLedgerByPayorGroup_InitialValue
CREATE   PROCEDURE [fp].[procCrosswalkChargeToGeneralLedgerByPayorGroup_InitialValue]
	 @EntityGroupConfigID INT,
	 @MonthsLoaded INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @EntityID INT,
	 @IsDebug BIT = 0
WITH RECOMPILE
 AS
 	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  BLI            Description
	 ** 1 	 2021-09-21  MY  	 JAZZ-25836	    Initial
	 ** 2	 2021-11-18	 MY		 JAZZ-29482		Performance Tuning
	 ** 3	 2021-12-08	 MY		 JAZZ-30002		Add Batch Processing
	 ** 4    2023-04-06	 MD		 JAZZ-52587		Update to use new CV data structure
	 ** 5	 2023-04-19	 MY		 JAZZ-53575		Improve performance on charge to GL crosswalk
	 ** 6	 2023-06-15  NT      JAZZ-56471		Add update statistics on #filterByDepartment on DBA's recommendation to improve performance
	 ** 7	 2023-06-27  MY      JAZZ-56923		Adding Service Line into the SLE to Charge payor mix calc
	 ** 8 	 2023-08-04  BW  	 JAZZ-58151	    Update for new GL data structure
	 ** 9 	 2023-04-11  MY  	 JAZZ-70660	    Update to leverage additional dimensions in mix table
	 ** 10 	 2024-09-12  MY  	 JAZZ-70741	    Update Charge to General Ledger Crosswalk Performance Improvement
	 ** 11	 2024-09-16  MY		 JAZZ-70683		Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix
	 *************************************************************/
 BEGIN
 	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
    IF OBJECT_ID('tempdb..#FilteredCrosswalkConfiguration') IS NOT NULL DROP TABLE #FilteredCrosswalkConfiguration
    IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount
 	IF OBJECT_ID('tempdb..#RecordsWithMixes') IS NOT NULL DROP TABLE #RecordsWithMixes
 	IF OBJECT_ID('tempdb..#RolledUpValues') IS NOT NULL DROP TABLE #RolledUpValues
 	IF OBJECT_ID('tempdb..#mixTable') IS NOT NULL DROP TABLE #mixTable
 	IF OBJECT_ID('tempdb..#chargeVolumeEntities') IS NOT NULL DROP TABLE #chargeVolumeEntities

	-- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc
	DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value 
												FROM fp.viewBudgetConfigSetting setting
													INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID
													INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
													AND setting.Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0)

	
	-- JAZZ-70660: Adding Additional Dimensionality into the SLE to Charge payor mix calc
	DECLARE @IsAdditionalDimensionalityEnabled BIT = ISNULL((SELECT Value 
												FROM fp.viewBudgetConfigSetting setting
													INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID
													INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
													AND setting.Name = 'Enable Charge to General Ledger Crosswalk to Use Detailed Mix'), 0)

	-- JAZZ-70683: Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix
	DECLARE @IsProjectionMixEnabled BIT = ISNULL((SELECT Value 
												FROM fp.viewBudgetConfigSetting setting
													INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID
													INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
													AND setting.Name = 'Enable Initial Projection Mix for Encounter to Charge Payor Group Mix'), 0)

	-- This setting overrides the 'Enable ServiceLine level mix for Charge to GL Crosswalk' setting
	IF (@IsAdditionalDimensionalityEnabled = 1)
	BEGIN
		SET @IsServiceLineEnabled = 1;
	END

	CREATE TABLE #RolledUpValues(EntityID INT, DepartmentID INT, AccountID INT, 
		InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8), InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), 
		InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8), InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8),
		InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), 
		InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8), 
	)
	
	CREATE TABLE #mixTable (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT, 
		PatientClassID INT,
		ServiceLineID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		MSDRGID INT,
		CPTID INT,
		ProviderID INT,
		PayorID INT,
		PayorGroupID INT,
		InitialProjectionMixPercentage DECIMAL(19, 8),
		InitialBudgetMixPercentage DECIMAL(19, 8)		
	)
	
	CREATE TABLE #FilteredCrosswalkConfiguration
	(
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		DepartmentID INT,
		ChargeCodeID INT,
		PatientClassID INT,
		PayorGroupID INT,
		AccountID INT
	)	

	CREATE TABLE #DistinctCrosswalkConfiguration_WithoutAccount 
	(
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		DepartmentID INT,
		ChargeCodeID INT,
		PatientClassID INT,
		PayorGroupID INT
	)	

	CREATE TABLE #DistinctCrosswalkConfiguration_WithAccount 
	(
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		DepartmentID INT,
		AccountID INT
	)
	
	SELECT DISTINCT EntityID AS ChargeVolumeEntityID, ServiceEntityID AS ServiceLineEncounterEntityID
	INTO #chargeVolumeEntities
	FROM fp.ChargeVolume
	WHERE EntityGroupConfigID = @EntityGroupConfigID
		AND EntityID = @EntityID

	IF (@IsAdditionalDimensionalityEnabled = 1)
	BEGIN
		INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID,
			MSDRGID, CPTID, ProviderID,	PayorID, PayorGroupID, InitialProjectionMixPercentage, InitialBudgetMixPercentage)
		SELECT 
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID, 
			PatientClassID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			MSDRGID,
			CPTID,
			ProviderID,
			PayorID,
			PayorGroupID,
			CASE WHEN @IsProjectionMixEnabled = 1 THEN InitialProjectionMixPercentage ELSE InitialMixPercentage END,
			InitialMixPercentage	
		FROM fp.ServiceLineEncounterToChargePayorMix mix
			INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END ELSE BEGIN
		INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID,
			MSDRGID, CPTID, ProviderID,	PayorID, PayorGroupID, InitialProjectionMixPercentage,	InitialBudgetMixPercentage)
		SELECT 
			BudgetConfigID,
			EntityGroupConfigID,
			EntityID, 
			PatientClassID,
			CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE ServiceLineID END AS ServiceLineID,
			0 AS AgeCohortID,
			0 AS MedicalSurgicalID,
			0 AS MSDRGID,
			0 AS CPTID,
			0 AS ProviderID,
			0 AS PayorID,
			PayorGroupID,
			InitialProjectionMixPercentage,
			InitialBudgetMixPercentage	
		FROM fp.viewServiceLineEncounterPayorGroupMix_Pivoted mix
			INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	
	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 
	BEGIN		
		INSERT INTO #FilteredCrosswalkConfiguration
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			config.DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID, 
			AccountID
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) 
			INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not
			AND IsRecordDeleted = 0

		INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID)
		SELECT DISTINCT
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			AccountID
		FROM #FilteredCrosswalkConfiguration fcc

		-- Filter to the distinct charge records so we don't duplicate charge records with the join.
		INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID
		FROM #FilteredCrosswalkConfiguration

		INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, InitialBudget01, InitialBudget02, InitialBudget03,
			InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
			InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, 
			InitialProjection10, InitialProjection11, InitialProjection12)
		SELECT DISTINCT
			cv.EntityID, 
			cv.DepartmentID,
			config.AccountID,
			SUM(cv.InitialBudgetDollars01 * InitialBudgetMixPercentage) AS InitialBudget01, 
			SUM(cv.InitialBudgetDollars02 * InitialBudgetMixPercentage) AS InitialBudget02, 
			SUM(cv.InitialBudgetDollars03 * InitialBudgetMixPercentage) AS InitialBudget03, 
			SUM(cv.InitialBudgetDollars04 * InitialBudgetMixPercentage) AS InitialBudget04, 
			SUM(cv.InitialBudgetDollars05 * InitialBudgetMixPercentage) AS InitialBudget05, 
			SUM(cv.InitialBudgetDollars06 * InitialBudgetMixPercentage) AS InitialBudget06, 
			SUM(cv.InitialBudgetDollars07 * InitialBudgetMixPercentage) AS InitialBudget07, 
			SUM(cv.InitialBudgetDollars08 * InitialBudgetMixPercentage) AS InitialBudget08, 
			SUM(cv.InitialBudgetDollars09 * InitialBudgetMixPercentage) AS InitialBudget09, 
			SUM(cv.InitialBudgetDollars10 * InitialBudgetMixPercentage) AS InitialBudget10, 
			SUM(cv.InitialBudgetDollars11 * InitialBudgetMixPercentage) AS InitialBudget11, 
			SUM(cv.InitialBudgetDollars12 * InitialBudgetMixPercentage) AS InitialBudget12,
			SUM(cv.InitialProjectionDollars01 * InitialProjectionMixPercentage) AS InitialProjection01, 
			SUM(cv.InitialProjectionDollars02 * InitialProjectionMixPercentage) AS InitialProjection02, 
			SUM(cv.InitialProjectionDollars03 * InitialProjectionMixPercentage) AS InitialProjection03, 
			SUM(cv.InitialProjectionDollars04 * InitialProjectionMixPercentage) AS InitialProjection04, 
			SUM(cv.InitialProjectionDollars05 * InitialProjectionMixPercentage) AS InitialProjection05, 
			SUM(cv.InitialProjectionDollars06 * InitialProjectionMixPercentage) AS InitialProjection06, 
			SUM(cv.InitialProjectionDollars07 * InitialProjectionMixPercentage) AS InitialProjection07, 
			SUM(cv.InitialProjectionDollars08 * InitialProjectionMixPercentage) AS InitialProjection08, 
			SUM(cv.InitialProjectionDollars09 * InitialProjectionMixPercentage) AS InitialProjection09, 
			SUM(cv.InitialProjectionDollars10 * InitialProjectionMixPercentage) AS InitialProjection10, 
			SUM(cv.InitialProjectionDollars11 * InitialProjectionMixPercentage) AS InitialProjection11, 
			SUM(cv.InitialProjectionDollars12 * InitialProjectionMixPercentage) AS InitialProjection12
		FROM fp.ChargeVolume cv WITH (READUNCOMMITTED)
			INNER JOIN #mixTable mix WITH (READUNCOMMITTED) on 
					mix.PatientClassID = cv.PatientClassID
				AND mix.EntityID = cv.ServiceEntityID
				AND mix.EntityGroupConfigID = cv.EntityGroupConfigID
				AND (@IsServiceLineEnabled = 0 OR mix.ServiceLineID = cv.ServiceLineID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.AgeCohortID = cv.AgeCohortID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MedicalSurgicalID = cv.MedicalSurgicalID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MSDRGID = cv.MSDRGID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.CPTID = cv.PrimaryCPTID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.ProviderID = cv.ServiceProviderID)
			INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON
					dim.BudgetConfigID = cv.BudgetConfigID
				AND dim.EntityGroupConfigID = cv.EntityGroupConfigID
				AND dim.DepartmentID = cv.DepartmentID
				AND dim.ChargeCodeID = cv.ChargeCodeID
				AND dim.PatientClassID = cv.PatientClassID
				AND dim.PatientClassID = mix.PatientClassID
                AND dim.PayorGroupID = mix.PayorGroupID
			INNER JOIN #FilteredCrosswalkConfiguration config WITH (READUNCOMMITTED) ON
					cv.DepartmentID = config.DepartmentID 
				AND cv.ChargeCodeID = config.ChargeCodeID
				AND mix.PatientClassID = config.PatientClassID
				AND mix.PayorGroupID = config.PayorGroupID
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID 
			AND cv.EntityID = @EntityID
		GROUP BY cv.EntityID, 
			cv.DepartmentID, 
			AccountID
		OPTION (RECOMPILE)

	END
	ELSE
	BEGIN
		CREATE TABLE #FilterByDepartment (DepartmentID int)
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
		INSERT INTO #FilteredCrosswalkConfiguration
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			config.DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID, 
			AccountID
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) 
			INNER JOIN #FilterByDepartment dept ON config.DepartmentID = dept.DepartmentID
			INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not
			AND IsRecordDeleted = 0

		INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID)
		SELECT DISTINCT
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			AccountID
		FROM #FilteredCrosswalkConfiguration fcc

		-- Filter to the distinct charge records so we don't duplicate charge records with the join.
		INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount
			(BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID)
		SELECT DISTINCT 
			BudgetConfigID,
			EntityGroupConfigID,
			DepartmentID,
			ChargeCodeID,
			PatientClassID,
			PayorGroupID
		FROM #FilteredCrosswalkConfiguration
		
		INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, InitialBudget01, InitialBudget02, InitialBudget03,
			InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
			InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, 
			InitialProjection10, InitialProjection11, InitialProjection12)
		SELECT DISTINCT
			cv.EntityID, 
			cv.DepartmentID,
			config.AccountID,
			SUM(cv.InitialBudgetDollars01 * InitialBudgetMixPercentage) AS InitialBudget01, 
			SUM(cv.InitialBudgetDollars02 * InitialBudgetMixPercentage) AS InitialBudget02, 
			SUM(cv.InitialBudgetDollars03 * InitialBudgetMixPercentage) AS InitialBudget03, 
			SUM(cv.InitialBudgetDollars04 * InitialBudgetMixPercentage) AS InitialBudget04, 
			SUM(cv.InitialBudgetDollars05 * InitialBudgetMixPercentage) AS InitialBudget05, 
			SUM(cv.InitialBudgetDollars06 * InitialBudgetMixPercentage) AS InitialBudget06, 
			SUM(cv.InitialBudgetDollars07 * InitialBudgetMixPercentage) AS InitialBudget07, 
			SUM(cv.InitialBudgetDollars08 * InitialBudgetMixPercentage) AS InitialBudget08, 
			SUM(cv.InitialBudgetDollars09 * InitialBudgetMixPercentage) AS InitialBudget09, 
			SUM(cv.InitialBudgetDollars10 * InitialBudgetMixPercentage) AS InitialBudget10, 
			SUM(cv.InitialBudgetDollars11 * InitialBudgetMixPercentage) AS InitialBudget11, 
			SUM(cv.InitialBudgetDollars12 * InitialBudgetMixPercentage) AS InitialBudget12,
			SUM(cv.InitialProjectionDollars01 * InitialProjectionMixPercentage) AS InitialProjection01, 
			SUM(cv.InitialProjectionDollars02 * InitialProjectionMixPercentage) AS InitialProjection02, 
			SUM(cv.InitialProjectionDollars03 * InitialProjectionMixPercentage) AS InitialProjection03, 
			SUM(cv.InitialProjectionDollars04 * InitialProjectionMixPercentage) AS InitialProjection04, 
			SUM(cv.InitialProjectionDollars05 * InitialProjectionMixPercentage) AS InitialProjection05, 
			SUM(cv.InitialProjectionDollars06 * InitialProjectionMixPercentage) AS InitialProjection06, 
			SUM(cv.InitialProjectionDollars07 * InitialProjectionMixPercentage) AS InitialProjection07, 
			SUM(cv.InitialProjectionDollars08 * InitialProjectionMixPercentage) AS InitialProjection08, 
			SUM(cv.InitialProjectionDollars09 * InitialProjectionMixPercentage) AS InitialProjection09, 
			SUM(cv.InitialProjectionDollars10 * InitialProjectionMixPercentage) AS InitialProjection10, 
			SUM(cv.InitialProjectionDollars11 * InitialProjectionMixPercentage) AS InitialProjection11, 
			SUM(cv.InitialProjectionDollars12 * InitialProjectionMixPercentage) AS InitialProjection12
		FROM fp.ChargeVolume cv WITH (READUNCOMMITTED)
			INNER JOIN #mixTable mix WITH (READUNCOMMITTED) on 
					mix.PatientClassID = cv.PatientClassID
				AND mix.EntityID = cv.ServiceEntityID
				AND mix.EntityGroupConfigID = cv.EntityGroupConfigID    
				AND (@IsServiceLineEnabled = 0 OR mix.ServiceLineID = cv.ServiceLineID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.AgeCohortID = cv.AgeCohortID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MedicalSurgicalID = cv.MedicalSurgicalID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MSDRGID = cv.MSDRGID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.CPTID = cv.PrimaryCPTID)
				AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.ProviderID = cv.ServiceProviderID)        
			INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON
					dim.BudgetConfigID = cv.BudgetConfigID
				AND dim.EntityGroupConfigID = cv.EntityGroupConfigID
				AND dim.DepartmentID = cv.DepartmentID
				AND dim.ChargeCodeID = cv.ChargeCodeID
				AND dim.PatientClassID = cv.PatientClassID
				AND dim.PatientClassID = mix.PatientClassID
                AND dim.PayorGroupID = mix.PayorGroupID
			INNER JOIN #FilteredCrosswalkConfiguration config WITH (READUNCOMMITTED) ON
					cv.DepartmentID = config.DepartmentID 
				AND cv.ChargeCodeID = config.ChargeCodeID
				AND mix.PatientClassID = config.PatientClassID
				AND mix.PayorGroupID = config.PayorGroupID
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID 
			AND cv.EntityID = @EntityID
		GROUP BY cv.EntityID, 
			cv.DepartmentID, 
			AccountID
		OPTION (RECOMPILE)

	END       
	
	IF (@IsDebug = 0) 
	BEGIN
        IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
        IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount

		UPDATE gl
			SET 
				InitialBudget01 = xwalk.InitialBudget01,
				InitialBudget02 = xwalk.InitialBudget02,
				InitialBudget03 = xwalk.InitialBudget03,
				InitialBudget04 = xwalk.InitialBudget04,
				InitialBudget05 = xwalk.InitialBudget05,
				InitialBudget06 = xwalk.InitialBudget06,
				InitialBudget07 = xwalk.InitialBudget07,
				InitialBudget08 = xwalk.InitialBudget08,
				InitialBudget09 = xwalk.InitialBudget09,
				InitialBudget10 = xwalk.InitialBudget10,
				InitialBudget11 = xwalk.InitialBudget11,
				InitialBudget12 = xwalk.InitialBudget12
		FROM fp.GeneralLedger gl
			INNER JOIN #RolledUpValues xwalk ON 
					gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 2 
			AND gl.EntityGroupConfigID = @EntityGroupConfigID
            AND (      gl.InitialBudget01 != xwalk.InitialBudget01
                    OR gl.InitialBudget02 != xwalk.InitialBudget02
                    OR gl.InitialBudget03 != xwalk.InitialBudget03
                    OR gl.InitialBudget04 != xwalk.InitialBudget04
                    OR gl.InitialBudget05 != xwalk.InitialBudget05
                    OR gl.InitialBudget06 != xwalk.InitialBudget06
                    OR gl.InitialBudget07 != xwalk.InitialBudget07
                    OR gl.InitialBudget08 != xwalk.InitialBudget08
                    OR gl.InitialBudget09 != xwalk.InitialBudget09
                    OR gl.InitialBudget10 != xwalk.InitialBudget10
                    OR gl.InitialBudget11 != xwalk.InitialBudget11
                    OR gl.InitialBudget12 != xwalk.InitialBudget12
			)

		DECLARE @i int = @MonthsLoaded + 1
		DECLARE @MonthsLoadedString CHAR(10)
		SELECT @MonthsLoadedString = CAST(@i as CHAR(2));

		DECLARE @sql varchar(max) = 'UPDATE gl SET '
		WHILE (@i <= 12)
		BEGIN 
			SET @sql = @sql + 'gl.InitialProjection' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+' = xwalk.InitialProjection' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+CASE WHEN @i<12 THEN ',' ELSE '' END
			SET @i = @i+1
		END

		SET @sql = @sql + '
		FROM fp.GeneralLedger gl
			INNER JOIN #RolledUpValues xwalk ON 
				gl.DepartmentID = xwalk.DepartmentID
			AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 2
			AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + '
			AND (
				   (gl.InitialProjection01 != xwalk.InitialProjection01 AND ' + @MonthsLoadedString + ' <= 1 )
				OR (gl.InitialProjection02 != xwalk.InitialProjection02 AND ' + @MonthsLoadedString + ' <= 2 )   
				OR (gl.InitialProjection03 != xwalk.InitialProjection03 AND ' + @MonthsLoadedString + ' <= 3 )   
				OR (gl.InitialProjection04 != xwalk.InitialProjection04 AND ' + @MonthsLoadedString + ' <= 4 )   
				OR (gl.InitialProjection05 != xwalk.InitialProjection05 AND ' + @MonthsLoadedString + ' <= 5 )   
				OR (gl.InitialProjection06 != xwalk.InitialProjection06 AND ' + @MonthsLoadedString + ' <= 6 )   
				OR (gl.InitialProjection07 != xwalk.InitialProjection07 AND ' + @MonthsLoadedString + ' <= 7 )   
				OR (gl.InitialProjection08 != xwalk.InitialProjection08 AND ' + @MonthsLoadedString + ' <= 8 )   
				OR (gl.InitialProjection09 != xwalk.InitialProjection09 AND ' + @MonthsLoadedString + ' <= 9 )   
				OR (gl.InitialProjection10 != xwalk.InitialProjection10 AND ' + @MonthsLoadedString + ' <= 10 )   
				OR (gl.InitialProjection11 != xwalk.InitialProjection11 AND ' + @MonthsLoadedString + ' <= 11 )   
				OR (gl.InitialProjection12 != xwalk.InitialProjection12 AND ' + @MonthsLoadedString + ' <= 12 )
			)
		'

		EXEC (@sql);

		SET @i = @MonthsLoaded + 1;
		SET @sql = 'UPDATE gl SET '
		WHILE (@i <= 12)
		BEGIN 
			SET @sql = @sql + 'gl.InitialProjection' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = 0' + CASE WHEN @i < 12 THEN ',' ELSE '' END
			SET @i = @i+1
		END

		SET @sql = @sql + '
			, ProjectionLockFlag = 1
			, ProjectionLockType = 3
		FROM fp.GeneralLedger gl
			INNER JOIN #RolledUpValues xwalk ON 
				gl.DepartmentID = xwalk.DepartmentID
			AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 1
			AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + '
			AND (
				   (gl.InitialProjection01 != 0 AND ' + @MonthsLoadedString + ' <= 1 )
				OR (gl.InitialProjection02 != 0 AND ' + @MonthsLoadedString + ' <= 2 )   
				OR (gl.InitialProjection03 != 0 AND ' + @MonthsLoadedString + ' <= 3 )   
				OR (gl.InitialProjection04 != 0 AND ' + @MonthsLoadedString + ' <= 4 )   
				OR (gl.InitialProjection05 != 0 AND ' + @MonthsLoadedString + ' <= 5 )   
				OR (gl.InitialProjection06 != 0 AND ' + @MonthsLoadedString + ' <= 6 )   
				OR (gl.InitialProjection07 != 0 AND ' + @MonthsLoadedString + ' <= 7 )   
				OR (gl.InitialProjection08 != 0 AND ' + @MonthsLoadedString + ' <= 8 )   
				OR (gl.InitialProjection09 != 0 AND ' + @MonthsLoadedString + ' <= 9 )   
				OR (gl.InitialProjection10 != 0 AND ' + @MonthsLoadedString + ' <= 10 )   
				OR (gl.InitialProjection11 != 0 AND ' + @MonthsLoadedString + ' <= 11 )   
				OR (gl.InitialProjection12 != 0 AND ' + @MonthsLoadedString + ' <= 12 )   
			)
		'

		EXEC (@sql);

		-- We 0 out any fixed portion for these crosswalked value
		UPDATE gl
			SET  
				InitialBudget01 = 0,
				InitialBudget02 = 0,
				InitialBudget03 = 0,
				InitialBudget04 = 0,
				InitialBudget05 = 0,
				InitialBudget06 = 0,
				InitialBudget07 = 0,
				InitialBudget08 = 0,
				InitialBudget09 = 0,
				InitialBudget10 = 0,
				InitialBudget11 = 0,
				InitialBudget12 = 0
		FROM fp.GeneralLedger gl
			INNER JOIN #RolledUpValues xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 1 
			AND gl.EntityGroupConfigID = @EntityGroupConfigID
			AND (      
					   gl.InitialBudget01 != 0
                    OR gl.InitialBudget02 != 0
                    OR gl.InitialBudget03 != 0
                    OR gl.InitialBudget04 != 0
                    OR gl.InitialBudget05 != 0
                    OR gl.InitialBudget06 != 0
                    OR gl.InitialBudget07 != 0
                    OR gl.InitialBudget08 != 0
                    OR gl.InitialBudget09 != 0
                    OR gl.InitialBudget10 != 0
                    OR gl.InitialBudget11 != 0
                    OR gl.InitialBudget12 != 0
			)

		IF (@IsAdditionalDimensionalityEnabled = 1)
		BEGIN
			-- Update records that do not have a corresponding mix. These are records with a configuration record, but not a corresponding match between Charges and the Encounter mix
			-- This can be for a few reasons, but one main reason is you have a config that does not directly map between the data (IE: It contains data in encounters and charges, however
			-- the specified Payor Group does not exist)
			UPDATE gl
			SET  
					InitialBudget01 = 0, InitialBudget02 = 0, InitialBudget03 = 0, InitialBudget04 = 0,	InitialBudget05 = 0, InitialBudget06 = 0,
					InitialBudget07 = 0, InitialBudget08 = 0, InitialBudget09 = 0, InitialBudget10 = 0, InitialBudget11 = 0, InitialBudget12 = 0
			FROM fp.GeneralLedger gl
				INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID
					AND gl.EntityGroupConfigID = config.EntityGroupConfigID
					AND gl.DepartmentID = config.DepartmentID
					AND gl.AccountID = config.AccountID
				LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID
					AND roll.DepartmentID = gl.DepartmentID
					AND roll.AccountID = gl.AccountID
			WHERE 1 = 1
				AND gl.EntityGroupConfigID = @EntityGroupConfigID
				AND gl.FlexingTypeID = 4 -- Charge to GL Crosswalk
				AND roll.AccountID IS NULL -- We only want records that are configured, but falled out of the value calc above
				AND (
						   gl.InitialBudget01 != 0 OR gl.InitialBudget02 != 0 OR gl.InitialBudget03 != 0 OR gl.InitialBudget04 != 0	OR gl.InitialBudget05 != 0 OR gl.InitialBudget06 != 0
						OR gl.InitialBudget07 != 0 OR gl.InitialBudget08 != 0 OR gl.InitialBudget09 != 0 OR gl.InitialBudget10 != 0 OR gl.InitialBudget11 != 0 OR gl.InitialBudget12 != 0
					)

			SET @i = @MonthsLoaded + 1;
			SET @sql = 'UPDATE gl SET '
			WHILE (@i <= 12)
			BEGIN 
				SET @sql = @sql + 'gl.InitialProjection' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = 0' + CASE WHEN @i < 12 THEN ',' ELSE '' END
				SET @i = @i+1
			END

			SET @sql = @sql + '
			FROM fp.GeneralLedger gl
				INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID
					AND gl.EntityGroupConfigID = config.EntityGroupConfigID
					AND gl.DepartmentID = config.DepartmentID
					AND gl.AccountID = config.AccountID
				LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID
					AND roll.DepartmentID = gl.DepartmentID
					AND roll.AccountID = gl.AccountID
			WHERE gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + '
				AND gl.FlexingTypeID = 4
				AND roll.AccountID IS NULL
				AND (
					   (gl.InitialProjection01 != 0 AND ' + @MonthsLoadedString + ' <= 1 )
					OR (gl.InitialProjection02 != 0 AND ' + @MonthsLoadedString + ' <= 2 )   
					OR (gl.InitialProjection03 != 0 AND ' + @MonthsLoadedString + ' <= 3 )   
					OR (gl.InitialProjection04 != 0 AND ' + @MonthsLoadedString + ' <= 4 )   
					OR (gl.InitialProjection05 != 0 AND ' + @MonthsLoadedString + ' <= 5 )   
					OR (gl.InitialProjection06 != 0 AND ' + @MonthsLoadedString + ' <= 6 )   
					OR (gl.InitialProjection07 != 0 AND ' + @MonthsLoadedString + ' <= 7 )   
					OR (gl.InitialProjection08 != 0 AND ' + @MonthsLoadedString + ' <= 8 )   
					OR (gl.InitialProjection09 != 0 AND ' + @MonthsLoadedString + ' <= 9 )   
					OR (gl.InitialProjection10 != 0 AND ' + @MonthsLoadedString + ' <= 10 )   
					OR (gl.InitialProjection11 != 0 AND ' + @MonthsLoadedString + ' <= 11 )   
					OR (gl.InitialProjection12 != 0 AND ' + @MonthsLoadedString + ' <= 12 )   
				)';
			
			EXEC (@sql)
		END
	END ELSE BEGIN
		SELECT '@IsServiceLineEnabled', @IsServiceLineEnabled
		SELECT '@IsAdditionalDimensionalityEnabled', @IsAdditionalDimensionalityEnabled
		SELECT '#mixTable', * FROM #mixTable
		SELECT '#DistinctCrosswalkConfiguration_WithAccount', * FROM #DistinctCrosswalkConfiguration_WithAccount
		SELECT '#DistinctCrosswalkConfiguration_WithoutAccount', * FROM #DistinctCrosswalkConfiguration_WithoutAccount
		SELECT '#RolledUpValues', * FROM #RolledUpValues
	END		

 END;
GO


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

-- fp.procCrosswalkChargeToGeneralLedger_InitialValue
CREATE   PROCEDURE [fp].[procCrosswalkChargeToGeneralLedger_InitialValue]
    @EntityGroupConfigID INT,
    @MonthsLoaded INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
    @IsDebug BIT = 0
 AS
 	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  BLI            Description
	 ** 1 	 2021-03-10  BK  	 JAZZ-16331	    Create proc
	 ** 2	 2022-08-04  NH      JAZZ-41156     FP ORM produced error
	 ** 3	 2023-04-06  MD      JAZZ-52587     Update for new charge volume data structure
	 ** 4 	 2023-08-04  BW  	 JAZZ-58151	    Update for new GL data structure
	 ** 5 	 2024-01-23  BW  	 JAZZ-65717	    OnePlan - performance tuning for [procCrosswalkChargeToGeneralLedger_InitialValue]
	 ** 6 	 2024-09-11  MY  	 JAZZ-75442	    GL Data is locked with locktype 3 with no crosswalk configured for chosen entity group
	 *************************************************************/
 BEGIN	
    IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
    IF OBJECT_ID('tempdb..#RecordsToCrosswalk') IS NOT NULL DROP TABLE #RecordsToCrosswalk

	CREATE TABLE #RecordsToCrosswalk(DepartmentID INT, AccountID INT, 
		InitialBudgetDollars01 DECIMAL(19,8), InitialBudgetDollars02 DECIMAL(19,8), InitialBudgetDollars03 DECIMAL(19,8), 
		InitialBudgetDollars04 DECIMAL(19,8), InitialBudgetDollars05 DECIMAL(19,8), InitialBudgetDollars06 DECIMAL(19,8), 
		InitialBudgetDollars07 DECIMAL(19,8), InitialBudgetDollars08 DECIMAL(19,8), InitialBudgetDollars09 DECIMAL(19,8), 
		InitialBudgetDollars10 DECIMAL(19,8), InitialBudgetDollars11 DECIMAL(19,8), InitialBudgetDollars12 DECIMAL(19,8),
		InitialProjectionDollars01 DECIMAL(19,8), InitialProjectionDollars02 DECIMAL(19,8), InitialProjectionDollars03 DECIMAL(19,8), 
		InitialProjectionDollars04 DECIMAL(19,8), InitialProjectionDollars05 DECIMAL(19,8), InitialProjectionDollars06 DECIMAL(19,8), 
		InitialProjectionDollars07 DECIMAL(19,8), InitialProjectionDollars08 DECIMAL(19,8), InitialProjectionDollars09 DECIMAL(19,8), 
		InitialProjectionDollars10 DECIMAL(19,8), InitialProjectionDollars11 DECIMAL(19,8), InitialProjectionDollars12 DECIMAL(19,8)
	)								 
					
	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 
	BEGIN
		
		INSERT INTO #RecordsToCrosswalk (DepartmentID, AccountID, 
			InitialBudgetDollars01, InitialBudgetDollars02, InitialBudgetDollars03, 
			InitialBudgetDollars04, InitialBudgetDollars05, InitialBudgetDollars06, 
			InitialBudgetDollars07, InitialBudgetDollars08, InitialBudgetDollars09, 
			InitialBudgetDollars10, InitialBudgetDollars11, InitialBudgetDollars12,
			InitialProjectionDollars01, InitialProjectionDollars02, InitialProjectionDollars03, 
			InitialProjectionDollars04, InitialProjectionDollars05, InitialProjectionDollars06, 
			InitialProjectionDollars07, InitialProjectionDollars08, InitialProjectionDollars09, 
			InitialProjectionDollars10, InitialProjectionDollars11, InitialProjectionDollars12
			)
		SELECT DISTINCT config.DepartmentID, config.AccountID,
			SUM(cv.InitialBudgetDollars01), SUM(cv.InitialBudgetDollars02), SUM(cv.InitialBudgetDollars03), 
			SUM(cv.InitialBudgetDollars04), SUM(cv.InitialBudgetDollars05), SUM(cv.InitialBudgetDollars06), 
			SUM(cv.InitialBudgetDollars07), SUM(cv.InitialBudgetDollars08), SUM(cv.InitialBudgetDollars09), 
			SUM(cv.InitialBudgetDollars10), SUM(cv.InitialBudgetDollars11), SUM(cv.InitialBudgetDollars12),
			SUM(cv.InitialProjectionDollars01), SUM(cv.InitialProjectionDollars02), SUM(cv.InitialProjectionDollars03), 
			SUM(cv.InitialProjectionDollars04), SUM(cv.InitialProjectionDollars05), SUM(cv.InitialProjectionDollars06), 
			SUM(cv.InitialProjectionDollars07), SUM(cv.InitialProjectionDollars08), SUM(cv.InitialProjectionDollars09), 
			SUM(cv.InitialProjectionDollars10), SUM(cv.InitialProjectionDollars11), SUM(cv.InitialProjectionDollars12)
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted)
			INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID
				AND config.ChargeCodeID = cv.ChargeCodeID
				AND config.PatientClassID = cv.PatientClassID
				AND config.EntityGroupConfigID = cv.EntityGroupConfigID
		WHERE config.EntityGroupConfigID = @EntityGroupConfigID 
			AND config.IsRecordDeleted = 0
			AND config.AccountID > 0
		GROUP BY config.DepartmentID, config.AccountID
		OPTION (RECOMPILE);
	END
	ELSE
	BEGIN
		CREATE TABLE #FilterByDepartment (DepartmentID int)
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

		INSERT INTO #RecordsToCrosswalk (DepartmentID, AccountID, 
			InitialBudgetDollars01, InitialBudgetDollars02, InitialBudgetDollars03, 
			InitialBudgetDollars04, InitialBudgetDollars05, InitialBudgetDollars06, 
			InitialBudgetDollars07, InitialBudgetDollars08, InitialBudgetDollars09, 
			InitialBudgetDollars10, InitialBudgetDollars11, InitialBudgetDollars12,
			InitialProjectionDollars01, InitialProjectionDollars02, InitialProjectionDollars03, 
			InitialProjectionDollars04, InitialProjectionDollars05, InitialProjectionDollars06, 
			InitialProjectionDollars07, InitialProjectionDollars08, InitialProjectionDollars09, 
			InitialProjectionDollars10, InitialProjectionDollars11, InitialProjectionDollars12
			)
		SELECT DISTINCT config.DepartmentID, config.AccountID,
			SUM(cv.InitialBudgetDollars01), SUM(cv.InitialBudgetDollars02), SUM(cv.InitialBudgetDollars03), 
			SUM(cv.InitialBudgetDollars04), SUM(cv.InitialBudgetDollars05), SUM(cv.InitialBudgetDollars06), 
			SUM(cv.InitialBudgetDollars07), SUM(cv.InitialBudgetDollars08), SUM(cv.InitialBudgetDollars09), 
			SUM(cv.InitialBudgetDollars10), SUM(cv.InitialBudgetDollars11), SUM(cv.InitialBudgetDollars12),
			SUM(cv.InitialProjectionDollars01), SUM(cv.InitialProjectionDollars02), SUM(cv.InitialProjectionDollars03), 
			SUM(cv.InitialProjectionDollars04), SUM(cv.InitialProjectionDollars05), SUM(cv.InitialProjectionDollars06), 
			SUM(cv.InitialProjectionDollars07), SUM(cv.InitialProjectionDollars08), SUM(cv.InitialProjectionDollars09), 
			SUM(cv.InitialProjectionDollars10), SUM(cv.InitialProjectionDollars11), SUM(cv.InitialProjectionDollars12)
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted)
			INNER JOIN #FilterByDepartment ft ON config.DepartmentID = ft.DepartmentID
			INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID
				AND config.ChargeCodeID = cv.ChargeCodeID
				AND config.PatientClassID = cv.PatientClassID
				AND config.EntityGroupConfigID = cv.EntityGroupConfigID
		WHERE config.EntityGroupConfigID = @EntityGroupConfigID 
			AND config.IsRecordDeleted = 0
			AND config.AccountID > 0
		GROUP BY config.DepartmentID, config.AccountID
		OPTION (RECOMPILE);
		
		DROP TABLE #FilterByDepartment		
	END

	IF (@IsDebug = 0) 
	BEGIN
		UPDATE gl
			SET  InitialBudget01 = xwalk.InitialBudgetDollars01
				,InitialBudget02 = xwalk.InitialBudgetDollars02
				,InitialBudget03 = xwalk.InitialBudgetDollars03
				,InitialBudget04 = xwalk.InitialBudgetDollars04
				,InitialBudget05 = xwalk.InitialBudgetDollars05
				,InitialBudget06 = xwalk.InitialBudgetDollars06
				,InitialBudget07 = xwalk.InitialBudgetDollars07
				,InitialBudget08 = xwalk.InitialBudgetDollars08
				,InitialBudget09 = xwalk.InitialBudgetDollars09
				,InitialBudget10 = xwalk.InitialBudgetDollars10
				,InitialBudget11 = xwalk.InitialBudgetDollars11
				,InitialBudget12 = xwalk.InitialBudgetDollars12
				,InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN gl.InitialProjection01 ELSE xwalk.InitialProjectionDollars01 END
				,InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN gl.InitialProjection02 ELSE xwalk.InitialProjectionDollars01 END
				,InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN gl.InitialProjection03 ELSE xwalk.InitialProjectionDollars03 END
				,InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN gl.InitialProjection04 ELSE xwalk.InitialProjectionDollars04 END
				,InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN gl.InitialProjection05 ELSE xwalk.InitialProjectionDollars05 END
				,InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN gl.InitialProjection06 ELSE xwalk.InitialProjectionDollars06 END
				,InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN gl.InitialProjection07 ELSE xwalk.InitialProjectionDollars07 END
				,InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN gl.InitialProjection08 ELSE xwalk.InitialProjectionDollars08 END
				,InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN gl.InitialProjection09 ELSE xwalk.InitialProjectionDollars09 END
				,InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE xwalk.InitialProjectionDollars10 END
				,InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE xwalk.InitialProjectionDollars11 END
				,InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE xwalk.InitialProjectionDollars12 END

		FROM fp.GeneralLedger gl
			INNER JOIN #RecordsToCrosswalk xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 2 AND gl.EntityGroupConfigID = @EntityGroupConfigID

		UPDATE gl
			SET  InitialBudget01 = 0
				,InitialBudget02 = 0
				,InitialBudget03 = 0
				,InitialBudget04 = 0
				,InitialBudget05 = 0
				,InitialBudget06 = 0
				,InitialBudget07 = 0
				,InitialBudget08 = 0
				,InitialBudget09 = 0
				,InitialBudget10 = 0
				,InitialBudget11 = 0
				,InitialBudget12 = 0
				,InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN gl.InitialProjection01 ELSE 0 END
				,InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN gl.InitialProjection02 ELSE 0 END
				,InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN gl.InitialProjection03 ELSE 0 END
				,InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN gl.InitialProjection04 ELSE 0 END
				,InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN gl.InitialProjection05 ELSE 0 END
				,InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN gl.InitialProjection06 ELSE 0 END
				,InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN gl.InitialProjection07 ELSE 0 END
				,InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN gl.InitialProjection08 ELSE 0 END
				,InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN gl.InitialProjection09 ELSE 0 END
				,InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE 0 END
				,InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE 0 END
				,InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE 0 END
		FROM fp.GeneralLedger gl
			INNER JOIN #RecordsToCrosswalk xwalk on gl.DepartmentID = xwalk.DepartmentID
				AND gl.AccountID = xwalk.AccountID
		WHERE gl.VariabilityID = 1 AND gl.EntityGroupConfigID = @EntityGroupConfigID
	END ELSE BEGIN
		SELECT 'RecordsToCrosswalk', * FROM #RecordsToCrosswalk
	END

 END
GO


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

-- fp.procCrosswalkChargeUnitsToStats
CREATE PROCEDURE [fp].[procCrosswalkChargeUnitsToStats] @EntityGroupConfigID INT
 ,@MonthsLoaded INT
 ,@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 ,@IsDebug BIT = 0
AS
BEGIN
 exec [dbo].[procSysDropTempTable] '#itemsToFlex'
 exec [dbo].[procSysDropTempTable] '#flexValues'
 exec [dbo].[procSysDropTempTable] '#weightedUnitsTotal'
 exec [dbo].[procSysDropTempTable] '#budget_basisIDs'
 exec [dbo].[procSysDropTempTable] '#projection_basisIDs'
 exec [dbo].[procSysDropTempTable] '#FilterByDepartment'
 exec [dbo].[procSysDropTempTable] '#cv'
 
 /**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI   Description
 ** 1    2018-07-04  IP      B-19914  APE Data Refresh - Flexing Revenue and Statistics by DCV
 ** 2    2018-10-19  BK      D-07730   Fix check for change values to include all months instead of total
 ** 3 	 2018-11-26  GF  	 D-07835  Add source dimensionality param
 ** 4 	 2018-12-16  MY  	 B-21514  Converted to new config table
 ** 5 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
 ** 6 	 2021-03-13  NN  	 JAZZ-14116  Remove null joins
 ** 7 	 2022-09-30	 JB		 JAZZ-43489	Remove FlexedValue references
 ** 8 	 2022-03-15	 BW		 JAZZ-49994	Updated for new data model, use [fp].[ChargeVolume]
 ** 8 	 2022-04-20	 BK		 JAZZ------	Performance tuning based on testing
 *************************************************************/
 CREATE TABLE #itemsToFlex (
  DepartmentID INT
  ,StatAccountID INT
  ,ChargeCodeID INT
  ,PatientClassID INT
  )
 CREATE TABLE #weightedUnitsTotal(
   DepartmentID INT
  ,PatientClassID INT
  ,ChargeCodeID INT
  ,AccountID INT
  ,AdjustedTargetValue01 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue02 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue03 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue04 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue05 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue06 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue07 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue08 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue09 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue10 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue11 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedTargetValue12 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue01 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue02 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue03 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue04 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue05 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue06 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue07 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue08 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue09 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue10 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue11 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedBudgetValue12 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue01 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue02 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue03 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue04 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue05 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue06 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue07 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue08 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue09 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue10 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue11 DECIMAL(19,8) NOT NULL DEFAULT(0)
  ,AdjustedProjectionValue12 DECIMAL(19,8) NOT NULL DEFAULT(0)
 )
 
 /* Based on performance testing, pulling cv data into the temp table reduced the time for this to run by 45 seconds */
 CREATE TABLE #cv ( DepartmentID int, ChargeCodeID int, PatientClassID int,
 TargetAdjusted01 DECIMAL(19,8),TargetAdjusted02  DECIMAL(19,8),TargetAdjusted03  DECIMAL(19,8),TargetAdjusted04  DECIMAL(19,8),TargetAdjusted05  DECIMAL(19,8),TargetAdjusted06  DECIMAL(19,8),TargetAdjusted07  DECIMAL(19,8),TargetAdjusted08  DECIMAL(19,8),TargetAdjusted09  DECIMAL(19,8),TargetAdjusted10  DECIMAL(19,8),TargetAdjusted11  DECIMAL(19,8),TargetAdjusted12  DECIMAL(19,8),
 BudgetAdjusted01  DECIMAL(19,8),BudgetAdjusted02  DECIMAL(19,8),BudgetAdjusted03  DECIMAL(19,8),BudgetAdjusted04  DECIMAL(19,8),BudgetAdjusted05  DECIMAL(19,8),BudgetAdjusted06  DECIMAL(19,8),BudgetAdjusted07  DECIMAL(19,8),BudgetAdjusted08  DECIMAL(19,8),BudgetAdjusted09  DECIMAL(19,8),BudgetAdjusted10  DECIMAL(19,8),BudgetAdjusted11  DECIMAL(19,8),BudgetAdjusted12  DECIMAL(19,8),
 ProjectionAdjusted01  DECIMAL(19,8),ProjectionAdjusted02  DECIMAL(19,8),ProjectionAdjusted03  DECIMAL(19,8),ProjectionAdjusted04  DECIMAL(19,8),ProjectionAdjusted05  DECIMAL(19,8),ProjectionAdjusted06  DECIMAL(19,8),ProjectionAdjusted07  DECIMAL(19,8),ProjectionAdjusted08  DECIMAL(19,8),ProjectionAdjusted09  DECIMAL(19,8),ProjectionAdjusted10  DECIMAL(19,8),ProjectionAdjusted11  DECIMAL(19,8),ProjectionAdjusted12 DECIMAL(19,8)
)
  
 CREATE TABLE #FilterByDepartment (DepartmentID int)
 INSERT INTO #FilterByDepartment (DepartmentID)
 SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
 
 -- Getting the department and accounts to flex by charge code budget (Once we either lock the screen or can target the adjustment we can target the flexing)
 IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
 BEGIN
	 INSERT INTO #itemsToFlex (DepartmentID, StatAccountID, ChargeCodeID, PatientClassID)
	 SELECT DISTINCT fsc.DepartmentID, fsc.AccountID AS StatAccountID, fsc.ChargeCodeID, fsc.PatientClassID
	 FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc
	 WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID AND fsc.AccountID > 0

	 INSERT INTO #cv
	 SELECT DepartmentID, ChargeCodeID, PatientClassID,
	 SUM(TargetAdjusted01),SUM(TargetAdjusted02),SUM(TargetAdjusted03),SUM(TargetAdjusted04),SUM(TargetAdjusted05),SUM(TargetAdjusted06),SUM(TargetAdjusted07),SUM(TargetAdjusted08),SUM(TargetAdjusted09),SUM(TargetAdjusted10),SUM(TargetAdjusted11),SUM(TargetAdjusted12),
	 SUM(BudgetAdjusted01),SUM(BudgetAdjusted02),SUM(BudgetAdjusted03),SUM(BudgetAdjusted04),SUM(BudgetAdjusted05),SUM(BudgetAdjusted06),SUM(BudgetAdjusted07),SUM(BudgetAdjusted08),SUM(BudgetAdjusted09),SUM(BudgetAdjusted10),SUM(BudgetAdjusted11),SUM(BudgetAdjusted12),
	 SUM(ProjectionAdjusted01),SUM(ProjectionAdjusted02),SUM(ProjectionAdjusted03),SUM(ProjectionAdjusted04),SUM(ProjectionAdjusted05),SUM(ProjectionAdjusted06),SUM(ProjectionAdjusted07),SUM(ProjectionAdjusted08),SUM(ProjectionAdjusted09),SUM(ProjectionAdjusted10),SUM(ProjectionAdjusted11),SUM(ProjectionAdjusted12)
	 FROM [fp].[ChargeVolume] WHERE UnitTypeID = 145 and EntityGroupConfigID = @EntityGroupConfigID
	 GROUP BY DepartmentID,PatientClassID,ChargeCodeID
 END ELSE BEGIN
	 INSERT INTO #itemsToFlex (DepartmentID, StatAccountID, ChargeCodeID, PatientClassID)
	 SELECT DISTINCT fsc.DepartmentID, fsc.AccountID AS StatAccountID, fsc.ChargeCodeID, fsc.PatientClassID
	 FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc
	 INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID
	 WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID AND fsc.AccountID > 0

	 INSERT INTO #cv
	 SELECT cv.DepartmentID, ChargeCodeID, PatientClassID,
	 SUM(TargetAdjusted01),SUM(TargetAdjusted02),SUM(TargetAdjusted03),SUM(TargetAdjusted04),SUM(TargetAdjusted05),SUM(TargetAdjusted06),SUM(TargetAdjusted07),SUM(TargetAdjusted08),SUM(TargetAdjusted09),SUM(TargetAdjusted10),SUM(TargetAdjusted11),SUM(TargetAdjusted12),
	 SUM(BudgetAdjusted01),SUM(BudgetAdjusted02),SUM(BudgetAdjusted03),SUM(BudgetAdjusted04),SUM(BudgetAdjusted05),SUM(BudgetAdjusted06),SUM(BudgetAdjusted07),SUM(BudgetAdjusted08),SUM(BudgetAdjusted09),SUM(BudgetAdjusted10),SUM(BudgetAdjusted11),SUM(BudgetAdjusted12),
	 SUM(ProjectionAdjusted01),SUM(ProjectionAdjusted02),SUM(ProjectionAdjusted03),SUM(ProjectionAdjusted04),SUM(ProjectionAdjusted05),SUM(ProjectionAdjusted06),SUM(ProjectionAdjusted07),SUM(ProjectionAdjusted08),SUM(ProjectionAdjusted09),SUM(ProjectionAdjusted10),SUM(ProjectionAdjusted11),SUM(ProjectionAdjusted12)
	 FROM [fp].[ChargeVolume] cv INNER JOIN #FilterByDepartment ft on ft.DepartmentID = cv.DepartmentID
	 WHERE UnitTypeID = 145 and EntityGroupConfigID = @EntityGroupConfigID
	 GROUP BY cv.DepartmentID,PatientClassID,ChargeCodeID
 END

 
  
 -- get the total weight charge data by department/chargecode/fiscalmonth 
INSERT INTO #weightedUnitsTotal (DepartmentID, PatientClassID, ChargeCodeID,  AccountID
  ,AdjustedTargetValue01 
  ,AdjustedTargetValue02 
  ,AdjustedTargetValue03 
  ,AdjustedTargetValue04 
  ,AdjustedTargetValue05 
  ,AdjustedTargetValue06 
  ,AdjustedTargetValue07 
  ,AdjustedTargetValue08 
  ,AdjustedTargetValue09 
  ,AdjustedTargetValue10 
  ,AdjustedTargetValue11 
  ,AdjustedTargetValue12 
  ,AdjustedBudgetValue01 
  ,AdjustedBudgetValue02 
  ,AdjustedBudgetValue03 
  ,AdjustedBudgetValue04 
  ,AdjustedBudgetValue05 
  ,AdjustedBudgetValue06 
  ,AdjustedBudgetValue07 
  ,AdjustedBudgetValue08 
  ,AdjustedBudgetValue09 
  ,AdjustedBudgetValue10 
  ,AdjustedBudgetValue11 
  ,AdjustedBudgetValue12 
  ,AdjustedProjectionValue01 
  ,AdjustedProjectionValue02 
  ,AdjustedProjectionValue03 
  ,AdjustedProjectionValue04 
  ,AdjustedProjectionValue05 
  ,AdjustedProjectionValue06 
  ,AdjustedProjectionValue07 
  ,AdjustedProjectionValue08 
  ,AdjustedProjectionValue09 
  ,AdjustedProjectionValue10 
  ,AdjustedProjectionValue11 
  ,AdjustedProjectionValue12 
  )
  SELECT 
   config.DepartmentID
  ,config.PatientClassID
  ,config.ChargeCodeID
  ,config.StatAccountID AS AccountID
  ,ISNULL(SUM(cv.TargetAdjusted01 * fsc.RVUWeight), 0) AS AdjustedTargetValue01
  ,ISNULL(SUM(cv.TargetAdjusted02 * fsc.RVUWeight), 0) AS AdjustedTargetValue02
  ,ISNULL(SUM(cv.TargetAdjusted03 * fsc.RVUWeight), 0) AS AdjustedTargetValue03
  ,ISNULL(SUM(cv.TargetAdjusted04 * fsc.RVUWeight), 0) AS AdjustedTargetValue04
  ,ISNULL(SUM(cv.TargetAdjusted05 * fsc.RVUWeight), 0) AS AdjustedTargetValue05
  ,ISNULL(SUM(cv.TargetAdjusted06 * fsc.RVUWeight), 0) AS AdjustedTargetValue06
  ,ISNULL(SUM(cv.TargetAdjusted07 * fsc.RVUWeight), 0) AS AdjustedTargetValue07
  ,ISNULL(SUM(cv.TargetAdjusted08 * fsc.RVUWeight), 0) AS AdjustedTargetValue08
  ,ISNULL(SUM(cv.TargetAdjusted09 * fsc.RVUWeight), 0) AS AdjustedTargetValue09
  ,ISNULL(SUM(cv.TargetAdjusted10 * fsc.RVUWeight), 0) AS AdjustedTargetValue10
  ,ISNULL(SUM(cv.TargetAdjusted11 * fsc.RVUWeight), 0) AS AdjustedTargetValue11
  ,ISNULL(SUM(cv.TargetAdjusted12 * fsc.RVUWeight), 0) AS AdjustedTargetValue12
  ,ISNULL(SUM(cv.BudgetAdjusted01 * fsc.RVUWeight), 0) AS AdjustedBudgetValue01
  ,ISNULL(SUM(cv.BudgetAdjusted02 * fsc.RVUWeight), 0) AS AdjustedBudgetValue02
  ,ISNULL(SUM(cv.BudgetAdjusted03 * fsc.RVUWeight), 0) AS AdjustedBudgetValue03
  ,ISNULL(SUM(cv.BudgetAdjusted04 * fsc.RVUWeight), 0) AS AdjustedBudgetValue04
  ,ISNULL(SUM(cv.BudgetAdjusted05 * fsc.RVUWeight), 0) AS AdjustedBudgetValue05
  ,ISNULL(SUM(cv.BudgetAdjusted06 * fsc.RVUWeight), 0) AS AdjustedBudgetValue06
  ,ISNULL(SUM(cv.BudgetAdjusted07 * fsc.RVUWeight), 0) AS AdjustedBudgetValue07
  ,ISNULL(SUM(cv.BudgetAdjusted08 * fsc.RVUWeight), 0) AS AdjustedBudgetValue08
  ,ISNULL(SUM(cv.BudgetAdjusted09 * fsc.RVUWeight), 0) AS AdjustedBudgetValue09
  ,ISNULL(SUM(cv.BudgetAdjusted10 * fsc.RVUWeight), 0) AS AdjustedBudgetValue10
  ,ISNULL(SUM(cv.BudgetAdjusted11 * fsc.RVUWeight), 0) AS AdjustedBudgetValue11
  ,ISNULL(SUM(cv.BudgetAdjusted12 * fsc.RVUWeight), 0) AS AdjustedBudgetValue12
  ,ISNULL(SUM(cv.ProjectionAdjusted01 * fsc.RVUWeight), 0) AS AdjustedProjectionValue01
  ,ISNULL(SUM(cv.ProjectionAdjusted02 * fsc.RVUWeight), 0) AS AdjustedProjectionValue02
  ,ISNULL(SUM(cv.ProjectionAdjusted03 * fsc.RVUWeight), 0) AS AdjustedProjectionValue03
  ,ISNULL(SUM(cv.ProjectionAdjusted04 * fsc.RVUWeight), 0) AS AdjustedProjectionValue04
  ,ISNULL(SUM(cv.ProjectionAdjusted05 * fsc.RVUWeight), 0) AS AdjustedProjectionValue05
  ,ISNULL(SUM(cv.ProjectionAdjusted06 * fsc.RVUWeight), 0) AS AdjustedProjectionValue06
  ,ISNULL(SUM(cv.ProjectionAdjusted07 * fsc.RVUWeight), 0) AS AdjustedProjectionValue07
  ,ISNULL(SUM(cv.ProjectionAdjusted08 * fsc.RVUWeight), 0) AS AdjustedProjectionValue08
  ,ISNULL(SUM(cv.ProjectionAdjusted09 * fsc.RVUWeight), 0) AS AdjustedProjectionValue09
  ,ISNULL(SUM(cv.ProjectionAdjusted10 * fsc.RVUWeight), 0) AS AdjustedProjectionValue10
  ,ISNULL(SUM(cv.ProjectionAdjusted11 * fsc.RVUWeight), 0) AS AdjustedProjectionValue11
  ,ISNULL(SUM(cv.ProjectionAdjusted12 * fsc.RVUWeight), 0) AS AdjustedProjectionValue12
 FROM #itemsToFlex config
 INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc 
  ON fsc.DepartmentID = config.DepartmentID 
   AND fsc.ChargeCodeID = config.ChargeCodeID 
   AND fsc.PatientClassID = config.PatientClassID 
   AND fsc.AccountID = config.StatAccountID
 LEFT JOIN #cv cv  
  ON cv.DepartmentID = config.DepartmentID
   AND cv.ChargeCodeID = config.ChargeCodeID
   AND cv.PatientClassID = config.PatientClassID   
 WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID
 GROUP BY config.DepartmentID,
  config.PatientClassID,
  config.ChargeCodeID,
  config.StatAccountID

SELECT 
  basis.StatisticsID
  ,SUM(ISNULL(abb.AdjustedTargetValue01, 0)) AS AdjustedTargetValue01
  ,SUM(ISNULL(abb.AdjustedTargetValue02, 0)) AS AdjustedTargetValue02
  ,SUM(ISNULL(abb.AdjustedTargetValue03, 0)) AS AdjustedTargetValue03
  ,SUM(ISNULL(abb.AdjustedTargetValue04, 0)) AS AdjustedTargetValue04
  ,SUM(ISNULL(abb.AdjustedTargetValue05, 0)) AS AdjustedTargetValue05
  ,SUM(ISNULL(abb.AdjustedTargetValue06, 0)) AS AdjustedTargetValue06
  ,SUM(ISNULL(abb.AdjustedTargetValue07, 0)) AS AdjustedTargetValue07
  ,SUM(ISNULL(abb.AdjustedTargetValue08, 0)) AS AdjustedTargetValue08
  ,SUM(ISNULL(abb.AdjustedTargetValue09, 0)) AS AdjustedTargetValue09
  ,SUM(ISNULL(abb.AdjustedTargetValue10, 0)) AS AdjustedTargetValue10
  ,SUM(ISNULL(abb.AdjustedTargetValue11, 0)) AS AdjustedTargetValue11
  ,SUM(ISNULL(abb.AdjustedTargetValue12, 0)) AS AdjustedTargetValue12
  ,SUM(ISNULL(abb.AdjustedBudgetValue01, 0)) AS AdjustedBudgetValue01
  ,SUM(ISNULL(abb.AdjustedBudgetValue02, 0)) AS AdjustedBudgetValue02
  ,SUM(ISNULL(abb.AdjustedBudgetValue03, 0)) AS AdjustedBudgetValue03
  ,SUM(ISNULL(abb.AdjustedBudgetValue04, 0)) AS AdjustedBudgetValue04
  ,SUM(ISNULL(abb.AdjustedBudgetValue05, 0)) AS AdjustedBudgetValue05
  ,SUM(ISNULL(abb.AdjustedBudgetValue06, 0)) AS AdjustedBudgetValue06
  ,SUM(ISNULL(abb.AdjustedBudgetValue07, 0)) AS AdjustedBudgetValue07
  ,SUM(ISNULL(abb.AdjustedBudgetValue08, 0)) AS AdjustedBudgetValue08
  ,SUM(ISNULL(abb.AdjustedBudgetValue09, 0)) AS AdjustedBudgetValue09
  ,SUM(ISNULL(abb.AdjustedBudgetValue10, 0)) AS AdjustedBudgetValue10
  ,SUM(ISNULL(abb.AdjustedBudgetValue11, 0)) AS AdjustedBudgetValue11
  ,SUM(ISNULL(abb.AdjustedBudgetValue12, 0)) AS AdjustedBudgetValue12
  ,SUM(ISNULL(abb.AdjustedProjectionValue01, 0)) AS AdjustedProjectionValue01
  ,SUM(ISNULL(abb.AdjustedProjectionValue02, 0)) AS AdjustedProjectionValue02
  ,SUM(ISNULL(abb.AdjustedProjectionValue03, 0)) AS AdjustedProjectionValue03
  ,SUM(ISNULL(abb.AdjustedProjectionValue04, 0)) AS AdjustedProjectionValue04
  ,SUM(ISNULL(abb.AdjustedProjectionValue05, 0)) AS AdjustedProjectionValue05
  ,SUM(ISNULL(abb.AdjustedProjectionValue06, 0)) AS AdjustedProjectionValue06
  ,SUM(ISNULL(abb.AdjustedProjectionValue07, 0)) AS AdjustedProjectionValue07
  ,SUM(ISNULL(abb.AdjustedProjectionValue08, 0)) AS AdjustedProjectionValue08
  ,SUM(ISNULL(abb.AdjustedProjectionValue09, 0)) AS AdjustedProjectionValue09
  ,SUM(ISNULL(abb.AdjustedProjectionValue10, 0)) AS AdjustedProjectionValue10
  ,SUM(ISNULL(abb.AdjustedProjectionValue11, 0)) AS AdjustedProjectionValue11
  ,SUM(ISNULL(abb.AdjustedProjectionValue12, 0)) AS AdjustedProjectionValue12
 INTO #flexValues
 FROM [fp].[FactStatistics] basis
 INNER JOIN #itemsToFlex fm
  ON basis.DepartmentID = fm.DepartmentID
   AND basis.AccountID = fm.StatAccountID
 LEFT JOIN #weightedUnitsTotal abb
  ON basis.DepartmentID = abb.DepartmentID
   AND fm.PatientClassID = abb.PatientClassID
   AND fm.ChargeCodeID = abb.ChargeCodeID
   AND fm.StatAccountID = abb.AccountID
 WHERE basis.EntityGroupConfigID = @EntityGroupConfigID
 GROUP BY basis.StatisticsID
 
 IF (@IsDebug = 0)
 BEGIN
  -- Flex the appropriate departments
  
 UPDATE basis
  SET basis.AdjustedValue01 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue01 ELSE flexed.AdjustedBudgetValue01 END
   ,basis.AdjustedValue02 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue02 ELSE flexed.AdjustedBudgetValue02 END
   ,basis.AdjustedValue03 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue03 ELSE flexed.AdjustedBudgetValue03 END
   ,basis.AdjustedValue04 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue04 ELSE flexed.AdjustedBudgetValue04 END
   ,basis.AdjustedValue05 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue05 ELSE flexed.AdjustedBudgetValue05 END
   ,basis.AdjustedValue06 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue06 ELSE flexed.AdjustedBudgetValue06 END
   ,basis.AdjustedValue07 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue07 ELSE flexed.AdjustedBudgetValue07 END
   ,basis.AdjustedValue08 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue08 ELSE flexed.AdjustedBudgetValue08 END
   ,basis.AdjustedValue09 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue09 ELSE flexed.AdjustedBudgetValue09 END
   ,basis.AdjustedValue10 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue10 ELSE flexed.AdjustedBudgetValue10 END
   ,basis.AdjustedValue11 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue11 ELSE flexed.AdjustedBudgetValue11 END
   ,basis.AdjustedValue12 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue12 ELSE flexed.AdjustedBudgetValue12 END
   ,basis.LockFlag = 1
   ,basis.LockType = 3
  FROM [fp].[FactStatisticsBudget] basis
  INNER JOIN #flexValues flexed
   ON basis.StatisticsID = flexed.StatisticsID
  -- AND basis.BudgetPhaseID = flexed.BudgetPhaseID
  WHERE 
     basis.AdjustedValue01 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue01 ELSE flexed.AdjustedBudgetValue01 END
   OR basis.AdjustedValue02 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue02 ELSE flexed.AdjustedBudgetValue02 END
   OR basis.AdjustedValue03 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue03 ELSE flexed.AdjustedBudgetValue03 END
   OR basis.AdjustedValue04 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue04 ELSE flexed.AdjustedBudgetValue04 END
   OR basis.AdjustedValue05 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue05 ELSE flexed.AdjustedBudgetValue05 END
   OR basis.AdjustedValue06 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue06 ELSE flexed.AdjustedBudgetValue06 END
   OR basis.AdjustedValue07 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue07 ELSE flexed.AdjustedBudgetValue07 END
   OR basis.AdjustedValue08 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue08 ELSE flexed.AdjustedBudgetValue08 END
   OR basis.AdjustedValue09 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue09 ELSE flexed.AdjustedBudgetValue09 END
   OR basis.AdjustedValue10 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue10 ELSE flexed.AdjustedBudgetValue10 END
   OR basis.AdjustedValue11 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue11 ELSE flexed.AdjustedBudgetValue11 END
   OR basis.AdjustedValue12 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue12 ELSE flexed.AdjustedBudgetValue12 END
   OR basis.LockFlag = 0 
    

  DECLARE @i int = @MonthsLoaded + 1 -- (starting from month that should be changed.)
  DECLARE @MonthsLoadedString CHAR(10)
  SELECT @MonthsLoadedString = CAST(@i as CHAR(2));
  DECLARE @sql varchar(max) = 'UPDATE basis SET '
  WHILE (@i <= 12)
  BEGIN 
   SET @sql = @sql + 'basis.AdjustedValue' + case when @i < 10 then '0' else '' end +cast(@i as varchar(2))+' = flexed.AdjustedProjectionValue' + case when @i < 10 then '0' else '' end +cast(@i as varchar(2)) + CASE WHEN @i < 12 THEN ', ' ELSE '' END
   SET @i = @i + 1
  END
  
  SET @sql = @sql + '
   , basis.LockFlag = 1
   , basis.LockType = 3
  FROM [fp].[FactStatisticsProjection] basis
  INNER JOIN #flexValues flexed
   ON basis.StatisticsID = flexed.StatisticsID
   --AND basis.BudgetPhaseID = flexed.BudgetPhaseID
  WHERE 
    (basis.AdjustedValue01 != flexed.AdjustedProjectionValue01 AND ' + @MonthsLoadedString + ' <= 1 )
   OR (basis.AdjustedValue02 != flexed.AdjustedProjectionValue02 AND ' + @MonthsLoadedString + ' <= 2 )   
   OR (basis.AdjustedValue03 != flexed.AdjustedProjectionValue03 AND ' + @MonthsLoadedString + ' <= 3 )   
   OR (basis.AdjustedValue04 != flexed.AdjustedProjectionValue04 AND ' + @MonthsLoadedString + ' <= 4 )   
   OR (basis.AdjustedValue05 != flexed.AdjustedProjectionValue05 AND ' + @MonthsLoadedString + ' <= 5 )   
   OR (basis.AdjustedValue06 != flexed.AdjustedProjectionValue06 AND ' + @MonthsLoadedString + ' <= 6 )   
   OR (basis.AdjustedValue07 != flexed.AdjustedProjectionValue07 AND ' + @MonthsLoadedString + ' <= 7 )   
   OR (basis.AdjustedValue08 != flexed.AdjustedProjectionValue08 AND ' + @MonthsLoadedString + ' <= 8 )   
   OR (basis.AdjustedValue09 != flexed.AdjustedProjectionValue09 AND ' + @MonthsLoadedString + ' <= 9 )   
   OR (basis.AdjustedValue10 != flexed.AdjustedProjectionValue10 AND ' + @MonthsLoadedString + ' <= 10 )   
   OR (basis.AdjustedValue11 != flexed.AdjustedProjectionValue11 AND ' + @MonthsLoadedString + ' <= 11 )   
   OR (basis.AdjustedValue12 != flexed.AdjustedProjectionValue12 AND ' + @MonthsLoadedString + ' <= 12 )
   OR basis.LockFlag = 0        
  '
 
  EXEC (@sql)

 END
 ELSE
 BEGIN
  SELECT 'ItemsToFlex', * FROM #itemsToFlex
  SELECT 'WeightedUnitTotal', * FROM #weightedUnitTotal
  SELECT 'FlexedValues', * FROM #flexValues
 END
 
END
GO


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

-- fp.procCrosswalkChargeUnitsToStats_InitialValue
CREATE PROCEDURE [fp].[procCrosswalkChargeUnitsToStats_InitialValue]
	 @EntityGroupConfigID INT,
	 @MonthsLoaded INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
 AS
 	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2 	 2021-03-13  NN  	 JAZZ-14116  Remove null joins
 	 ** 3 	 2022-03-15	 BW		 JAZZ-49994	Updated for new data model, use [fp].[ChargeVolume]
	 *************************************************************/
 BEGIN
 	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	CREATE TABLE #itemsToFlex(DepartmentID INT, StatAccountID INT, ChargeCodeID INT, PatientClassID INT)	
	
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #itemsToFlex(DepartmentID, StatAccountID, ChargeCodeID, PatientClassID)
		SELECT DISTINCT fsc.DepartmentID, fsc.AccountID, fsc.ChargeCodeID, fsc.PatientClassID
		FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc
		WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID and fsc.AccountID > 0
	END ELSE BEGIN
		INSERT INTO #itemsToFlex(DepartmentID, StatAccountID, ChargeCodeID, PatientClassID)
		SELECT DISTINCT fsc.DepartmentID, fsc.AccountID, fsc.ChargeCodeID, fsc.PatientClassID
		FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID
		WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID and fsc.AccountID > 0
	END
						   
	
		
	 -- get the total weight charge data by department/chargecode/fiscalmonth
    SELECT 
		flex.DepartmentID, 
		flex.PatientClassID, 
		flex.ChargeCodeID,
		flex.StatAccountID,
		ISNULL(SUM(cv.InitialBudget01 * csc.RVUWeight), 0) As InitialBudget01,
		ISNULL(SUM(cv.InitialBudget02 * csc.RVUWeight), 0) As InitialBudget02,
		ISNULL(SUM(cv.InitialBudget03 * csc.RVUWeight), 0) As InitialBudget03,
		ISNULL(SUM(cv.InitialBudget04 * csc.RVUWeight), 0) As InitialBudget04,
		ISNULL(SUM(cv.InitialBudget05 * csc.RVUWeight), 0) As InitialBudget05,
		ISNULL(SUM(cv.InitialBudget06 * csc.RVUWeight), 0) As InitialBudget06,
		ISNULL(SUM(cv.InitialBudget07 * csc.RVUWeight), 0) As InitialBudget07,
		ISNULL(SUM(cv.InitialBudget08 * csc.RVUWeight), 0) As InitialBudget08,
		ISNULL(SUM(cv.InitialBudget09 * csc.RVUWeight), 0) As InitialBudget09,
		ISNULL(SUM(cv.InitialBudget10 * csc.RVUWeight), 0) As InitialBudget10,
		ISNULL(SUM(cv.InitialBudget11 * csc.RVUWeight), 0) As InitialBudget11,
		ISNULL(SUM(cv.InitialBudget12 * csc.RVUWeight), 0) As InitialBudget12,
		ISNULL(SUM(cv.InitialProjection01 * csc.RVUWeight), 0) As InitialProjection01,
		ISNULL(SUM(cv.InitialProjection02 * csc.RVUWeight), 0) As InitialProjection02,
		ISNULL(SUM(cv.InitialProjection03 * csc.RVUWeight), 0) As InitialProjection03,
		ISNULL(SUM(cv.InitialProjection04 * csc.RVUWeight), 0) As InitialProjection04,
		ISNULL(SUM(cv.InitialProjection05 * csc.RVUWeight), 0) As InitialProjection05,
		ISNULL(SUM(cv.InitialProjection06 * csc.RVUWeight), 0) As InitialProjection06,
		ISNULL(SUM(cv.InitialProjection07 * csc.RVUWeight), 0) As InitialProjection07,
		ISNULL(SUM(cv.InitialProjection08 * csc.RVUWeight), 0) As InitialProjection08,
		ISNULL(SUM(cv.InitialProjection09 * csc.RVUWeight), 0) As InitialProjection09,
		ISNULL(SUM(cv.InitialProjection10 * csc.RVUWeight), 0) As InitialProjection10,
		ISNULL(SUM(cv.InitialProjection11 * csc.RVUWeight), 0) As InitialProjection11,
		ISNULL(SUM(cv.InitialProjection12 * csc.RVUWeight), 0) As InitialProjection12
    INTO #weightedUnitTotal
    FROM #itemsToFlex flex
		INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] csc 
			ON flex.DepartmentID = csc.DepartmentID 
				AND flex.ChargeCodeID = csc.ChargeCodeID 
				AND flex.PatientClassID = csc.PatientClassID
				AND flex.StatAccountID = csc.AccountID
				AND csc.EntityGroupConfigID = @EntityGroupConfigID   
		LEFT JOIN [fp].[ChargeVolume] cv
			ON cv.DepartmentID = flex.DepartmentID 
				AND cv.ChargeCodeID = flex.ChargeCodeID 
				AND cv.PatientClassID = flex.PatientClassID
				AND cv.UnitTypeID = 145
	        	AND cv.EntityGroupConfigID = @EntityGroupConfigID 	
    GROUP BY 
	    flex.DepartmentID, 
		flex.PatientClassID, 
		flex.ChargeCodeID, 
		flex.StatAccountID
  
	SELECT 
		basis.StatisticsID,
		SUM(abb.InitialBudget01) AS InitialBudget01,
		SUM(abb.InitialBudget02) AS InitialBudget02,
		SUM(abb.InitialBudget03) AS InitialBudget03,
		SUM(abb.InitialBudget04) AS InitialBudget04,
		SUM(abb.InitialBudget05) AS InitialBudget05,
		SUM(abb.InitialBudget06) AS InitialBudget06,
		SUM(abb.InitialBudget07) AS InitialBudget07,
		SUM(abb.InitialBudget08) AS InitialBudget08,
		SUM(abb.InitialBudget09) AS InitialBudget09,
		SUM(abb.InitialBudget10) AS InitialBudget10,
		SUM(abb.InitialBudget11) AS InitialBudget11,
		SUM(abb.InitialBudget12) AS InitialBudget12,
		SUM(abb.InitialProjection01) AS InitialProjection01,
		SUM(abb.InitialProjection02) AS InitialProjection02,
		SUM(abb.InitialProjection03) AS InitialProjection03,
		SUM(abb.InitialProjection04) AS InitialProjection04,
		SUM(abb.InitialProjection05) AS InitialProjection05,
		SUM(abb.InitialProjection06) AS InitialProjection06,
		SUM(abb.InitialProjection07) AS InitialProjection07,
		SUM(abb.InitialProjection08) AS InitialProjection08,
		SUM(abb.InitialProjection09) AS InitialProjection09,
		SUM(abb.InitialProjection10) AS InitialProjection10,
		SUM(abb.InitialProjection11) AS InitialProjection11,
		SUM(abb.InitialProjection12) AS InitialProjection12
    INTO #flexedValues
	FROM [fp].[FactStatistics] basis
	    INNER JOIN #itemsToFlex fm ON basis.DepartmentID = fm.DepartmentID AND basis.AccountID = fm.StatAccountID
	    INNER JOIN #weightedUnitTotal abb
	            ON basis.DepartmentID = abb.DepartmentID
		            AND fm.PatientClassID = abb.PatientClassID
	                AND fm.ChargeCodeID = abb.ChargeCodeID
					AND fm.StatAccountID = abb.StatAccountID
    WHERE basis.EntityGroupConfigID = @EntityGroupConfigID
    GROUP BY basis.StatisticsID
 
 
	IF (@IsDebug = 0) 
	BEGIN
				
	    -- Flex
	    UPDATE basis
	    SET basis.InitialBudget01 = flexed.InitialBudget01,
			basis.InitialBudget02 = flexed.InitialBudget02,
			basis.InitialBudget03 = flexed.InitialBudget03,
			basis.InitialBudget04 = flexed.InitialBudget04,
			basis.InitialBudget05 = flexed.InitialBudget05,
			basis.InitialBudget06 = flexed.InitialBudget06,
			basis.InitialBudget07 = flexed.InitialBudget07,
			basis.InitialBudget08 = flexed.InitialBudget08,
			basis.InitialBudget09 = flexed.InitialBudget09,
			basis.InitialBudget10 = flexed.InitialBudget10,
			basis.InitialBudget11 = flexed.InitialBudget11,
			basis.InitialBudget12 = flexed.InitialBudget12,
			basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN basis.InitialProjection01 ELSE flexed.InitialProjection01 END,
			basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN basis.InitialProjection02 ELSE flexed.InitialProjection02 END,
			basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN basis.InitialProjection03 ELSE flexed.InitialProjection03 END,
			basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN basis.InitialProjection04 ELSE flexed.InitialProjection04 END,
			basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN basis.InitialProjection05 ELSE flexed.InitialProjection05 END,
			basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN basis.InitialProjection06 ELSE flexed.InitialProjection06 END,
			basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN basis.InitialProjection07 ELSE flexed.InitialProjection07 END,
			basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN basis.InitialProjection08 ELSE flexed.InitialProjection08 END,
			basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN basis.InitialProjection09 ELSE flexed.InitialProjection09 END,
			basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE flexed.InitialProjection10 END,
			basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE flexed.InitialProjection11 END,
			basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE flexed.InitialProjection12 END
	    FROM [fp].[FactStatistics] basis
		INNER JOIN #flexedValues flexed
	            ON basis.StatisticsID = flexed.StatisticsID
	    WHERE basis.EntityGroupConfigID = @EntityGroupConfigID
	
	END ELSE BEGIN
	
		SELECT 'ItemsToFlex', * FROM #itemsToFlex
		SELECT 'WeightedUnitTotal', * FROM #weightedUnitTotal
		SELECT 'FlexedValues', * FROM #flexedValues
	
	END	
	
 END
GO


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

-- fp.procDataRefreshMethodPreActions
CREATE PROCEDURE fp.procDataRefreshMethodPreActions
	@BudgetConfigID INT,
	@SourceID INT,
	@AdjustmentGUID UNIQUEIDENTIFIER,
	@DataRefreshMethodName NVARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN

	SET NOCOUNT ON;

	/******************* PLEASE READ BEFORE UPDATING THIS PROC ******************
	
		When adding to the proc, please do the following:
		  - Create a defect
		  - Create a migration updating this proc with the workaround
		  		- When updating this migration, include the defect number and breif summary	
		  		
	****************************************************************************/

	-- This proc runs before any datarefresh method and can be customized to workaround a specific issue.

 END
GO


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

-- fp.procDataViewRegisterDimensions
CREATE proc [fp].[procDataViewRegisterDimensions]
	@dvguid uniqueidentifier
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, 5) 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

	--budget config
	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 = 'BudgetConfigID')) 
	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 = 'BudgetConfigID')) begin
		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'BudgetConfigID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Budget Config'
		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 = 'Budget Config' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Budget Config' when a.SQLColumnName = 'Description' then 'Budget Config 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 = 'Budget Config' 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', 'BudgetConfigCode', 'OBModelSectionName', 'OBUnitsFinancialReporting', 'OBUnitsFinancialReportingLineName', 'OBUnitsFinancialReportingSortOrder', 'OBPayor', 'OBPayorGroup', 'OBUnitType', 'PatientClass'))
		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', 'GMAccountRollup1', 'GMAccountRollup2', 'GMAccountRollup3', 'GMAccountRollup4', 'GMAccountRollup5', 'GMAccountRollup6') 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
	
	--variability
	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 = 'VariabilityID')) 
	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 = 'VariabilityID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering VariabilityID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'VariabilityID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Variability'
		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 = 'Variability' and rd.DataViewGUID = @dvguid;
		
		insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias)
		select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Variability' 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 = 'Variability' 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

	--Patient 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 = 'PatientClassID')) 
	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 = 'PatientClassID')) begin
		print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PatientClassID'

		insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured)
		select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PatientClassID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Patient 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 = 'Patient 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 'Patient 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 = 'Patient 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
    
	--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

	--ensure default security
	insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select @dvguid, g.UserGroupGUID, 1, 0, 0 from UserGroup g where g.Name = 'OB - System Administrator'
	and not exists(select 1 from S3SimplePermission ex where ex.LootID = @dvguid and ex.IdentityGUID = g.UserGroupGUID)
GO


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

-- fp.procDeductionsByGrossChargesFlexConfigPopulation
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2018-06-12  IP      B-19913		APE Data Refresh - Flex Mappings, add parameter to process particular departments
** 2    2018-07-03  IP      TK-59678	fix case when @SourceDimensionality is empty
** 3    2018-09-11  apukii  TK-62350	fixed typo in code
** 4    2018-09-25  GF      E-02313		Simplify source dimensionality to only department
** 5	2019-03-08	IP		B-22295		Removed using table variables, small optimizations
** 6    20201-03-26 NT	    JAZZ-14122  Simplify code and remove null joins on targeting object
** 7	 8-11-2023   NT      JAZZ-58154	Data restructure changes
*************************************************************/
CREATE   PROCEDURE [fp].[procDeductionsByGrossChargesFlexConfigPopulation]
	 @EntityGroupConfigGUID UNIQUEIDENTIFIER,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
AS
BEGIN
 	DECLARE @BudgetConfigID INT,
			@EntityGroupConfigID INT,
			@TotalGrossCharges INT,
			@FlexTypeID INT
			
	CREATE TABLE #flexMap (DepartmentID int NOT NULL, GLAccountID int NOT NULL)
	
	SET @BudgetConfigID = (SELECT bc.BudgetConfigID 
						   FROM [fp].[EntityGroupConfig] egc
						   	INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
						   WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
						   
	SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	SET @TotalGrossCharges = 8;
	SET @FlexTypeID = 6;
	
	CREATE TABLE #SourceDimensionality (DepartmentID int)
	

	-- Currently overrides is not a thing on deductions yet, so whatever the department is set to is what wins.	
	-- We just need to find the deduction accounts that are being flexed by total gross charges. Gross Charges By Patient Class will come later
 
	/*
	check if @SourceDimensionality not is empty, then use filter, else - skip using table
	*/
	IF EXISTS (select 1 from @SourceDimensionality) 
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID)
		SELECT DepartmentID FROM @SourceDimensionality
	END ELSE BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[GeneralLedger] fgl
		WHERE fgl.APEModelSectionID = 4
			AND fgl.BudgetConfigID = @BudgetConfigID        
			AND fgl.VariabilityID = 2
	END

	INSERT INTO #flexMap(DepartmentID, GLAccountID)
	SELECT DISTINCT fgl.DepartmentID, fgl.AccountID AS GLAccountID
	FROM [fp].[GeneralLedger] fgl
		INNER JOIN [fp].[DeductionsFlexingConfig] dfc ON dfc.DepartmentID = fgl.DepartmentID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = dfc.EntityGroupConfigGUID
		INNER JOIN [fw].[DimAccount] a ON fgl.AccountID = a.AccountID
		INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fgl.DepartmentID 
	WHERE fgl.APEModelSectionID = 4
		AND dfc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND dfc.FlexMethodID = @TotalGrossCharges
		AND fgl.BudgetConfigID = @BudgetConfigID        
		AND fgl.VariabilityID = 2;	
					
 
	
	;WITH TRG AS 
	(
		SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.FlexingTypeID 
		FROM [fp].[FlexConfigMapping] fcm
		INNER JOIN #SourceDimensionality SD
		ON SD.DepartmentID = fcm.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND FlexingTypeID = @FlexTypeID
	)
	MERGE TRG
	USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID,
				DepartmentID,
				GLAccountID,
				@FlexTypeID AS FlexingTypeID
		FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID and TRG.GLAccountID = SRC.GLAccountID
	WHEN NOT MATCHED BY TARGET THEN
	INSERT VALUES (src.EntityGroupConfigID,src.DepartmentID,src.GLAccountID,src.FlexingTypeID) 
	WHEN NOT MATCHED BY SOURCE THEN DELETE;
	
 END
GO


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

-- fp.procDeleteOrphanAPESectionRoleAccessData
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author  WI   	     Description
** 1 	 2022-07-26  NH  	 JAZZ-35199  Clean up orphan data
*************************************************************/ 
CREATE PROCEDURE fp.procDeleteOrphanAPESectionRoleAccessData
AS
BEGIN
	DELETE sra FROM [fp].[APESectionRoleAccess]  sra
	LEFT JOIN [dbo].[UserRole] ur ON sra.RoleID = ur.RoleID
	WHERE ur.RoleID IS NULL
END
GO


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

-- fp.procDeleteSnapshotDataGeneralLedger
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author			WI			   Description
** 1		2024-10-22		MY				JAZZ-77735	   Initial Creation
** 2		2024-11-04		MY				JAZZ-77737	   Delete Reporting Data
***************************************************************/
CREATE   PROCEDURE [fp].[procDeleteSnapshotDataGeneralLedger]
	@SnapshotID INT
AS
BEGIN	
	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END;
	DECLARE @r INT;
	
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN		
		BEGIN TRANSACTION;			  
			
		DELETE TOP (@ChunkCount) gl 
		FROM [fp].[GeneralLedgerSnapshot] gl
		WHERE SnapshotID = @SnapshotID

		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN		
		BEGIN TRANSACTION;			  
			
		DELETE TOP (@ChunkCount) gl 
		FROM [fp].[FactReportGeneralLedgerSnapshot] gl
		WHERE SnapshotID = @SnapshotID

		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN		
		BEGIN TRANSACTION;			  
			
		DELETE TOP (@ChunkCount) gl 
		FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] gl
		WHERE SnapshotID = @SnapshotID

		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
END
GO


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

-- fp.procDependentStatisticsByDriverStatisticsFlexConfigPopulation
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2020-14-12  MY      JAZZ-11324	Initial
** 2    2021-22-12  OP      JAZZ-30940	Make dependent data sample ignoring IsUsingProviderStats
** 3    2023-13-06  MY      JAZZ-53443	Update stats sampling for cross department stats flexing
** 4    2023-19-09  MY      JAZZ-60117	Updating flexing to support mix of cross dept flexing and non cross dept flexing
** 5    2023-23-10  MY      JAZZ-62535	For Driver > Dependent Flexing without cross department flexing, join on Department
*************************************************************/
CREATE   PROCEDURE [fp].[procDependentStatisticsByDriverStatisticsFlexConfigPopulation]
	 @EntityGroupConfigID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
AS
BEGIN
	-- IMPORTANT NOTE: You may notice that here we're breaking it down by Entity Group Config despite that Provider Sampling is all broken
	-- out by budget config. The reason for this is how the current flexing engine works. It processes each flexing type by entity because most
	-- of them are by entity. If we were to break this out by budget config, we would have to build out an entirely new flexing process outside of the
	-- normal process in order do this which would leave gaps for potential issues. So instead we just parse out the entity groups.

 	DECLARE @BudgetConfigID INT,
			@FlexTypeID INT
			
	SET @BudgetConfigID = (SELECT bc.BudgetConfigID 
						   FROM [fp].[EntityGroupConfig] egc
						   	INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
						   WHERE EntityGroupConfigID = @EntityGroupConfigID)
	SET @FlexTypeID = 8;
	
	CREATE TABLE #flexMap (
                    EntityGroupConfigID INT NOT NULL,
                    DepartmentID INT NOT NULL,
	                DriverAccountID INT NOT NULL,
					DependentStatisticAccountID INT NOT NULL,
					SourceDepartmentID INT NOT NULL
                );

	CREATE TABLE #SourceDimensionality (DepartmentID int)
	INSERT INTO #SourceDimensionality (DepartmentID)
	SELECT DepartmentID FROM @SourceDimensionality
	
	IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[FactStatistics]
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND SubsectionID = 2 -- Dependent
	END

	-- We need to find accounts that meet the following criteria
	--   1. The Department must be configured to use Provider
	--	 2. Provider sampling must be turned on (this is handled in code since it's just a feature flag)
	--	 3. The account combination must be setup as a dependent stat. Accounts labeled as Drivers only are ignored
	--	 4. The account combination must exist in FactStatistics for the Department/Driver/Depdendent to appear

	-- Populate flex config mapping where we are using cross department flexing. In this case, Source Department (Driver) may be different than Dependent Department.
	INSERT INTO #flexMap (EntityGroupConfigID, DepartmentID, DriverAccountID, DependentStatisticAccountID, SourceDepartmentID)
	SELECT DISTINCT depend.EntityGroupConfigID, dsad.DepartmentID, dsa.DriverAccountID, dsa.DependentAccountID, dsa.SourceDepartmentID
	FROM [fp].[DependentStatisticsAccount] dsa
		INNER JOIN [fp].[DependentStatisticsAccountDepartment] dsad ON dsad.DependentStatisticsAccountID = dsa.DependentStatisticsAccountID
		INNER JOIN #SourceDimensionality SD on SD.DepartmentID = dsad.DepartmentID
		-- Validating that the driver account exists for the given department otherwise don't populate it
		INNER JOIN [fp].[FactStatistics] driver ON driver.BudgetConfigID = dsa.BudgetConfigID AND driver.AccountID = dsa.DriverAccountID AND driver.DepartmentID = dsa.SourceDepartmentID AND driver.SubSectionID = 1 -- Driver
		-- Validating that the dependent account exists for the given department otherwise don't populate it
		INNER JOIN [fp].[FactStatistics] depend ON depend.BudgetConfigID = dsa.BudgetConfigID AND depend.AccountID = dsa.DependentAccountID AND depend.DepartmentID = dsad.DepartmentID AND depend.SubSectionID = 2 -- Dependent
	WHERE driver.BudgetConfigID = @BudgetConfigID
		AND driver.UnitTypeID = 140	
		AND depend.BudgetConfigID = @BudgetConfigID
		AND depend.UnitTypeID = 140
		AND depend.EntityGroupConfigID = @EntityGroupConfigID
		
	-- Populate Flex Config mapping where not using Cross Department Flexing
	INSERT INTO #flexMap (EntityGroupConfigID, DepartmentID, DriverAccountID, DependentStatisticAccountID, SourceDepartmentID)
	SELECT DISTINCT depend.EntityGroupConfigID, depend.DepartmentID, dsa.DriverAccountID, dsa.DependentAccountID, depend.DepartmentID
	FROM [fp].[FactStatistics] depend
		INNER JOIN #SourceDimensionality SD on SD.DepartmentID = depend.DepartmentID
		INNER JOIN [fp].[DependentStatisticsAccount] dsa ON depend.BudgetConfigID = dsa.BudgetConfigID AND depend.AccountID = dsa.DependentAccountID -- Validating that the dependent account exists for the given department otherwise don't populate it
		-- Validating that the driver account exists for the given department otherwise don't populate it
		INNER JOIN [fp].[FactStatistics] driver ON driver.BudgetConfigID = dsa.BudgetConfigID AND driver.AccountID = dsa.DriverAccountID AND driver.DepartmentID = depend.DepartmentID AND driver.SubSectionID = 1 -- Driver
		LEFT JOIN [fp].[DependentStatisticsAccountDepartment] dsad ON dsad.DependentStatisticsAccountID = dsa.DependentStatisticsAccountID
		LEFT JOIN #flexMap fm ON fm.DepartmentID = depend.DepartmentID AND fm.DependentStatisticAccountID = depend.AccountID
	WHERE depend.BudgetConfigID = @BudgetConfigID
		AND depend.UnitTypeID = 140
		AND depend.SubSectionID = 2 -- Dependent
		AND depend.EntityGroupConfigID = @EntityGroupConfigID
		AND dsad.RowID IS NULL
		AND fm.DepartmentID IS NULL -- Verify the Department doesn't already exist in here from Cross Department Flexing

	IF (@IsDebug = 0) 
	BEGIN
		;WITH TRG
		AS (
			SELECT 
				fcm.EntityGroupConfigID,
				fcm.DepartmentID,
				fcm.StatAccountID,
				fcm.DependentStatisticAccountID,
				fcm.FlexingTypeID,
				fcm.SourceDepartmentID
			FROM [fp].[FlexConfigMapping] fcm
				INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = fcm.DepartmentID -- NOTE: There may be better ways to handle this merge to get rid of the null condition like this. For now leaving it because the others had it.
			WHERE EntityGroupConfigID = @EntityGroupConfigID 
				AND FlexingTypeID = @FlexTypeID
			) 
		
		MERGE TRG
		USING (
			SELECT EntityGroupConfigID,
					DepartmentID,
					DriverAccountID,
					DependentStatisticAccountID,
					@FlexTypeID AS FlexingTypeID,
					SourceDepartmentID
			FROM #flexMap				
		) AS Src ON TRG.EntityGroupConfigID = SRC.EntityGroupConfigID 
			AND TRG.DepartmentID = SRC.DepartmentID 
			AND TRG.DependentStatisticAccountID = SRC.DependentStatisticAccountID 
			AND TRG.StatAccountID = SRC.DriverAccountID 
			AND TRG.SourceDepartmentID = SRC.SourceDepartmentID
		WHEN NOT MATCHED BY TARGET THEN
		INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.DriverAccountID, src.DependentStatisticAccountID, src.FlexingTypeID, src.SourceDepartmentID) 
		WHEN NOT MATCHED BY SOURCE THEN DELETE; 
	END ELSE BEGIN
		SELECT DepartmentID FROM #SourceDimensionality
		SELECT EntityGroupConfigID, DepartmentID, DriverAccountID, DependentStatisticAccountID, SourceDepartmentID FROM #flexMap
	END

END
GO


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

-- fp.procEditRosterAdjustment
/*************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI			Description
** 1		11/13/17	MY		B-17923		Creates a Dummy Proc for Roster Changes
*************************************************************************************************************************/
CREATE PROCEDURE fp.procEditRosterAdjustment
	@DepartmentID INT,
	@PayCodeGroupID INT,
	@Value DECIMAL(19, 4),
	@Field NVARCHAR(100),
	@JobCodeID INT,
	@EmployeeID INT
AS
BEGIN
	-- Enter Any Logic that is needed for after saving a Roster Adjustment
	PRINT ''
END
GO


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

-- fp.procEncounterBudgetStampOff
CREATE   PROCEDURE [fp].[procEncounterBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
    /*******************************************************************************
    ** Change History
    ********************************************************************************
    ** CID  Date        Author  WI              Description
    ** 1	01-31-2023  MY      JAZZ-48962      Initial Creation
    ** 2	03-28-2023  BK      JAZZ-51558      Update to use new table structure
    ** 3	01-03-2024  MZ      JAZZ-65385      Added Target TimeClass
    ** 4	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	*******************************************************************************/

	-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Budgeted Time Class
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) [int].[FactServiceLine]	WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
   
	INSERT INTO [int].[FactServiceLine] ([TimeClassID], [TimeClassCode], [FiscalYearID], [FiscalYearCode], [FiscalMonthID],
		[FiscalMonthCode], [EntityID], [EntityCode], [PatientClassID], [PatientClassCode], [ServiceLineID], [ServiceLine], [AgeCohortID],
		[AgeCohort], [MedicalSurgicalID], [MedSurg], [DepartmentID], [DepartmentCode], [OBForecastDetailID], [ForecastDetail], [PayorGroupID],
		[PayorID], [Value],	[IsDeleted], [HistoryItemGUID],[PayorGroupCode], [PayorCode])
	SELECT
		@TargetTimeClassID AS [TimeClassID],
		@TimeClassCode AS [TimeClassCode],
		bc.[FiscalYearID],
		bc.[FiscalYearID] AS [FiscalYearCode],
		FM.[FiscalMonthID],
		FM.[FiscalMonthCode],
		FE.[EntityID],
		et.Code AS EntityCode,
		pt.[PatientClassID],
		pt.Code AS [PatientClassCode],
		SL.[ServiceLineID],
		SL.code AS [ServiceLine],
		AG.AgeCohortID AS AgeCohortID,
		AG.Code AS AgeCohort,
		MS.MedicalSurgicalID AS MedicalSurgicalID,
		MS.Code AS MedSurg,
		dep.[DepartmentID],
		dep.[DepartmentCode],
		FD.[OBForecastDetailID],
		fd.Name AS [ForecastDetail],
		FE.[PayorGroupID],
		FE.[PayorID],
		[Value],
		0 AS [IsDeleted],
		@HistoryItemGUID AS [HistoryItemGUID],
		PG.[PayorGroupCode],
		PY.[PayorCode]
FROM (
		SELECT ServiceLineEncounterID, BudgetConfigID, DepartmentID, EntityID, PatientClassID, AgeCohortID, MedicalSurgicalID, ServiceLineID, PayorGroupID, PayorID, UnitTypeID, m.FiscalMonthID, f.Value
		FROM (
			SELECT sle.ServiceLineEncounterID, sle.BudgetConfigID, sle.DepartmentID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.PayorGroupID, sle.PayorID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.UnitTypeID, 
				BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, 
				BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, 
				BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12
			FROM fp.ServiceLineEncounter sle
			WHERE BudgetConfigID = @BudgetConfigID
		) sle
		UNPIVOT (Value FOR FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month')
	) FE
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = FE.BudgetConfigID
		INNER JOIN [fw].[DimFiscalMonth] FM ON FM.FiscalMonthID = FE.FiscalMonthID
		INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = FE.DepartmentID
		INNER JOIN [fw].[DimEntity] et ON et.EntityID = FE.EntityID
		INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = FE.AgeCohortID
		INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = FE.MedicalSurgicalID
		INNER JOIN [fw].[DimPatientClass] PT ON PT.PatientClassID = FE.PatientClassID
		INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = FE.ServiceLineID -- Primary serice line dimension for OB definitions
		INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = 36 -- Encounters
		INNER JOIN [fw].[DimPayorGroup] PG ON PG.PayorGroupID = FE.PayorGroupID
		INNER JOIN [fw].[DimPayor] PY ON PY.PayorID = FE.PayorID
	WHERE 1=1
		and FE.Value <> 0
		and bc.BudgetConfigID = @BudgetConfigID
END
GO


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

-- fp.procEncounterProjectionStampOff
CREATE   PROCEDURE [fp].[procEncounterProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
    /*******************************************************************************
    ** Change History
    ********************************************************************************
    ** CID  Date        Author  WI              Description
    ** 1	11-08-2023  AO      JAZZ-62128      Initial Creation
    ** 2	01-03-2024  MZ      JAZZ-65385      Added Target TimeClass 
    ** 3	01-24-2024  MZ      JAZZ-64527      Fix Months Loaded
	** 4	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 5	04-03-2024	MZ		JAZZ-70053		Fix Month Loaded excluding logic
    *******************************************************************************/

	-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Projected Time Class
	-- and all months if months loaded included otherwise only months NOT loaded will be cleared
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) sl FROM [int].[FactServiceLine] sl
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = sl.FiscalMonthID
		WHERE sl.FiscalYearID = @FiscalYear
			AND sl.TimeClassID = @TargetTimeClassID
			AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded)
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
	
   
	INSERT INTO [int].[FactServiceLine] ([TimeClassID], [TimeClassCode], [FiscalYearID], [FiscalYearCode], [FiscalMonthID],
		[FiscalMonthCode], [EntityID], [EntityCode], [PatientClassID], [PatientClassCode], [ServiceLineID], [ServiceLine], [AgeCohortID],
		[AgeCohort], [MedicalSurgicalID], [MedSurg], [DepartmentID], [DepartmentCode], [OBForecastDetailID], [ForecastDetail], [PayorGroupID],
		[PayorID], [Value],	[IsDeleted], [HistoryItemGUID],[PayorGroupCode], [PayorCode])
	SELECT
		@TargetTimeClassID AS [TimeClassID],
		@TimeClassCode AS [TimeClassCode],
		@FiscalYear,
		@FiscalYear AS [FiscalYearCode],
		FM.[FiscalMonthID],
		FM.[FiscalMonthCode],
		FE.[EntityID],
		et.Code AS EntityCode,
		pt.[PatientClassID],
		pt.Code AS [PatientClassCode],
		SL.[ServiceLineID],
		SL.code AS [ServiceLine],
		AG.AgeCohortID AS AgeCohortID,
		AG.Code AS AgeCohort,
		MS.MedicalSurgicalID AS MedicalSurgicalID,
		MS.Code AS MedSurg,
		dep.[DepartmentID],
		dep.[DepartmentCode],
		FD.[OBForecastDetailID],
		fd.Name AS [ForecastDetail],
		FE.[PayorGroupID],
		FE.[PayorID],
		[Value],
		0 AS [IsDeleted],
		@HistoryItemGUID AS [HistoryItemGUID],
		PG.[PayorGroupCode],
		PY.[PayorCode]
FROM (
		SELECT ServiceLineEncounterID, BudgetConfigID, DepartmentID, EntityID, PatientClassID, AgeCohortID, MedicalSurgicalID, ServiceLineID, PayorGroupID, PayorID, UnitTypeID, m.FiscalMonthID, f.Value
		FROM (
			SELECT sle.ServiceLineEncounterID, sle.BudgetConfigID, sle.DepartmentID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.PayorGroupID, sle.PayorID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.UnitTypeID, 
				ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, 
				ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, 
				ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12
			FROM fp.ServiceLineEncounter sle
			WHERE BudgetConfigID = @BudgetConfigID
		) sle
		UNPIVOT (Value FOR FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month')
	) FE
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = FE.BudgetConfigID
		INNER JOIN [fw].[DimFiscalMonth] FM ON FM.FiscalMonthID = FE.FiscalMonthID
		INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = FE.DepartmentID
		INNER JOIN [fw].[DimEntity] et ON et.EntityID = FE.EntityID
		INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = FE.AgeCohortID
		INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = FE.MedicalSurgicalID
		INNER JOIN [fw].[DimPatientClass] PT ON PT.PatientClassID = FE.PatientClassID
		INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = FE.ServiceLineID -- Primary serice line dimension for OB definitions
		INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = 36 -- Encounters
		INNER JOIN [fw].[DimPayorGroup] PG ON PG.PayorGroupID = FE.PayorGroupID
		INNER JOIN [fw].[DimPayor] PY ON PY.PayorID = FE.PayorID
	WHERE 1=1
		AND FE.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
		AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded)
END
GO


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

-- fp.procEnginePostActions
CREATE   PROCEDURE [fp].[procEnginePostActions]
	@BudgetConfigID INT,
	@SourceID INT,
	@AdjustmentGUID UNIQUEIDENTIFIER,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	SET NOCOUNT ON; 
	
	/******************* PLEASE READ BEFORE UPDATING THIS PROC ******************
	
		When adding to the proc, please do the following:
		  - Create a defect
		  - Create a migration updating this proc with the workaround
		  		- When updating this migration, include the defect number and breif summary	
		  		
	 ****************************************************************************/     

	-- D-09032 & D-09167: Workaround for issue where Benefits are adjusted, but phase 3 adjustments to Staffing aren't flexing phase 3 Benefits
	IF(@SourceID IN (17, 42)) --BenefitsWereAdjusted (D-09032), ReapplyBenefitsAdjustments (D-09167)
	BEGIN
		CREATE TABLE #FilterByDepartment (DepartmentID INT)
		    INSERT INTO #FilterByDepartment (DepartmentID)
		    SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		DECLARE @Json VARCHAR(MAX)
		IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
		BEGIN
		    DECLARE @DeptList VARCHAR(MAX)
		    SET @DeptList=''
		    SELECT  @DeptList = @DeptList + CAST(DepartmentID AS VARCHAR) +','
		    FROM    #FilterByDepartment
		    SELECT  LEFT(@DeptList,LEN(@DeptList)-1) AS DepartmentID
		    SELECT @Json = '{"AffectedDepartments":[' +  LEFT(@DeptList, LEN(@DeptList) - 1) + '],"BudgetPhaseID":null}'
		END ELSE BEGIN
		    SELECT @Json = '{"AffectedDepartments":[],"BudgetPhaseID":null}'
		END
		INSERT INTO fp.BudgetRefreshRequest (BudgetConfigID, DateTimeStamp, DateTimeStampUTC, SourceDimensionalityJSON, SourceActionID, UserName, IsIgnoreTargetingError)
		VALUES (@BudgetConfigID, GETDATE(), GETUTCDATE(), @Json, 48, 'SDT User', 1)   --  PayrollDepartmentPhaseWasAdjusted
	END
	
	
END
GO


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

-- fp.procEnginePreActions
CREATE PROCEDURE fp.procEnginePreActions
	@BudgetConfigID INT,
	@SourceID INT,
	@AdjustmentGUID UNIQUEIDENTIFIER,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
	
	SET NOCOUNT ON;	
	
	/******************* PLEASE READ BEFORE UPDATING THIS PROC ******************
	
		When adding to the proc, please do the following:
		  - Create a defect
		  - Create a migration updating this proc with the workaround
		  		- When updating this migration, include the defect number and breif summary	
		  		
	****************************************************************************/
	
	
	
 END
GO


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

-- fp.procEnsureRoleSecurityDefaultAccess
create proc fp.procEnsureRoleSecurityDefaultAccess
as
	update p set p.ReadValue = 1, p.WriteValue = 1
	from 
		S3Permission p 
		inner join S3PermissionSet ps on ps.PermissionSetID = p.PermissionSetID 
		inner join UserRole r on r.RoleID = p.RoleID 
	where 
		ps.Name = 'Department'
		and exists(select 1 from fp.APESectionRoleAccess ra where ra.RoleID = r.RoleID)
GO


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

-- fp.procFactChargeVolumeBaselineAndHistoryToReportingTransfer
CREATE   PROCEDURE [fp].[procFactChargeVolumeBaselineAndHistoryToReportingTransfer]  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2021-12-27   MD        JAZZ-29138  Initial Creation
	** 2    2022-06-01   MY        JAZZ-33343  Fix Missing Charge Code Join
	** 3    2022-06-03   MY        JAZZ-33343  Update Data Source to Pivoted
	** 4    2022-06-29   BW        JAZZ-39340  Switching from MSDRGID to MSDRGRollupID
	** 5    2022-07-18   MY        JAZZ-37944  Add Initial Baseline
	** 6    2022-12-21   MD        JAZZ-47250  Update history temp table inserts to include dollars without units
	** 7	2023-03-21	 MY		   JAZZ-49993  Update reporting to support new data model
	*************************************************************/

	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to [fp].[FactReportingAPCharges].
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to [fp].[FactReportingAPCharges], where SQL will then replicate
	-- to Snowflake. 
	--
	-- It's also important to note that this functionality is currently only availible on demand and is not automatically synced.
	-- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. 
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics

	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#SRC') IS NOT NULL DROP TABLE #SRC
	IF OBJECT_ID('tempdb..#history') IS NOT NULL DROP TABLE #history

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	DECLARE @FiscalYearID SMALLINT
	SELECT @FiscalYearID = FiscalYearID FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		ServiceLineID INT,
		PatientClassID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		ChargeCodeID INT,
		FiscalYearID SMALLINT,

		ServiceEntityID INT,
		MSDRGID INT,
		UBRevCodeID INT,
		PrimaryCPTID INT,
		ServiceProviderID INT,
		ServiceProviderSpecialtyID INT,
		PerformingProviderID INT,
		PerformingProviderSpecialtyID INT,
		BillingCPTID INT,
		
		ActualDollars01 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars02 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars03 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars04 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars05 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars06 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars07 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars08 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars09 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars10 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars11 DECIMAL(19, 8) DEFAULT(0),
		ActualDollars12 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars01 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars02 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars03 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars04 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars05 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars06 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars07 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars08 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars09 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars10 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars11 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars12 DECIMAL(19, 8) DEFAULT(0),

		ActualUnits01 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits02 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits03 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits04 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits05 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits06 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits07 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits08 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits09 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits10 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits11 DECIMAL(19, 8) DEFAULT(0),
		ActualUnits12 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits01 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits02 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits03 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits04 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits05 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits06 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits07 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits08 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits09 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits10 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits11 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits12 DECIMAL(19, 8) DEFAULT(0),

		InitialUnits01 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits02 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits03 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits04 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits05 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits06 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits07 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits08 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits09 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits10 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits11 DECIMAL(19, 8) DEFAULT(0),
		InitialUnits12 DECIMAL(19, 8) DEFAULT(0),
		
		InitialDollars01 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars02 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars03 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars04 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars05 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars06 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars07 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars08 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars09 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars10 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars11 DECIMAL(19, 8) DEFAULT(0),
		InitialDollars12 DECIMAL(19, 8) DEFAULT(0)
	)

	-- Populate Targeting
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If targeting is empty we need all departments
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.ChargeVolume 
		WHERE BudgetConfigID = @BudgetConfigID
	END

	-- Populate #history temp table, this way we only need to do the main filtering and JOINs once rather than once per time class
	SELECT
		cv.BudgetConfigID,
		cv.EntityID, 
		cv.DepartmentID, 
		cv.ServiceLineID, 
		cv.PatientClassID, 
		cv.AgeCohortID, 
		cv.MedicalSurgicalID, 
		cv.ChargeCodeID, 
		cv.ServiceEntityID,
		cv.MSDRGID,
		cv.UBRevCodeID,
		cv.PrimaryCPTID,
		cv.ServiceProviderID,
		cv.ServiceProviderSpecialtyID,
		cv.PerformingProviderID,
		cv.PerformingProviderSpecialtyID,
		cv.BillingCPTID,

		hist.ActualYTDValue01 AS ActualYTDUnits01, 
		hist.ActualYTDValue02 AS ActualYTDUnits02, 
		hist.ActualYTDValue03 AS ActualYTDUnits03, 
		hist.ActualYTDValue04 AS ActualYTDUnits04, 
		hist.ActualYTDValue05 AS ActualYTDUnits05, 
		hist.ActualYTDValue06 AS ActualYTDUnits06, 
		hist.ActualYTDValue07 AS ActualYTDUnits07, 
		hist.ActualYTDValue08 AS ActualYTDUnits08,
		hist.ActualYTDValue09 AS ActualYTDUnits09, 
		hist.ActualYTDValue10 AS ActualYTDUnits10, 
		hist.ActualYTDValue11 AS ActualYTDUnits11, 
		hist.ActualYTDValue12 AS ActualYTDUnits12,
		hist.ActualYTDValueTotal AS ActualYTDUnitsTotal,
		hist.ActualYTDDollarValue01 AS ActualYTDDollars01, 
		hist.ActualYTDDollarValue02 AS ActualYTDDollars02, 
		hist.ActualYTDDollarValue03 AS ActualYTDDollars03, 
		hist.ActualYTDDollarValue04 AS ActualYTDDollars04, 
		hist.ActualYTDDollarValue05 AS ActualYTDDollars05, 
		hist.ActualYTDDollarValue06 AS ActualYTDDollars06, 
		hist.ActualYTDDollarValue07 AS ActualYTDDollars07, 
		hist.ActualYTDDollarValue08 AS ActualYTDDollars08,
		hist.ActualYTDDollarValue09 AS ActualYTDDollars09, 
		hist.ActualYTDDollarValue10 AS ActualYTDDollars10, 
		hist.ActualYTDDollarValue11 AS ActualYTDDollars11, 
		hist.ActualYTDDollarValue12 AS ActualYTDDollars12,
		hist.ActualYTDDollarValueTotal AS ActualYTDDollarsTotal,
		
		hist.PriorYearActualValue01 AS PriorYearActualUnits01, 
		hist.PriorYearActualValue02 AS PriorYearActualUnits02, 
		hist.PriorYearActualValue03 AS PriorYearActualUnits03, 
		hist.PriorYearActualValue04 AS PriorYearActualUnits04, 
		hist.PriorYearActualValue05 AS PriorYearActualUnits05, 
		hist.PriorYearActualValue06 AS PriorYearActualUnits06, 
		hist.PriorYearActualValue07 AS PriorYearActualUnits07, 
		hist.PriorYearActualValue08 AS PriorYearActualUnits08,
		hist.PriorYearActualValue09 AS PriorYearActualUnits09, 
		hist.PriorYearActualValue10 AS PriorYearActualUnits10, 
		hist.PriorYearActualValue11 AS PriorYearActualUnits11, 
		hist.PriorYearActualValue12 AS PriorYearActualUnits12,
		hist.PriorYearActualValueTotal AS PriorYearActualUnitsTotal,
		hist.PriorYearActualDollarValue01 AS PriorYearActualDollars01, 
		hist.PriorYearActualDollarValue02 AS PriorYearActualDollars02, 
		hist.PriorYearActualDollarValue03 AS PriorYearActualDollars03, 
		hist.PriorYearActualDollarValue04 AS PriorYearActualDollars04, 
		hist.PriorYearActualDollarValue05 AS PriorYearActualDollars05, 
		hist.PriorYearActualDollarValue06 AS PriorYearActualDollars06, 
		hist.PriorYearActualDollarValue07 AS PriorYearActualDollars07, 
		hist.PriorYearActualDollarValue08 AS PriorYearActualDollars08,
		hist.PriorYearActualDollarValue09 AS PriorYearActualDollars09, 
		hist.PriorYearActualDollarValue10 AS PriorYearActualDollars10, 
		hist.PriorYearActualDollarValue11 AS PriorYearActualDollars11, 
		hist.PriorYearActualDollarValue12 AS PriorYearActualDollars12,
		hist.PriorYearActualDollarValueTotal AS PriorYearActualDollarsTotal,
		
		hist.CurrentYearBudget01 AS CurrentYearBudgetUnits01, 
		hist.CurrentYearBudget02 AS CurrentYearBudgetUnits02, 
		hist.CurrentYearBudget03 AS CurrentYearBudgetUnits03, 
		hist.CurrentYearBudget04 AS CurrentYearBudgetUnits04, 
		hist.CurrentYearBudget05 AS CurrentYearBudgetUnits05, 
		hist.CurrentYearBudget06 AS CurrentYearBudgetUnits06, 
		hist.CurrentYearBudget07 AS CurrentYearBudgetUnits07, 
		hist.CurrentYearBudget08 AS CurrentYearBudgetUnits08,
		hist.CurrentYearBudget09 AS CurrentYearBudgetUnits09, 
		hist.CurrentYearBudget10 AS CurrentYearBudgetUnits10, 
		hist.CurrentYearBudget11 AS CurrentYearBudgetUnits11, 
		hist.CurrentYearBudget12 AS CurrentYearBudgetUnits12,
		hist.CurrentYearBudgetTotal AS CurrentYearBudgetUnitsTotal,
		hist.CurrentYearBudgetDollar01 AS CurrentYearBudgetDollars01, 
		hist.CurrentYearBudgetDollar02 AS CurrentYearBudgetDollars02, 
		hist.CurrentYearBudgetDollar03 AS CurrentYearBudgetDollars03, 
		hist.CurrentYearBudgetDollar04 AS CurrentYearBudgetDollars04, 
		hist.CurrentYearBudgetDollar05 AS CurrentYearBudgetDollars05, 
		hist.CurrentYearBudgetDollar06 AS CurrentYearBudgetDollars06, 
		hist.CurrentYearBudgetDollar07 AS CurrentYearBudgetDollars07, 
		hist.CurrentYearBudgetDollar08 AS CurrentYearBudgetDollars08,
		hist.CurrentYearBudgetDollar09 AS CurrentYearBudgetDollars09, 
		hist.CurrentYearBudgetDollar10 AS CurrentYearBudgetDollars10, 
		hist.CurrentYearBudgetDollar11 AS CurrentYearBudgetDollars11, 
		hist.CurrentYearBudgetDollar12 AS CurrentYearBudgetDollars12,
		hist.CurrentYearBudgetDollarTotal AS CurrentYearBudgetDollarsTotal,

		cv.InitialBudget01 AS InitialUnits01, 
		cv.InitialBudget02 AS InitialUnits02, 
		cv.InitialBudget03 AS InitialUnits03, 
		cv.InitialBudget04 AS InitialUnits04, 
		cv.InitialBudget05 AS InitialUnits05, 
		cv.InitialBudget06 AS InitialUnits06, 
		cv.InitialBudget07 AS InitialUnits07, 
		cv.InitialBudget08 AS InitialUnits08,
		cv.InitialBudget09 AS InitialUnits09, 
		cv.InitialBudget10 AS InitialUnits10, 
		cv.InitialBudget11 AS InitialUnits11, 
		cv.InitialBudget12 AS InitialUnits12,
		cv.InitialBudgetTotal AS InitialUnitsTotal,

		cv.InitialBudgetDollars01 AS InitialDollars01, 
		cv.InitialBudgetDollars02 AS InitialDollars02, 
		cv.InitialBudgetDollars03 AS InitialDollars03, 
		cv.InitialBudgetDollars04 AS InitialDollars04, 
		cv.InitialBudgetDollars05 AS InitialDollars05, 
		cv.InitialBudgetDollars06 AS InitialDollars06, 
		cv.InitialBudgetDollars07 AS InitialDollars07, 
		cv.InitialBudgetDollars08 AS InitialDollars08,
		cv.InitialBudgetDollars09 AS InitialDollars09, 
		cv.InitialBudgetDollars10 AS InitialDollars10, 
		cv.InitialBudgetDollars11 AS InitialDollars11, 
		cv.InitialBudgetDollars12 AS InitialDollars12,
		cv.InitialBudgetDollarsTotal AS InitialDollarsTotal
	INTO #history
	FROM fp.ChargeVolume cv 
		INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID
		INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID
	WHERE cv.UnitTypeID = 145
	AND cv.BudgetConfigID = @BudgetConfigID

	-- Populating Baseline
	INSERT INTO #SRC (BudgetConfigID, EntityID,	DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
		ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
		BillingCPTID, FiscalYearID, 
		InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12,
		InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08, InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12)
	SELECT
		BudgetConfigID,
		EntityID, 
		DepartmentID, 
		ServiceLineID, 
		PatientClassID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		ChargeCodeID, 
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		@FiscalYearID AS FiscalYearID,
		InitialUnits01, 
		InitialUnits02, 
		InitialUnits03, 
		InitialUnits04, 
		InitialUnits05, 
		InitialUnits06, 
		InitialUnits07, 
		InitialUnits08,
		InitialUnits09, 
		InitialUnits10, 
		InitialUnits11, 
		InitialUnits12,
		InitialDollars01, 
		InitialDollars02, 
		InitialDollars03, 
		InitialDollars04, 
		InitialDollars05, 
		InitialDollars06, 
		InitialDollars07, 
		InitialDollars08,
		InitialDollars09, 
		InitialDollars10, 
		InitialDollars11, 
		InitialDollars12
	FROM #history
	-- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units
	WHERE 
		InitialUnitsTotal != 0 OR InitialDollarsTotal != 0
	 

	-- Populating Actual YTD
	-- Populating Current Year Budget
	INSERT INTO #SRC (BudgetConfigID, EntityID,	DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
		ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
		BillingCPTID, FiscalYearID, 
		ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12,
		ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12,
		BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12,
		BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12)
	SELECT
		BudgetConfigID,
		EntityID, 
		DepartmentID, 
		ServiceLineID, 
		PatientClassID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		ChargeCodeID, 
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		@FiscalYearID - 1 AS FiscalYearID,
		ActualYTDUnits01, 
		ActualYTDUnits02, 
		ActualYTDUnits03, 
		ActualYTDUnits04, 
		ActualYTDUnits05, 
		ActualYTDUnits06, 
		ActualYTDUnits07, 
		ActualYTDUnits08,
		ActualYTDUnits09, 
		ActualYTDUnits10, 
		ActualYTDUnits11, 
		ActualYTDUnits12,
		ActualYTDDollars01, 
		ActualYTDDollars02, 
		ActualYTDDollars03, 
		ActualYTDDollars04, 
		ActualYTDDollars05, 
		ActualYTDDollars06, 
		ActualYTDDollars07, 
		ActualYTDDollars08,
		ActualYTDDollars09, 
		ActualYTDDollars10, 
		ActualYTDDollars11, 
		ActualYTDDollars12,
		CurrentYearBudgetUnits01, 
		CurrentYearBudgetUnits02, 
		CurrentYearBudgetUnits03, 
		CurrentYearBudgetUnits04, 
		CurrentYearBudgetUnits05, 
		CurrentYearBudgetUnits06, 
		CurrentYearBudgetUnits07, 
		CurrentYearBudgetUnits08,
		CurrentYearBudgetUnits09, 
		CurrentYearBudgetUnits10, 
		CurrentYearBudgetUnits11, 
		CurrentYearBudgetUnits12,
		CurrentYearBudgetDollars01, 
		CurrentYearBudgetDollars02, 
		CurrentYearBudgetDollars03, 
		CurrentYearBudgetDollars04, 
		CurrentYearBudgetDollars05, 
		CurrentYearBudgetDollars06, 
		CurrentYearBudgetDollars07, 
		CurrentYearBudgetDollars08,
		CurrentYearBudgetDollars09, 
		CurrentYearBudgetDollars10, 
		CurrentYearBudgetDollars11, 
		CurrentYearBudgetDollars12
	FROM #history
	-- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units
	WHERE 
		((ActualYTDUnitsTotal != 0 OR ActualYTDDollarsTotal != 0) OR
		(CurrentYearBudgetUnitsTotal != 0 OR CurrentYearBudgetDollarsTotal != 0))
		
	-- Populating Prior Year Actuals
	INSERT INTO #SRC (BudgetConfigID, EntityID,	DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
		ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
		BillingCPTID, FiscalYearID, 
		ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12,
		ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12)
	SELECT
		BudgetConfigID,
		EntityID, 
		DepartmentID, 
		ServiceLineID, 
		PatientClassID, 
		AgeCohortID, 
		MedicalSurgicalID, 
		ChargeCodeID, 
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		@FiscalYearID - 2 AS FiscalYearID,
		PriorYearActualUnits01, 
		PriorYearActualUnits02, 
		PriorYearActualUnits03, 
		PriorYearActualUnits04, 
		PriorYearActualUnits05, 
		PriorYearActualUnits06, 
		PriorYearActualUnits07, 
		PriorYearActualUnits08,
		PriorYearActualUnits09, 
		PriorYearActualUnits10, 
		PriorYearActualUnits11, 
		PriorYearActualUnits12,
		PriorYearActualDollars01, 
		PriorYearActualDollars02, 
		PriorYearActualDollars03, 
		PriorYearActualDollars04, 
		PriorYearActualDollars05, 
		PriorYearActualDollars06, 
		PriorYearActualDollars07, 
		PriorYearActualDollars08,
		PriorYearActualDollars09, 
		PriorYearActualDollars10, 
		PriorYearActualDollars11, 
		PriorYearActualDollars12
	FROM #history
	-- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units
	WHERE
		PriorYearActualUnitsTotal != 0 OR PriorYearActualDollarsTotal != 0
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT 
			'#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, 
			PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID
			BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, 
			BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08,	BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12,
			ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, 
			ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08,	ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12,
			InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, 
			InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08,	InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12
		FROM #SRC;
				
		RETURN
	END

	-- Publish the data from the temp table to fp.FactReportingAPCharges. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    
	SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, 
			PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID,
			BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, 
			BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08,	BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12,
			ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, 
			ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08,	ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12
	INTO #HistorySRC
	FROM #SRC
	WHERE FiscalYearID < @FiscalYearID

	-- Historical Values
	;WITH TGT AS 
	(
		SELECT	
			EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, 
			PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID,
			BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, 
			BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08,	BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12,
			ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, 
			ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08,	ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12
		FROM [fp].[FactReportingAPCharges] FRS	
		WHERE FiscalYearID < @FiscalYearID
	)
	MERGE TGT AS target
	USING #HistorySRC AS source
		ON (
				target.EntityID							= source.EntityID
			AND target.DepartmentID						= source.DepartmentID
			AND target.ServiceLineID					= source.ServiceLineID
			AND target.PatientClassID					= source.PatientClassID
			AND target.AgeCohortID						= source.AgeCohortID
			AND target.MedicalSurgicalID				= source.MedicalSurgicalID
			AND target.ChargeCodeID						= source.ChargeCodeID
			AND target.ServiceEntityID					= source.ServiceEntityID
			AND target.MSDRGRollupID					= source.MSDRGID
			AND target.UBRevenueCodeID					= source.UBRevCodeID
			AND target.PrimaryCPTID						= source.PrimaryCPTID
			AND target.PhysicianID						= source.ServiceProviderID
			AND target.PhysicianSpecialtyID				= source.ServiceProviderSpecialtyID
			AND target.PerformingProviderID				= source.PerformingProviderID
			AND target.PerformingPhysicianSpecialtyID	= source.PerformingProviderSpecialtyID
			AND target.BilledCPTID						= source.BillingCPTID
			AND target.FiscalYearID						= source.FiscalYearID
			)
		WHEN MATCHED AND 
			(	
				target.BudgetDollars01 <> source.BudgetDollars01
			 OR target.BudgetDollars02 <> source.BudgetDollars02
			 OR target.BudgetDollars03 <> source.BudgetDollars03
			 OR target.BudgetDollars04 <> source.BudgetDollars04
			 OR target.BudgetDollars05 <> source.BudgetDollars05
			 OR target.BudgetDollars06 <> source.BudgetDollars06
			 OR target.BudgetDollars07 <> source.BudgetDollars07
			 OR target.BudgetDollars08 <> source.BudgetDollars08
			 OR target.BudgetDollars09 <> source.BudgetDollars09
			 OR target.BudgetDollars10 <> source.BudgetDollars10
			 OR target.BudgetDollars11 <> source.BudgetDollars11
			 OR target.BudgetDollars12 <> source.BudgetDollars12

			 OR	target.ActualDollars01 <> source.ActualDollars01
			 OR target.ActualDollars02 <> source.ActualDollars02
			 OR target.ActualDollars03 <> source.ActualDollars03
			 OR target.ActualDollars04 <> source.ActualDollars04
			 OR target.ActualDollars05 <> source.ActualDollars05
			 OR target.ActualDollars06 <> source.ActualDollars06
			 OR target.ActualDollars07 <> source.ActualDollars07
			 OR target.ActualDollars08 <> source.ActualDollars08
			 OR target.ActualDollars09 <> source.ActualDollars09
			 OR target.ActualDollars10 <> source.ActualDollars10
			 OR target.ActualDollars11 <> source.ActualDollars11
			 OR target.ActualDollars12 <> source.ActualDollars12

			 OR	target.BudgetUnits01 <> source.BudgetUnits01
			 OR target.BudgetUnits02 <> source.BudgetUnits02
			 OR target.BudgetUnits03 <> source.BudgetUnits03
			 OR target.BudgetUnits04 <> source.BudgetUnits04
			 OR target.BudgetUnits05 <> source.BudgetUnits05
			 OR target.BudgetUnits06 <> source.BudgetUnits06
			 OR target.BudgetUnits07 <> source.BudgetUnits07
			 OR target.BudgetUnits08 <> source.BudgetUnits08
			 OR target.BudgetUnits09 <> source.BudgetUnits09
			 OR target.BudgetUnits10 <> source.BudgetUnits10
			 OR target.BudgetUnits11 <> source.BudgetUnits11
			 OR target.BudgetUnits12 <> source.BudgetUnits12

			 OR	target.ActualUnits01 <> source.ActualUnits01
			 OR target.ActualUnits02 <> source.ActualUnits02
			 OR target.ActualUnits03 <> source.ActualUnits03
			 OR target.ActualUnits04 <> source.ActualUnits04
			 OR target.ActualUnits05 <> source.ActualUnits05
			 OR target.ActualUnits06 <> source.ActualUnits06
			 OR target.ActualUnits07 <> source.ActualUnits07
			 OR target.ActualUnits08 <> source.ActualUnits08
			 OR target.ActualUnits09 <> source.ActualUnits09
			 OR target.ActualUnits10 <> source.ActualUnits10
			 OR target.ActualUnits11 <> source.ActualUnits11
			 OR target.ActualUnits12 <> source.ActualUnits12
			 )
		THEN
			UPDATE SET
				target.BudgetDollars01 = ISNULL(source.BudgetDollars01, 0),
				target.BudgetDollars02 = ISNULL(source.BudgetDollars02, 0),
				target.BudgetDollars03 = ISNULL(source.BudgetDollars03, 0),
				target.BudgetDollars04 = ISNULL(source.BudgetDollars04, 0),
				target.BudgetDollars05 = ISNULL(source.BudgetDollars05, 0),
				target.BudgetDollars06 = ISNULL(source.BudgetDollars06, 0),
				target.BudgetDollars07 = ISNULL(source.BudgetDollars07, 0),
				target.BudgetDollars08 = ISNULL(source.BudgetDollars08, 0),
				target.BudgetDollars09 = ISNULL(source.BudgetDollars09, 0),
				target.BudgetDollars10 = ISNULL(source.BudgetDollars10, 0),
				target.BudgetDollars11 = ISNULL(source.BudgetDollars11, 0),
				target.BudgetDollars12 = ISNULL(source.BudgetDollars12, 0),
				
				target.ActualDollars01 = ISNULL(source.ActualDollars01, 0),
				target.ActualDollars02 = ISNULL(source.ActualDollars02, 0),
				target.ActualDollars03 = ISNULL(source.ActualDollars03, 0),
				target.ActualDollars04 = ISNULL(source.ActualDollars04, 0),
				target.ActualDollars05 = ISNULL(source.ActualDollars05, 0),
				target.ActualDollars06 = ISNULL(source.ActualDollars06, 0),
				target.ActualDollars07 = ISNULL(source.ActualDollars07, 0),
				target.ActualDollars08 = ISNULL(source.ActualDollars08, 0),
				target.ActualDollars09 = ISNULL(source.ActualDollars09, 0),
				target.ActualDollars10 = ISNULL(source.ActualDollars10, 0),
				target.ActualDollars11 = ISNULL(source.ActualDollars11, 0),
				target.ActualDollars12 = ISNULL(source.ActualDollars12, 0),

				target.BudgetUnits01 = ISNULL(source.BudgetUnits01, 0),
				target.BudgetUnits02 = ISNULL(source.BudgetUnits02, 0),
				target.BudgetUnits03 = ISNULL(source.BudgetUnits03, 0),
				target.BudgetUnits04 = ISNULL(source.BudgetUnits04, 0),
				target.BudgetUnits05 = ISNULL(source.BudgetUnits05, 0),
				target.BudgetUnits06 = ISNULL(source.BudgetUnits06, 0),
				target.BudgetUnits07 = ISNULL(source.BudgetUnits07, 0),
				target.BudgetUnits08 = ISNULL(source.BudgetUnits08, 0),
				target.BudgetUnits09 = ISNULL(source.BudgetUnits09, 0),
				target.BudgetUnits10 = ISNULL(source.BudgetUnits10, 0),
				target.BudgetUnits11 = ISNULL(source.BudgetUnits11, 0),
				target.BudgetUnits12 = ISNULL(source.BudgetUnits12, 0),

				target.ActualUnits01 = ISNULL(source.ActualUnits01, 0),
				target.ActualUnits02 = ISNULL(source.ActualUnits02, 0),
				target.ActualUnits03 = ISNULL(source.ActualUnits03, 0),
				target.ActualUnits04 = ISNULL(source.ActualUnits04, 0),
				target.ActualUnits05 = ISNULL(source.ActualUnits05, 0),
				target.ActualUnits06 = ISNULL(source.ActualUnits06, 0),
				target.ActualUnits07 = ISNULL(source.ActualUnits07, 0),
				target.ActualUnits08 = ISNULL(source.ActualUnits08, 0),
				target.ActualUnits09 = ISNULL(source.ActualUnits09, 0),
				target.ActualUnits10 = ISNULL(source.ActualUnits10, 0),
				target.ActualUnits11 = ISNULL(source.ActualUnits11, 0),
				target.ActualUnits12 = ISNULL(source.ActualUnits12, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, 
			PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID,
			BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, 
			BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08,	BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12,
			ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, 
			ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08,	ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12
				)
				VALUES (
					source.EntityID,
					source.DepartmentID,
					source.ServiceLineID,
					source.PatientClassID,
					source.AgeCohortID,
					source.MedicalSurgicalID,
					source.ChargeCodeID,
					source.ServiceEntityID,
					source.MSDRGID,
					source.UBRevCodeID,
					source.PrimaryCPTID,
					source.ServiceProviderID,
					source.ServiceProviderSpecialtyID,
					source.PerformingProviderID,
					source.PerformingProviderSpecialtyID,
					source.BillingCPTID,
					source.FiscalYearID,
					ISNULL(source.BudgetUnits01, 0),
					ISNULL(source.BudgetUnits02, 0),
					ISNULL(source.BudgetUnits03, 0),
					ISNULL(source.BudgetUnits04, 0),
					ISNULL(source.BudgetUnits05, 0),
					ISNULL(source.BudgetUnits06, 0),
					ISNULL(source.BudgetUnits07, 0),
					ISNULL(source.BudgetUnits08, 0),
					ISNULL(source.BudgetUnits09, 0),
					ISNULL(source.BudgetUnits10, 0),
					ISNULL(source.BudgetUnits11, 0),
					ISNULL(source.BudgetUnits12, 0),

					ISNULL(source.BudgetDollars01, 0),
					ISNULL(source.BudgetDollars02, 0),
					ISNULL(source.BudgetDollars03, 0),
					ISNULL(source.BudgetDollars04, 0),
					ISNULL(source.BudgetDollars05, 0),
					ISNULL(source.BudgetDollars06, 0),
					ISNULL(source.BudgetDollars07, 0),
					ISNULL(source.BudgetDollars08, 0),
					ISNULL(source.BudgetDollars09, 0),
					ISNULL(source.BudgetDollars10, 0),
					ISNULL(source.BudgetDollars11, 0),
					ISNULL(source.BudgetDollars12, 0),

					ISNULL(source.ActualUnits01, 0),
					ISNULL(source.ActualUnits02, 0),
					ISNULL(source.ActualUnits03, 0),
					ISNULL(source.ActualUnits04, 0),
					ISNULL(source.ActualUnits05, 0),
					ISNULL(source.ActualUnits06, 0),
					ISNULL(source.ActualUnits07, 0),
					ISNULL(source.ActualUnits08, 0),
					ISNULL(source.ActualUnits09, 0),
					ISNULL(source.ActualUnits10, 0),
					ISNULL(source.ActualUnits11, 0),
					ISNULL(source.ActualUnits12, 0),

					ISNULL(source.ActualDollars01, 0),
					ISNULL(source.ActualDollars02, 0),
					ISNULL(source.ActualDollars03, 0),
					ISNULL(source.ActualDollars04, 0),
					ISNULL(source.ActualDollars05, 0),
					ISNULL(source.ActualDollars06, 0),
					ISNULL(source.ActualDollars07, 0),
					ISNULL(source.ActualDollars08, 0),
					ISNULL(source.ActualDollars09, 0),
					ISNULL(source.ActualDollars10, 0),
					ISNULL(source.ActualDollars11, 0),
					ISNULL(source.ActualDollars12, 0)
				);


	SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, 
			PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID,
			InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, 
			InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08,	InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12
	INTO #BaselineSRC
	FROM #SRC
	WHERE FiscalYearID = @FiscalYearID

	-- Initial baseline, we need to do these seperately, otherwise when running the baseline row will wipe out Target/Budget
	;WITH TGT AS 
	(
		SELECT	
			EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, 
			PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID,
			InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, 
			InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08,	InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12
		FROM [fp].[FactReportingAPCharges] FRS	
		WHERE FiscalYearID = @FiscalYearID
	)
	MERGE TGT AS target
	USING #BaselineSRC AS source
		ON (
				target.EntityID							= source.EntityID
			AND target.DepartmentID						= source.DepartmentID
			AND target.ServiceLineID					= source.ServiceLineID
			AND target.PatientClassID					= source.PatientClassID
			AND target.AgeCohortID						= source.AgeCohortID
			AND target.MedicalSurgicalID				= source.MedicalSurgicalID
			AND target.ChargeCodeID						= source.ChargeCodeID
			AND target.ServiceEntityID					= source.ServiceEntityID
			AND target.MSDRGRollupID					= source.MSDRGID
			AND target.UBRevenueCodeID					= source.UBRevCodeID
			AND target.PrimaryCPTID						= source.PrimaryCPTID
			AND target.PhysicianID						= source.ServiceProviderID
			AND target.PhysicianSpecialtyID				= source.ServiceProviderSpecialtyID
			AND target.PerformingProviderID				= source.PerformingProviderID
			AND target.PerformingPhysicianSpecialtyID	= source.PerformingProviderSpecialtyID
			AND target.BilledCPTID						= source.BillingCPTID
			AND target.FiscalYearID						= source.FiscalYearID
			)
		WHEN MATCHED AND 
			(	
			 	target.InitialDollars01 <> source.InitialDollars01
			 OR target.InitialDollars02 <> source.InitialDollars02
			 OR target.InitialDollars03 <> source.InitialDollars03
			 OR target.InitialDollars04 <> source.InitialDollars04
			 OR target.InitialDollars05 <> source.InitialDollars05
			 OR target.InitialDollars06 <> source.InitialDollars06
			 OR target.InitialDollars07 <> source.InitialDollars07
			 OR target.InitialDollars08 <> source.InitialDollars08
			 OR target.InitialDollars09 <> source.InitialDollars09
			 OR target.InitialDollars10 <> source.InitialDollars10
			 OR target.InitialDollars11 <> source.InitialDollars11
			 OR target.InitialDollars12 <> source.InitialDollars12

			 OR	target.InitialUnits01 <> source.InitialUnits01
			 OR target.InitialUnits02 <> source.InitialUnits02
			 OR target.InitialUnits03 <> source.InitialUnits03
			 OR target.InitialUnits04 <> source.InitialUnits04
			 OR target.InitialUnits05 <> source.InitialUnits05
			 OR target.InitialUnits06 <> source.InitialUnits06
			 OR target.InitialUnits07 <> source.InitialUnits07
			 OR target.InitialUnits08 <> source.InitialUnits08
			 OR target.InitialUnits09 <> source.InitialUnits09
			 OR target.InitialUnits10 <> source.InitialUnits10
			 OR target.InitialUnits11 <> source.InitialUnits11
			 OR target.InitialUnits12 <> source.InitialUnits12
			 )
		THEN
			UPDATE SET

				target.InitialDollars01 = ISNULL(source.InitialDollars01, 0),
				target.InitialDollars02 = ISNULL(source.InitialDollars02, 0),
				target.InitialDollars03 = ISNULL(source.InitialDollars03, 0),
				target.InitialDollars04 = ISNULL(source.InitialDollars04, 0),
				target.InitialDollars05 = ISNULL(source.InitialDollars05, 0),
				target.InitialDollars06 = ISNULL(source.InitialDollars06, 0),
				target.InitialDollars07 = ISNULL(source.InitialDollars07, 0),
				target.InitialDollars08 = ISNULL(source.InitialDollars08, 0),
				target.InitialDollars09 = ISNULL(source.InitialDollars09, 0),
				target.InitialDollars10 = ISNULL(source.InitialDollars10, 0),
				target.InitialDollars11 = ISNULL(source.InitialDollars11, 0),
				target.InitialDollars12 = ISNULL(source.InitialDollars12, 0),

				target.InitialUnits01 = ISNULL(source.InitialUnits01, 0),
				target.InitialUnits02 = ISNULL(source.InitialUnits02, 0),
				target.InitialUnits03 = ISNULL(source.InitialUnits03, 0),
				target.InitialUnits04 = ISNULL(source.InitialUnits04, 0),
				target.InitialUnits05 = ISNULL(source.InitialUnits05, 0),
				target.InitialUnits06 = ISNULL(source.InitialUnits06, 0),
				target.InitialUnits07 = ISNULL(source.InitialUnits07, 0),
				target.InitialUnits08 = ISNULL(source.InitialUnits08, 0),
				target.InitialUnits09 = ISNULL(source.InitialUnits09, 0),
				target.InitialUnits10 = ISNULL(source.InitialUnits10, 0),
				target.InitialUnits11 = ISNULL(source.InitialUnits11, 0),
				target.InitialUnits12 = ISNULL(source.InitialUnits12, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, 
			PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID,
			InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, 
			InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08,	InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12
				)
				VALUES (
					source.EntityID,
					source.DepartmentID,
					source.ServiceLineID,
					source.PatientClassID,
					source.AgeCohortID,
					source.MedicalSurgicalID,
					source.ChargeCodeID,
					source.ServiceEntityID,
					source.MSDRGID,
					source.UBRevCodeID,
					source.PrimaryCPTID,
					source.ServiceProviderID,
					source.ServiceProviderSpecialtyID,
					source.PerformingProviderID,
					source.PerformingProviderSpecialtyID,
					source.BillingCPTID,
					source.FiscalYearID,
										
					ISNULL(source.InitialUnits01, 0),
					ISNULL(source.InitialUnits02, 0),
					ISNULL(source.InitialUnits03, 0),
					ISNULL(source.InitialUnits04, 0),
					ISNULL(source.InitialUnits05, 0),
					ISNULL(source.InitialUnits06, 0),
					ISNULL(source.InitialUnits07, 0),
					ISNULL(source.InitialUnits08, 0),
					ISNULL(source.InitialUnits09, 0),
					ISNULL(source.InitialUnits10, 0),
					ISNULL(source.InitialUnits11, 0),
					ISNULL(source.InitialUnits12, 0),

					ISNULL(source.InitialDollars01, 0),
					ISNULL(source.InitialDollars02, 0),
					ISNULL(source.InitialDollars03, 0),
					ISNULL(source.InitialDollars04, 0),
					ISNULL(source.InitialDollars05, 0),
					ISNULL(source.InitialDollars06, 0),
					ISNULL(source.InitialDollars07, 0),
					ISNULL(source.InitialDollars08, 0),
					ISNULL(source.InitialDollars09, 0),
					ISNULL(source.InitialDollars10, 0),
					ISNULL(source.InitialDollars11, 0),
					ISNULL(source.InitialDollars12, 0)
				);
END
GO


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

-- fp.procFactChargeVolumeToReportingTransfer
CREATE   PROCEDURE [fp].[procFactChargeVolumeToReportingTransfer]  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2021-12-27   MD        JAZZ-29138  Initial Creation
	** 2    2022-06-01   MY        JAZZ-33343  Fix Missing Charge Code Join
	** 3    2022-06-03   MY        JAZZ-33343  Update Data Source to Pivoted
	** 4    2022-06-29   BW        JAZZ-39340  Switching from MSDRGID to MSDRGRollupID
	** 5    2022-12-20   MD        JAZZ-47250  Make sure dollars without units are brought over
	** 6    2023-02-23   MY        JAZZ-49629  Handing zeroing out for AA data marts
	** 7	2023-03-21	 MY		   JAZZ-49993  Update reporting to support new data model
	*************************************************************/

	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to [fp].[FactReportingAPCharges].
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to [fp].[FactReportingAPCharges], where SQL will then replicate
	-- to Snowflake. 
	--
	-- It's also important to note that this functionality is currently only availible on demand and is not automatically synced.
	-- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. 
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics

	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#SRC') IS NOT NULL DROP TABLE #SRC

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	DECLARE @FiscalYearID SMALLINT
	SELECT @FiscalYearID = FiscalYearID FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		ServiceLineID INT,
		PatientClassID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		ChargeCodeID INT,
		FiscalYearID SMALLINT,

		ServiceEntityID INT,
		MSDRGID INT,
		UBRevCodeID INT,
		PrimaryCPTID INT,
		ServiceProviderID INT,
		ServiceProviderSpecialtyID INT,
		PerformingProviderID INT,
		PerformingProviderSpecialtyID INT,
		BillingCPTID INT,

		BudgetDollars01 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars02 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars03 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars04 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars05 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars06 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars07 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars08 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars09 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars10 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars11 DECIMAL(19, 8) DEFAULT(0),
		BudgetDollars12 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars01 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars02 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars03 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars04 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars05 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars06 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars07 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars08 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars09 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars10 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars11 DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars12 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars01 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars02 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars03 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars04 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars05 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars06 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars07 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars08 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars09 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars10 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars11 DECIMAL(19, 8) DEFAULT(0),
		TargetDollars12 DECIMAL(19, 8) DEFAULT(0),

		BudgetUnits01 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits02 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits03 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits04 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits05 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits06 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits07 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits08 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits09 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits10 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits11 DECIMAL(19, 8) DEFAULT(0),
		BudgetUnits12 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits01 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits02 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits03 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits04 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits05 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits06 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits07 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits08 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits09 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits10 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits11 DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits12 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits01 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits02 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits03 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits04 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits05 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits06 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits07 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits08 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits09 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits10 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits11 DECIMAL(19, 8) DEFAULT(0),
		TargetUnits12 DECIMAL(19, 8) DEFAULT(0)
	)

	-- Populate Targeting
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If targeting is empty we need all departments
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.ChargeVolume 
		WHERE BudgetConfigID = @BudgetConfigID
	END

	-- Populating Target/Budget Values.
	INSERT INTO #SRC (BudgetConfigID, EntityID,	DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
		ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
		BillingCPTID, FiscalYearID, 
		TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12,
		BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12,
		TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12,
		BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12)
	SELECT
		cv.BudgetConfigID,
		cv.EntityID, 
		cv.DepartmentID, 
		cv.ServiceLineID, 
		cv.PatientClassID, 
		cv.AgeCohortID, 
		cv.MedicalSurgicalID, 
		cv.ChargeCodeID, 
		cv.ServiceEntityID,
		cv.MSDRGID,
		cv.UBRevCodeID,
		cv.PrimaryCPTID,
		cv.ServiceProviderID,
		cv.ServiceProviderSpecialtyID,
		cv.PerformingProviderID,
		cv.PerformingProviderSpecialtyID,
		cv.BillingCPTID,
		@FiscalYearID AS FiscalYearID,
		cv.TargetAdjusted01 AS TargetUnits01, 
		cv.TargetAdjusted02 AS TargetUnits02, 
		cv.TargetAdjusted03 AS TargetUnits03, 
		cv.TargetAdjusted04 AS TargetUnits04, 
		cv.TargetAdjusted05 AS TargetUnits05, 
		cv.TargetAdjusted06 AS TargetUnits06, 
		cv.TargetAdjusted07 AS TargetUnits07, 
		cv.TargetAdjusted08 AS TargetUnits08,
		cv.TargetAdjusted09 AS TargetUnits09, 
		cv.TargetAdjusted10 AS TargetUnits10, 
		cv.TargetAdjusted11 AS TargetUnits11, 
		cv.TargetAdjusted12 AS TargetUnits12,
		cv.BudgetAdjusted01 AS BudgetUnits01, 
		cv.BudgetAdjusted02 AS BudgetUnits02, 
		cv.BudgetAdjusted03 AS BudgetUnits03, 
		cv.BudgetAdjusted04 AS BudgetUnits04, 
		cv.BudgetAdjusted05 AS BudgetUnits05, 
		cv.BudgetAdjusted06 AS BudgetUnits06, 
		cv.BudgetAdjusted07 AS BudgetUnits07, 
		cv.BudgetAdjusted08 AS BudgetUnits08,
		cv.BudgetAdjusted09 AS BudgetUnits09, 
		cv.BudgetAdjusted10 AS BudgetUnits10, 
		cv.BudgetAdjusted11 AS BudgetUnits11, 
		cv.BudgetAdjusted12 AS BudgetUnits12,
		cv.TargetDollarsAdjusted01 AS TargetDollars01, 
		cv.TargetDollarsAdjusted02 AS TargetDollars02, 
		cv.TargetDollarsAdjusted03 AS TargetDollars03, 
		cv.TargetDollarsAdjusted04 AS TargetDollars04, 
		cv.TargetDollarsAdjusted05 AS TargetDollars05, 
		cv.TargetDollarsAdjusted06 AS TargetDollars06, 
		cv.TargetDollarsAdjusted07 AS TargetDollars07, 
		cv.TargetDollarsAdjusted08 AS TargetDollars08,
		cv.TargetDollarsAdjusted09 AS TargetDollars09, 
		cv.TargetDollarsAdjusted10 AS TargetDollars10, 
		cv.TargetDollarsAdjusted11 AS TargetDollars11, 
		cv.TargetDollarsAdjusted12 AS TargetDollars12,
		cv.BudgetDollarsAdjusted01 AS BudgetDollars01, 
		cv.BudgetDollarsAdjusted02 AS BudgetDollars02, 
		cv.BudgetDollarsAdjusted03 AS BudgetDollars03, 
		cv.BudgetDollarsAdjusted04 AS BudgetDollars04, 
		cv.BudgetDollarsAdjusted05 AS BudgetDollars05, 
		cv.BudgetDollarsAdjusted06 AS BudgetDollars06, 
		cv.BudgetDollarsAdjusted07 AS BudgetDollars07, 
		cv.BudgetDollarsAdjusted08 AS BudgetDollars08,
		cv.BudgetDollarsAdjusted09 AS BudgetDollars09, 
		cv.BudgetDollarsAdjusted10 AS BudgetDollars10, 
		cv.BudgetDollarsAdjusted11 AS BudgetDollars11, 
		cv.BudgetDollarsAdjusted12 AS BudgetDollars12
	FROM fp.ChargeVolume cv 
		INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID
	WHERE cv.UnitTypeID = 145
	AND cv.BudgetConfigID = @BudgetConfigID
	-- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units
	AND ((cv.TargetAdjustedTotal != 0 OR cv.TargetDollarsAdjustedTotal != 0)
	OR (cv.BudgetAdjustedTotal != 0 OR cv.BudgetDollarsAdjustedTotal != 0))


	-- Populating Projection Values
	INSERT INTO #SRC (BudgetConfigID, EntityID,	DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID,
		ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
		BillingCPTID, FiscalYearID, 
		ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12,
		ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12)
	SELECT
		cv.BudgetConfigID,
		cv.EntityID, 
		cv.DepartmentID, 
		cv.ServiceLineID, 
		cv.PatientClassID, 
		cv.AgeCohortID, 
		cv.MedicalSurgicalID, 
		cv.ChargeCodeID, 
		cv.ServiceEntityID,
		cv.MSDRGID,
		cv.UBRevCodeID,
		cv.PrimaryCPTID,
		cv.ServiceProviderID,
		cv.ServiceProviderSpecialtyID,
		cv.PerformingProviderID,
		cv.PerformingProviderSpecialtyID,
		cv.BillingCPTID,
		@FiscalYearID - 1 AS FiscalYearID,
		cv.ProjectionAdjusted01 AS ProjectedUnits01, 
		cv.ProjectionAdjusted02 AS ProjectedUnits02, 
		cv.ProjectionAdjusted03 AS ProjectedUnits03, 
		cv.ProjectionAdjusted04 AS ProjectedUnits04, 
		cv.ProjectionAdjusted05 AS ProjectedUnits05, 
		cv.ProjectionAdjusted06 AS ProjectedUnits06, 
		cv.ProjectionAdjusted07 AS ProjectedUnits07, 
		cv.ProjectionAdjusted08 AS ProjectedUnits08,
		cv.ProjectionAdjusted09 AS ProjectedUnits09, 
		cv.ProjectionAdjusted10 AS ProjectedUnits10, 
		cv.ProjectionAdjusted11 AS ProjectedUnits11, 
		cv.ProjectionAdjusted12 AS ProjectedUnits12,
		cv.ProjectionDollarsAdjusted01 AS ProjectedDollars01, 
		cv.ProjectionDollarsAdjusted02 AS ProjectedDollars02, 
		cv.ProjectionDollarsAdjusted03 AS ProjectedDollars03, 
		cv.ProjectionDollarsAdjusted04 AS ProjectedDollars04, 
		cv.ProjectionDollarsAdjusted05 AS ProjectedDollars05, 
		cv.ProjectionDollarsAdjusted06 AS ProjectedDollars06, 
		cv.ProjectionDollarsAdjusted07 AS ProjectedDollars07, 
		cv.ProjectionDollarsAdjusted08 AS ProjectedDollars08,
		cv.ProjectionDollarsAdjusted09 AS ProjectedDollars09, 
		cv.ProjectionDollarsAdjusted10 AS ProjectedDollars10, 
		cv.ProjectionDollarsAdjusted11 AS ProjectedDollars11, 
		cv.ProjectionDollarsAdjusted12 AS ProjectedDollars12
	FROM fp.ChargeVolume cv 
		INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID
	WHERE cv.UnitTypeID = 145
	AND cv.BudgetConfigID = @BudgetConfigID
	-- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units
	AND (cv.ProjectionAdjustedTotal != 0 OR cv.ProjectionDollarsAdjustedTotal != 0)

	IF (@IsDebug = 1)
	BEGIN
		SELECT 
			'#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, 
			PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID
			BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, 
			ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12, 
			TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12, 
			BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, 
			ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12, 
			TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12
		FROM #SRC;
		
		RETURN
	END

	-- Publish the data from the temp table to fp.FactReportingAPCharges. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- NOTE: We don't handle DELETES here as there shouldn't ever be a reason to delete the data
	;WITH TGT AS 
	(
		SELECT	
			EntityID, FRS.DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
			ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, 
			PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID,
			BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, 
			ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12, 
			TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12, 
			BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, 
			ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12, 
			TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12
		FROM [fp].[FactReportingAPCharges] FRS	
			INNER JOIN #FilterByDepartment dept ON FRS.DepartmentID = dept.DepartmentID
	)
	MERGE TGT AS target
	USING #SRC AS source
		ON (
				target.EntityID							= source.EntityID
			AND target.DepartmentID						= source.DepartmentID
			AND target.ServiceLineID					= source.ServiceLineID
			AND target.PatientClassID					= source.PatientClassID
			AND target.AgeCohortID						= source.AgeCohortID
			AND target.MedicalSurgicalID				= source.MedicalSurgicalID
			AND target.ChargeCodeID						= source.ChargeCodeID
			AND target.ServiceEntityID					= source.ServiceEntityID
			AND target.MSDRGRollupID					= source.MSDRGID
			AND target.UBRevenueCodeID					= source.UBRevCodeID
			AND target.PrimaryCPTID						= source.PrimaryCPTID
			AND target.PhysicianID						= source.ServiceProviderID
			AND target.PhysicianSpecialtyID				= source.ServiceProviderSpecialtyID
			AND target.PerformingProviderID				= source.PerformingProviderID
			AND target.PerformingPhysicianSpecialtyID	= source.PerformingProviderSpecialtyID
			AND target.BilledCPTID						= source.BillingCPTID
			AND target.FiscalYearID						= source.FiscalYearID
			)
		WHEN MATCHED AND 
			(	
				target.BudgetDollars01 <> source.BudgetDollars01
			 OR target.BudgetDollars02 <> source.BudgetDollars02
			 OR target.BudgetDollars03 <> source.BudgetDollars03
			 OR target.BudgetDollars04 <> source.BudgetDollars04
			 OR target.BudgetDollars05 <> source.BudgetDollars05
			 OR target.BudgetDollars06 <> source.BudgetDollars06
			 OR target.BudgetDollars07 <> source.BudgetDollars07
			 OR target.BudgetDollars08 <> source.BudgetDollars08
			 OR target.BudgetDollars09 <> source.BudgetDollars09
			 OR target.BudgetDollars10 <> source.BudgetDollars10
			 OR target.BudgetDollars11 <> source.BudgetDollars11
			 OR target.BudgetDollars12 <> source.BudgetDollars12

			 OR	target.ProjectedDollars01 <> source.ProjectedDollars01
			 OR target.ProjectedDollars02 <> source.ProjectedDollars02
			 OR target.ProjectedDollars03 <> source.ProjectedDollars03
			 OR target.ProjectedDollars04 <> source.ProjectedDollars04
			 OR target.ProjectedDollars05 <> source.ProjectedDollars05
			 OR target.ProjectedDollars06 <> source.ProjectedDollars06
			 OR target.ProjectedDollars07 <> source.ProjectedDollars07
			 OR target.ProjectedDollars08 <> source.ProjectedDollars08
			 OR target.ProjectedDollars09 <> source.ProjectedDollars09
			 OR target.ProjectedDollars10 <> source.ProjectedDollars10
			 OR target.ProjectedDollars11 <> source.ProjectedDollars11
			 OR target.ProjectedDollars12 <> source.ProjectedDollars12

			 OR	target.TargetDollars01 <> source.TargetDollars01
			 OR target.TargetDollars02 <> source.TargetDollars02
			 OR target.TargetDollars03 <> source.TargetDollars03
			 OR target.TargetDollars04 <> source.TargetDollars04
			 OR target.TargetDollars05 <> source.TargetDollars05
			 OR target.TargetDollars06 <> source.TargetDollars06
			 OR target.TargetDollars07 <> source.TargetDollars07
			 OR target.TargetDollars08 <> source.TargetDollars08
			 OR target.TargetDollars09 <> source.TargetDollars09
			 OR target.TargetDollars10 <> source.TargetDollars10
			 OR target.TargetDollars11 <> source.TargetDollars11
			 OR target.TargetDollars12 <> source.TargetDollars12

			 OR	target.BudgetUnits01 <> source.BudgetUnits01
			 OR target.BudgetUnits02 <> source.BudgetUnits02
			 OR target.BudgetUnits03 <> source.BudgetUnits03
			 OR target.BudgetUnits04 <> source.BudgetUnits04
			 OR target.BudgetUnits05 <> source.BudgetUnits05
			 OR target.BudgetUnits06 <> source.BudgetUnits06
			 OR target.BudgetUnits07 <> source.BudgetUnits07
			 OR target.BudgetUnits08 <> source.BudgetUnits08
			 OR target.BudgetUnits09 <> source.BudgetUnits09
			 OR target.BudgetUnits10 <> source.BudgetUnits10
			 OR target.BudgetUnits11 <> source.BudgetUnits11
			 OR target.BudgetUnits12 <> source.BudgetUnits12

			 OR	target.ProjectedUnits01 <> source.ProjectedUnits01
			 OR target.ProjectedUnits02 <> source.ProjectedUnits02
			 OR target.ProjectedUnits03 <> source.ProjectedUnits03
			 OR target.ProjectedUnits04 <> source.ProjectedUnits04
			 OR target.ProjectedUnits05 <> source.ProjectedUnits05
			 OR target.ProjectedUnits06 <> source.ProjectedUnits06
			 OR target.ProjectedUnits07 <> source.ProjectedUnits07
			 OR target.ProjectedUnits08 <> source.ProjectedUnits08
			 OR target.ProjectedUnits09 <> source.ProjectedUnits09
			 OR target.ProjectedUnits10 <> source.ProjectedUnits10
			 OR target.ProjectedUnits11 <> source.ProjectedUnits11
			 OR target.ProjectedUnits12 <> source.ProjectedUnits12

			 OR	target.TargetUnits01 <> source.TargetUnits01
			 OR target.TargetUnits02 <> source.TargetUnits02
			 OR target.TargetUnits03 <> source.TargetUnits03
			 OR target.TargetUnits04 <> source.TargetUnits04
			 OR target.TargetUnits05 <> source.TargetUnits05
			 OR target.TargetUnits06 <> source.TargetUnits06
			 OR target.TargetUnits07 <> source.TargetUnits07
			 OR target.TargetUnits08 <> source.TargetUnits08
			 OR target.TargetUnits09 <> source.TargetUnits09
			 OR target.TargetUnits10 <> source.TargetUnits10
			 OR target.TargetUnits11 <> source.TargetUnits11
			 OR target.TargetUnits12 <> source.TargetUnits12
			 )
		THEN
			UPDATE SET
				target.BudgetDollars01 = ISNULL(source.BudgetDollars01, 0),
				target.BudgetDollars02 = ISNULL(source.BudgetDollars02, 0),
				target.BudgetDollars03 = ISNULL(source.BudgetDollars03, 0),
				target.BudgetDollars04 = ISNULL(source.BudgetDollars04, 0),
				target.BudgetDollars05 = ISNULL(source.BudgetDollars05, 0),
				target.BudgetDollars06 = ISNULL(source.BudgetDollars06, 0),
				target.BudgetDollars07 = ISNULL(source.BudgetDollars07, 0),
				target.BudgetDollars08 = ISNULL(source.BudgetDollars08, 0),
				target.BudgetDollars09 = ISNULL(source.BudgetDollars09, 0),
				target.BudgetDollars10 = ISNULL(source.BudgetDollars10, 0),
				target.BudgetDollars11 = ISNULL(source.BudgetDollars11, 0),
				target.BudgetDollars12 = ISNULL(source.BudgetDollars12, 0),
				
				target.ProjectedDollars01 = ISNULL(source.ProjectedDollars01, 0),
				target.ProjectedDollars02 = ISNULL(source.ProjectedDollars02, 0),
				target.ProjectedDollars03 = ISNULL(source.ProjectedDollars03, 0),
				target.ProjectedDollars04 = ISNULL(source.ProjectedDollars04, 0),
				target.ProjectedDollars05 = ISNULL(source.ProjectedDollars05, 0),
				target.ProjectedDollars06 = ISNULL(source.ProjectedDollars06, 0),
				target.ProjectedDollars07 = ISNULL(source.ProjectedDollars07, 0),
				target.ProjectedDollars08 = ISNULL(source.ProjectedDollars08, 0),
				target.ProjectedDollars09 = ISNULL(source.ProjectedDollars09, 0),
				target.ProjectedDollars10 = ISNULL(source.ProjectedDollars10, 0),
				target.ProjectedDollars11 = ISNULL(source.ProjectedDollars11, 0),
				target.ProjectedDollars12 = ISNULL(source.ProjectedDollars12, 0),
								
				target.TargetDollars01 = ISNULL(source.TargetDollars01, 0),
				target.TargetDollars02 = ISNULL(source.TargetDollars02, 0),
				target.TargetDollars03 = ISNULL(source.TargetDollars03, 0),
				target.TargetDollars04 = ISNULL(source.TargetDollars04, 0),
				target.TargetDollars05 = ISNULL(source.TargetDollars05, 0),
				target.TargetDollars06 = ISNULL(source.TargetDollars06, 0),
				target.TargetDollars07 = ISNULL(source.TargetDollars07, 0),
				target.TargetDollars08 = ISNULL(source.TargetDollars08, 0),
				target.TargetDollars09 = ISNULL(source.TargetDollars09, 0),
				target.TargetDollars10 = ISNULL(source.TargetDollars10, 0),
				target.TargetDollars11 = ISNULL(source.TargetDollars11, 0),
				target.TargetDollars12 = ISNULL(source.TargetDollars12, 0),
				
				target.BudgetUnits01 = ISNULL(source.BudgetUnits01, 0),
				target.BudgetUnits02 = ISNULL(source.BudgetUnits02, 0),
				target.BudgetUnits03 = ISNULL(source.BudgetUnits03, 0),
				target.BudgetUnits04 = ISNULL(source.BudgetUnits04, 0),
				target.BudgetUnits05 = ISNULL(source.BudgetUnits05, 0),
				target.BudgetUnits06 = ISNULL(source.BudgetUnits06, 0),
				target.BudgetUnits07 = ISNULL(source.BudgetUnits07, 0),
				target.BudgetUnits08 = ISNULL(source.BudgetUnits08, 0),
				target.BudgetUnits09 = ISNULL(source.BudgetUnits09, 0),
				target.BudgetUnits10 = ISNULL(source.BudgetUnits10, 0),
				target.BudgetUnits11 = ISNULL(source.BudgetUnits11, 0),
				target.BudgetUnits12 = ISNULL(source.BudgetUnits12, 0),
				
				target.ProjectedUnits01 = ISNULL(source.ProjectedUnits01, 0),
				target.ProjectedUnits02 = ISNULL(source.ProjectedUnits02, 0),
				target.ProjectedUnits03 = ISNULL(source.ProjectedUnits03, 0),
				target.ProjectedUnits04 = ISNULL(source.ProjectedUnits04, 0),
				target.ProjectedUnits05 = ISNULL(source.ProjectedUnits05, 0),
				target.ProjectedUnits06 = ISNULL(source.ProjectedUnits06, 0),
				target.ProjectedUnits07 = ISNULL(source.ProjectedUnits07, 0),
				target.ProjectedUnits08 = ISNULL(source.ProjectedUnits08, 0),
				target.ProjectedUnits09 = ISNULL(source.ProjectedUnits09, 0),
				target.ProjectedUnits10 = ISNULL(source.ProjectedUnits10, 0),
				target.ProjectedUnits11 = ISNULL(source.ProjectedUnits11, 0),
				target.ProjectedUnits12 = ISNULL(source.ProjectedUnits12, 0),
				
				target.TargetUnits01 = ISNULL(source.TargetUnits01, 0),
				target.TargetUnits02 = ISNULL(source.TargetUnits02, 0),
				target.TargetUnits03 = ISNULL(source.TargetUnits03, 0),
				target.TargetUnits04 = ISNULL(source.TargetUnits04, 0),
				target.TargetUnits05 = ISNULL(source.TargetUnits05, 0),
				target.TargetUnits06 = ISNULL(source.TargetUnits06, 0),
				target.TargetUnits07 = ISNULL(source.TargetUnits07, 0),
				target.TargetUnits08 = ISNULL(source.TargetUnits08, 0),
				target.TargetUnits09 = ISNULL(source.TargetUnits09, 0),
				target.TargetUnits10 = ISNULL(source.TargetUnits10, 0),
				target.TargetUnits11 = ISNULL(source.TargetUnits11, 0),
				target.TargetUnits12 = ISNULL(source.TargetUnits12, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, 
					ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, 
					PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID,
					BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, 
					ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12, 
					TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12, 
					BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, 
					ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12, 
					TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12
				)
				VALUES (
					source.EntityID,
					source.DepartmentID,
					source.ServiceLineID,
					source.PatientClassID,
					source.AgeCohortID,
					source.MedicalSurgicalID,
					source.ChargeCodeID,
					source.ServiceEntityID,
					source.MSDRGID,
					source.UBRevCodeID,
					source.PrimaryCPTID,
					source.ServiceProviderID,
					source.ServiceProviderSpecialtyID,
					source.PerformingProviderID,
					source.PerformingProviderSpecialtyID,
					source.BillingCPTID,
					source.FiscalYearID,
					ISNULL(source.BudgetDollars01, 0),
					ISNULL(source.BudgetDollars02, 0),
					ISNULL(source.BudgetDollars03, 0),
					ISNULL(source.BudgetDollars04, 0),
					ISNULL(source.BudgetDollars05, 0),
					ISNULL(source.BudgetDollars06, 0),
					ISNULL(source.BudgetDollars07, 0),
					ISNULL(source.BudgetDollars08, 0),
					ISNULL(source.BudgetDollars09, 0),
					ISNULL(source.BudgetDollars10, 0),
					ISNULL(source.BudgetDollars11, 0),
					ISNULL(source.BudgetDollars12, 0),
					ISNULL(source.ProjectedDollars01, 0),
					ISNULL(source.ProjectedDollars02, 0),
					ISNULL(source.ProjectedDollars03, 0),
					ISNULL(source.ProjectedDollars04, 0),
					ISNULL(source.ProjectedDollars05, 0),
					ISNULL(source.ProjectedDollars06, 0),
					ISNULL(source.ProjectedDollars07, 0),
					ISNULL(source.ProjectedDollars08, 0),
					ISNULL(source.ProjectedDollars09, 0),
					ISNULL(source.ProjectedDollars10, 0),
					ISNULL(source.ProjectedDollars11, 0),
					ISNULL(source.ProjectedDollars12, 0),
					ISNULL(source.TargetDollars01, 0),
					ISNULL(source.TargetDollars02, 0),
					ISNULL(source.TargetDollars03, 0),
					ISNULL(source.TargetDollars04, 0),
					ISNULL(source.TargetDollars05, 0),
					ISNULL(source.TargetDollars06, 0),
					ISNULL(source.TargetDollars07, 0),
					ISNULL(source.TargetDollars08, 0),
					ISNULL(source.TargetDollars09, 0),
					ISNULL(source.TargetDollars10, 0),
					ISNULL(source.TargetDollars11, 0),
					ISNULL(source.TargetDollars12, 0),
					ISNULL(source.BudgetUnits01, 0),
					ISNULL(source.BudgetUnits02, 0),
					ISNULL(source.BudgetUnits03, 0),
					ISNULL(source.BudgetUnits04, 0),
					ISNULL(source.BudgetUnits05, 0),
					ISNULL(source.BudgetUnits06, 0),
					ISNULL(source.BudgetUnits07, 0),
					ISNULL(source.BudgetUnits08, 0),
					ISNULL(source.BudgetUnits09, 0),
					ISNULL(source.BudgetUnits10, 0),
					ISNULL(source.BudgetUnits11, 0),
					ISNULL(source.BudgetUnits12, 0),
					ISNULL(source.ProjectedUnits01, 0),
					ISNULL(source.ProjectedUnits02, 0),
					ISNULL(source.ProjectedUnits03, 0),
					ISNULL(source.ProjectedUnits04, 0),
					ISNULL(source.ProjectedUnits05, 0),
					ISNULL(source.ProjectedUnits06, 0),
					ISNULL(source.ProjectedUnits07, 0),
					ISNULL(source.ProjectedUnits08, 0),
					ISNULL(source.ProjectedUnits09, 0),
					ISNULL(source.ProjectedUnits10, 0),
					ISNULL(source.ProjectedUnits11, 0),
					ISNULL(source.ProjectedUnits12, 0),
					ISNULL(source.TargetUnits01, 0),
					ISNULL(source.TargetUnits02, 0),
					ISNULL(source.TargetUnits03, 0),
					ISNULL(source.TargetUnits04, 0),
					ISNULL(source.TargetUnits05, 0),
					ISNULL(source.TargetUnits06, 0),
					ISNULL(source.TargetUnits07, 0),
					ISNULL(source.TargetUnits08, 0),
					ISNULL(source.TargetUnits09, 0),
					ISNULL(source.TargetUnits10, 0),
					ISNULL(source.TargetUnits11, 0),
					ISNULL(source.TargetUnits12, 0)
				);

	-------------------------------------------------------------------------------------------------------
	-- JAZZ-49629 : Handing zeroing out for AA data marts
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above.
	-------------------------------------------------------------------------------------------------------
	
	-- Get all records that were adjusted
	SELECT DISTINCT chg.ChargeVolumeID
	INTO #adjustedRecords
	FROM [fp].[ChargeVolumeChangeHistory] chg
		INNER JOIN [fp].[ChargeVolume] fgl ON chg.ChargeVolumeID = fgl.ChargeVolumeID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
	WHERE chg.BudgetConfigID = @BudgetConfigID
	
	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	SELECT
		cv.BudgetConfigID,
		cv.EntityID, 
		cv.DepartmentID, 
		cv.ServiceLineID, 
		cv.PatientClassID, 
		cv.AgeCohortID, 
		cv.MedicalSurgicalID, 
		cv.ChargeCodeID, 
		cv.ServiceEntityID,
		cv.MSDRGID,
		cv.UBRevCodeID,
		cv.PrimaryCPTID,
		cv.ServiceProviderID,
		cv.ServiceProviderSpecialtyID,
		cv.PerformingProviderID,
		cv.PerformingProviderSpecialtyID,
		cv.BillingCPTID,
		cv.TargetAdjusted01 AS TargetUnits01, 
		cv.TargetAdjusted02 AS TargetUnits02, 
		cv.TargetAdjusted03 AS TargetUnits03, 
		cv.TargetAdjusted04 AS TargetUnits04, 
		cv.TargetAdjusted05 AS TargetUnits05, 
		cv.TargetAdjusted06 AS TargetUnits06, 
		cv.TargetAdjusted07 AS TargetUnits07, 
		cv.TargetAdjusted08 AS TargetUnits08,
		cv.TargetAdjusted09 AS TargetUnits09, 
		cv.TargetAdjusted10 AS TargetUnits10, 
		cv.TargetAdjusted11 AS TargetUnits11, 
		cv.TargetAdjusted12 AS TargetUnits12,
		cv.BudgetAdjusted01 AS BudgetUnits01, 
		cv.BudgetAdjusted02 AS BudgetUnits02, 
		cv.BudgetAdjusted03 AS BudgetUnits03, 
		cv.BudgetAdjusted04 AS BudgetUnits04, 
		cv.BudgetAdjusted05 AS BudgetUnits05, 
		cv.BudgetAdjusted06 AS BudgetUnits06, 
		cv.BudgetAdjusted07 AS BudgetUnits07, 
		cv.BudgetAdjusted08 AS BudgetUnits08,
		cv.BudgetAdjusted09 AS BudgetUnits09, 
		cv.BudgetAdjusted10 AS BudgetUnits10, 
		cv.BudgetAdjusted11 AS BudgetUnits11, 
		cv.BudgetAdjusted12 AS BudgetUnits12,
		cv.ProjectionAdjusted01 AS ProjectionUnits01, 
		cv.ProjectionAdjusted02 AS ProjectionUnits02, 
		cv.ProjectionAdjusted03 AS ProjectionUnits03, 
		cv.ProjectionAdjusted04 AS ProjectionUnits04, 
		cv.ProjectionAdjusted05 AS ProjectionUnits05, 
		cv.ProjectionAdjusted06 AS ProjectionUnits06, 
		cv.ProjectionAdjusted07 AS ProjectionUnits07, 
		cv.ProjectionAdjusted08 AS ProjectionUnits08,
		cv.ProjectionAdjusted09 AS ProjectionUnits09, 
		cv.ProjectionAdjusted10 AS ProjectionUnits10, 
		cv.ProjectionAdjusted11 AS ProjectionUnits11, 
		cv.ProjectionAdjusted12 AS ProjectionUnits12,
		cv.TargetDollarsAdjusted01 AS TargetDollars01, 
		cv.TargetDollarsAdjusted02 AS TargetDollars02, 
		cv.TargetDollarsAdjusted03 AS TargetDollars03, 
		cv.TargetDollarsAdjusted04 AS TargetDollars04, 
		cv.TargetDollarsAdjusted05 AS TargetDollars05, 
		cv.TargetDollarsAdjusted06 AS TargetDollars06, 
		cv.TargetDollarsAdjusted07 AS TargetDollars07, 
		cv.TargetDollarsAdjusted08 AS TargetDollars08,
		cv.TargetDollarsAdjusted09 AS TargetDollars09, 
		cv.TargetDollarsAdjusted10 AS TargetDollars10, 
		cv.TargetDollarsAdjusted11 AS TargetDollars11, 
		cv.TargetDollarsAdjusted12 AS TargetDollars12,
		cv.BudgetDollarsAdjusted01 AS BudgetDollars01, 
		cv.BudgetDollarsAdjusted02 AS BudgetDollars02, 
		cv.BudgetDollarsAdjusted03 AS BudgetDollars03, 
		cv.BudgetDollarsAdjusted04 AS BudgetDollars04, 
		cv.BudgetDollarsAdjusted05 AS BudgetDollars05, 
		cv.BudgetDollarsAdjusted06 AS BudgetDollars06, 
		cv.BudgetDollarsAdjusted07 AS BudgetDollars07, 
		cv.BudgetDollarsAdjusted08 AS BudgetDollars08,
		cv.BudgetDollarsAdjusted09 AS BudgetDollars09, 
		cv.BudgetDollarsAdjusted10 AS BudgetDollars10, 
		cv.BudgetDollarsAdjusted11 AS BudgetDollars11, 
		cv.BudgetDollarsAdjusted12 AS BudgetDollars12,
		cv.ProjectionDollarsAdjusted01 AS ProjectionDollars01, 
		cv.ProjectionDollarsAdjusted02 AS ProjectionDollars02, 
		cv.ProjectionDollarsAdjusted03 AS ProjectionDollars03, 
		cv.ProjectionDollarsAdjusted04 AS ProjectionDollars04, 
		cv.ProjectionDollarsAdjusted05 AS ProjectionDollars05, 
		cv.ProjectionDollarsAdjusted06 AS ProjectionDollars06, 
		cv.ProjectionDollarsAdjusted07 AS ProjectionDollars07, 
		cv.ProjectionDollarsAdjusted08 AS ProjectionDollars08,
		cv.ProjectionDollarsAdjusted09 AS ProjectionDollars09, 
		cv.ProjectionDollarsAdjusted10 AS ProjectionDollars10, 
		cv.ProjectionDollarsAdjusted11 AS ProjectionDollars11, 
		cv.ProjectionDollarsAdjusted12 AS ProjectionDollars12
	INTO #tempUnpivoted
	FROM fp.ChargeVolume cv 
		INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID
		INNER JOIN #adjustedRecords adj ON cv.ChargeVolumeID = adj.ChargeVolumeID
	WHERE cv.UnitTypeID = 145
		AND cv.BudgetConfigID = @BudgetConfigID
		-- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units
		AND (
			   (cv.TargetAdjustedTotal = 0 OR cv.TargetDollarsAdjustedTotal = 0)
			OR (cv.BudgetAdjustedTotal = 0 OR cv.BudgetDollarsAdjustedTotal = 0)
			OR (cv.ProjectionAdjustedTotal = 0 OR cv.ProjectionDollarsAdjustedTotal = 0)
		)
	
	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		frgl.RowID,
		cv.TargetUnits01, 
		cv.TargetUnits02, 
		cv.TargetUnits03, 
		cv.TargetUnits04, 
		cv.TargetUnits05, 
		cv.TargetUnits06, 
		cv.TargetUnits07, 
		cv.TargetUnits08, 
		cv.TargetUnits09, 
		cv.TargetUnits10, 
		cv.TargetUnits11, 
		cv.TargetUnits12, 
		cv.BudgetUnits01, 
		cv.BudgetUnits02, 
		cv.BudgetUnits03, 
		cv.BudgetUnits04, 
		cv.BudgetUnits05, 
		cv.BudgetUnits06, 
		cv.BudgetUnits07, 
		cv.BudgetUnits08, 
		cv.BudgetUnits09, 
		cv.BudgetUnits10, 
		cv.BudgetUnits11, 
		cv.BudgetUnits12, 
		cv.ProjectionUnits01, 
		cv.ProjectionUnits02, 
		cv.ProjectionUnits03, 
		cv.ProjectionUnits04, 
		cv.ProjectionUnits05, 
		cv.ProjectionUnits06, 
		cv.ProjectionUnits07, 
		cv.ProjectionUnits08, 
		cv.ProjectionUnits09, 
		cv.ProjectionUnits10, 
		cv.ProjectionUnits11, 
		cv.ProjectionUnits12, 
		cv.TargetDollars01,
		cv.TargetDollars02,
		cv.TargetDollars03,
		cv.TargetDollars04,
		cv.TargetDollars05,
		cv.TargetDollars06,
		cv.TargetDollars07,
		cv.TargetDollars08,
		cv.TargetDollars09,
		cv.TargetDollars10,
		cv.TargetDollars11,
		cv.TargetDollars12,
		cv.BudgetDollars01,
		cv.BudgetDollars02,
		cv.BudgetDollars03,
		cv.BudgetDollars04,
		cv.BudgetDollars05,
		cv.BudgetDollars06,
		cv.BudgetDollars07,
		cv.BudgetDollars08,
		cv.BudgetDollars09,
		cv.BudgetDollars10,
		cv.BudgetDollars11,
		cv.BudgetDollars12,
		cv.ProjectionDollars01,
		cv.ProjectionDollars02,
		cv.ProjectionDollars03,
		cv.ProjectionDollars04,
		cv.ProjectionDollars05,
		cv.ProjectionDollars06,
		cv.ProjectionDollars07,
		cv.ProjectionDollars08,
		cv.ProjectionDollars09,
		cv.ProjectionDollars10,
		cv.ProjectionDollars11,
		cv.ProjectionDollars12
	INTO #dataToUpdate_Budget
	FROM [fp].[FactReportingAPCharges] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 						  =	frgl.EntityID 
			AND cv.DepartmentID 					  =	frgl.DepartmentID 
			AND cv.ServiceLineID 					  =	frgl.ServiceLineID 
			AND cv.PatientClassID 					  =	frgl.PatientClassID 
			AND cv.AgeCohortID 						  =	frgl.AgeCohortID 
			AND cv.MedicalSurgicalID 				  =	frgl.MedicalSurgicalID 
			AND cv.ChargeCodeID 					  =	frgl.ChargeCodeID 
			AND cv.ServiceEntityID					  =	frgl.ServiceEntityID
			AND cv.MSDRGID							  =	frgl.MSDRGRollupID
			AND cv.UBRevCodeID						  =	frgl.UBRevenueCodeID
			AND cv.PrimaryCPTID					      =	frgl.PrimaryCPTID
			AND cv.ServiceProviderID				  =	frgl.PhysicianID
			AND cv.ServiceProviderSpecialtyID		  =	frgl.PhysicianSpecialtyID
			AND cv.PerformingProviderID			      =	frgl.PerformingProviderID
			AND cv.PerformingProviderSpecialtyID	  =	frgl.PerformingPhysicianSpecialtyID
			AND cv.BillingCPTID					      =	frgl.BilledCPTID
			AND @FiscalYearID						  = frgl.FiscalYearID
	WHERE 1 = 1
		AND (
			   cv.TargetUnits01   != frgl.TargetUnits01
			OR cv.TargetUnits02   != frgl.TargetUnits02
			OR cv.TargetUnits03   != frgl.TargetUnits03
			OR cv.TargetUnits04   != frgl.TargetUnits04
			OR cv.TargetUnits05   != frgl.TargetUnits05
			OR cv.TargetUnits06   != frgl.TargetUnits06
			OR cv.TargetUnits07   != frgl.TargetUnits07
			OR cv.TargetUnits08   != frgl.TargetUnits08
			OR cv.TargetUnits09   != frgl.TargetUnits09
			OR cv.TargetUnits10   != frgl.TargetUnits10
			OR cv.TargetUnits11   != frgl.TargetUnits11
			OR cv.TargetUnits12   != frgl.TargetUnits12
			OR cv.BudgetUnits01   != frgl.BudgetUnits01
			OR cv.BudgetUnits02   != frgl.BudgetUnits02
			OR cv.BudgetUnits03   != frgl.BudgetUnits03
			OR cv.BudgetUnits04   != frgl.BudgetUnits04
			OR cv.BudgetUnits05   != frgl.BudgetUnits05
			OR cv.BudgetUnits06   != frgl.BudgetUnits06
			OR cv.BudgetUnits07   != frgl.BudgetUnits07
			OR cv.BudgetUnits08   != frgl.BudgetUnits08
			OR cv.BudgetUnits09   != frgl.BudgetUnits09
			OR cv.BudgetUnits10   != frgl.BudgetUnits10
			OR cv.BudgetUnits11   != frgl.BudgetUnits11
			OR cv.BudgetUnits12   != frgl.BudgetUnits12
			OR cv.TargetDollars01 != frgl.TargetDollars01
			OR cv.TargetDollars02 != frgl.TargetDollars02
			OR cv.TargetDollars03 != frgl.TargetDollars03
			OR cv.TargetDollars04 != frgl.TargetDollars04
			OR cv.TargetDollars05 != frgl.TargetDollars05
			OR cv.TargetDollars06 != frgl.TargetDollars06
			OR cv.TargetDollars07 != frgl.TargetDollars07
			OR cv.TargetDollars08 != frgl.TargetDollars08
			OR cv.TargetDollars09 != frgl.TargetDollars09
			OR cv.TargetDollars10 != frgl.TargetDollars10
			OR cv.TargetDollars11 != frgl.TargetDollars11
			OR cv.TargetDollars12 != frgl.TargetDollars12
			OR cv.BudgetDollars01 != frgl.BudgetDollars01
			OR cv.BudgetDollars02 != frgl.BudgetDollars02
			OR cv.BudgetDollars03 != frgl.BudgetDollars03
			OR cv.BudgetDollars04 != frgl.BudgetDollars04
			OR cv.BudgetDollars05 != frgl.BudgetDollars05
			OR cv.BudgetDollars06 != frgl.BudgetDollars06
			OR cv.BudgetDollars07 != frgl.BudgetDollars07
			OR cv.BudgetDollars08 != frgl.BudgetDollars08
			OR cv.BudgetDollars09 != frgl.BudgetDollars09
			OR cv.BudgetDollars10 != frgl.BudgetDollars10
			OR cv.BudgetDollars11 != frgl.BudgetDollars11
			OR cv.BudgetDollars12 != frgl.BudgetDollars12
		)	

		SELECT 
		frgl.RowID,
		cv.ProjectionUnits01, 
		cv.ProjectionUnits02, 
		cv.ProjectionUnits03, 
		cv.ProjectionUnits04, 
		cv.ProjectionUnits05, 
		cv.ProjectionUnits06, 
		cv.ProjectionUnits07, 
		cv.ProjectionUnits08, 
		cv.ProjectionUnits09, 
		cv.ProjectionUnits10, 
		cv.ProjectionUnits11, 
		cv.ProjectionUnits12, 
		cv.ProjectionDollars01,
		cv.ProjectionDollars02,
		cv.ProjectionDollars03,
		cv.ProjectionDollars04,
		cv.ProjectionDollars05,
		cv.ProjectionDollars06,
		cv.ProjectionDollars07,
		cv.ProjectionDollars08,
		cv.ProjectionDollars09,
		cv.ProjectionDollars10,
		cv.ProjectionDollars11,
		cv.ProjectionDollars12
	INTO #dataToUpdate_Projection
	FROM [fp].[FactReportingAPCharges] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 						  =	frgl.EntityID 
			AND cv.DepartmentID 					  =	frgl.DepartmentID 
			AND cv.ServiceLineID 					  =	frgl.ServiceLineID 
			AND cv.PatientClassID 					  =	frgl.PatientClassID 
			AND cv.AgeCohortID 						  =	frgl.AgeCohortID 
			AND cv.MedicalSurgicalID 				  =	frgl.MedicalSurgicalID 
			AND cv.ChargeCodeID 					  =	frgl.ChargeCodeID 
			AND cv.ServiceEntityID					  =	frgl.ServiceEntityID
			AND cv.MSDRGID							  =	frgl.MSDRGRollupID
			AND cv.UBRevCodeID						  =	frgl.UBRevenueCodeID
			AND cv.PrimaryCPTID					      =	frgl.PrimaryCPTID
			AND cv.ServiceProviderID				  =	frgl.PhysicianID
			AND cv.ServiceProviderSpecialtyID		  =	frgl.PhysicianSpecialtyID
			AND cv.PerformingProviderID			      =	frgl.PerformingProviderID
			AND cv.PerformingProviderSpecialtyID	  =	frgl.PerformingPhysicianSpecialtyID
			AND cv.BillingCPTID					      =	frgl.BilledCPTID
			AND @FiscalYearID - 1					  = frgl.FiscalYearID
	WHERE 1 = 1
		AND (
			   cv.ProjectionUnits01   != frgl.ProjectedUnits01
			OR cv.ProjectionUnits02   != frgl.ProjectedUnits02
			OR cv.ProjectionUnits03   != frgl.ProjectedUnits03
			OR cv.ProjectionUnits04   != frgl.ProjectedUnits04
			OR cv.ProjectionUnits05   != frgl.ProjectedUnits05
			OR cv.ProjectionUnits06   != frgl.ProjectedUnits06
			OR cv.ProjectionUnits07   != frgl.ProjectedUnits07
			OR cv.ProjectionUnits08   != frgl.ProjectedUnits08
			OR cv.ProjectionUnits09   != frgl.ProjectedUnits09
			OR cv.ProjectionUnits10   != frgl.ProjectedUnits10
			OR cv.ProjectionUnits11   != frgl.ProjectedUnits11
			OR cv.ProjectionUnits12   != frgl.ProjectedUnits12
			OR cv.ProjectionDollars01   != frgl.ProjectedDollars01
			OR cv.ProjectionDollars02   != frgl.ProjectedDollars02
			OR cv.ProjectionDollars03   != frgl.ProjectedDollars03
			OR cv.ProjectionDollars04   != frgl.ProjectedDollars04
			OR cv.ProjectionDollars05   != frgl.ProjectedDollars05
			OR cv.ProjectionDollars06   != frgl.ProjectedDollars06
			OR cv.ProjectionDollars07   != frgl.ProjectedDollars07
			OR cv.ProjectionDollars08   != frgl.ProjectedDollars08
			OR cv.ProjectionDollars09   != frgl.ProjectedDollars09
			OR cv.ProjectionDollars10   != frgl.ProjectedDollars10
			OR cv.ProjectionDollars11   != frgl.ProjectedDollars11
			OR cv.ProjectionDollars12   != frgl.ProjectedDollars12
		)	

	-- Update the records
	UPDATE report
	SET 
		report.TargetUnits01   = upd.TargetUnits01,
		report.TargetUnits02   = upd.TargetUnits02,
		report.TargetUnits03   = upd.TargetUnits03,
		report.TargetUnits04   = upd.TargetUnits04,
		report.TargetUnits05   = upd.TargetUnits05,
		report.TargetUnits06   = upd.TargetUnits06,
		report.TargetUnits07   = upd.TargetUnits07,
		report.TargetUnits08   = upd.TargetUnits08,
		report.TargetUnits09   = upd.TargetUnits09,
		report.TargetUnits10   = upd.TargetUnits10,
		report.TargetUnits11   = upd.TargetUnits11,
		report.TargetUnits12   = upd.TargetUnits12,
		report.BudgetUnits01   = upd.BudgetUnits01,
		report.BudgetUnits02   = upd.BudgetUnits02,
		report.BudgetUnits03   = upd.BudgetUnits03,
		report.BudgetUnits04   = upd.BudgetUnits04,
		report.BudgetUnits05   = upd.BudgetUnits05,
		report.BudgetUnits06   = upd.BudgetUnits06,
		report.BudgetUnits07   = upd.BudgetUnits07,
		report.BudgetUnits08   = upd.BudgetUnits08,
		report.BudgetUnits09   = upd.BudgetUnits09,
		report.BudgetUnits10   = upd.BudgetUnits10,
		report.BudgetUnits11   = upd.BudgetUnits11,
		report.BudgetUnits12   = upd.BudgetUnits12,
		report.TargetDollars01 = upd.TargetDollars01,
		report.TargetDollars02 = upd.TargetDollars02,
		report.TargetDollars03 = upd.TargetDollars03,
		report.TargetDollars04 = upd.TargetDollars04,
		report.TargetDollars05 = upd.TargetDollars05,
		report.TargetDollars06 = upd.TargetDollars06,
		report.TargetDollars07 = upd.TargetDollars07,
		report.TargetDollars08 = upd.TargetDollars08,
		report.TargetDollars09 = upd.TargetDollars09,
		report.TargetDollars10 = upd.TargetDollars10,
		report.TargetDollars11 = upd.TargetDollars11,
		report.TargetDollars12 = upd.TargetDollars12,
		report.BudgetDollars01 = upd.BudgetDollars01,
		report.BudgetDollars02 = upd.BudgetDollars02,
		report.BudgetDollars03 = upd.BudgetDollars03,
		report.BudgetDollars04 = upd.BudgetDollars04,
		report.BudgetDollars05 = upd.BudgetDollars05,
		report.BudgetDollars06 = upd.BudgetDollars06,
		report.BudgetDollars07 = upd.BudgetDollars07,
		report.BudgetDollars08 = upd.BudgetDollars08,
		report.BudgetDollars09 = upd.BudgetDollars09,
		report.BudgetDollars10 = upd.BudgetDollars10,
		report.BudgetDollars11 = upd.BudgetDollars11,
		report.BudgetDollars12 = upd.BudgetDollars12
	FROM [fp].[FactReportingAPCharges] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Budget upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND (
			   report.TargetUnits01   != upd.TargetUnits01
			OR report.TargetUnits02   != upd.TargetUnits02
			OR report.TargetUnits03   != upd.TargetUnits03
			OR report.TargetUnits04   != upd.TargetUnits04
			OR report.TargetUnits05   != upd.TargetUnits05
			OR report.TargetUnits06   != upd.TargetUnits06
			OR report.TargetUnits07   != upd.TargetUnits07
			OR report.TargetUnits08   != upd.TargetUnits08
			OR report.TargetUnits09   != upd.TargetUnits09
			OR report.TargetUnits10   != upd.TargetUnits10
			OR report.TargetUnits11   != upd.TargetUnits11
			OR report.TargetUnits12   != upd.TargetUnits12
			OR report.BudgetUnits01   != upd.BudgetUnits01
			OR report.BudgetUnits02   != upd.BudgetUnits02
			OR report.BudgetUnits03   != upd.BudgetUnits03
			OR report.BudgetUnits04   != upd.BudgetUnits04
			OR report.BudgetUnits05   != upd.BudgetUnits05
			OR report.BudgetUnits06   != upd.BudgetUnits06
			OR report.BudgetUnits07   != upd.BudgetUnits07
			OR report.BudgetUnits08   != upd.BudgetUnits08
			OR report.BudgetUnits09   != upd.BudgetUnits09
			OR report.BudgetUnits10   != upd.BudgetUnits10
			OR report.BudgetUnits11   != upd.BudgetUnits11
			OR report.BudgetUnits12   != upd.BudgetUnits12
			OR report.TargetDollars01 != upd.TargetDollars01
			OR report.TargetDollars02 != upd.TargetDollars02
			OR report.TargetDollars03 != upd.TargetDollars03
			OR report.TargetDollars04 != upd.TargetDollars04
			OR report.TargetDollars05 != upd.TargetDollars05
			OR report.TargetDollars06 != upd.TargetDollars06
			OR report.TargetDollars07 != upd.TargetDollars07
			OR report.TargetDollars08 != upd.TargetDollars08
			OR report.TargetDollars09 != upd.TargetDollars09
			OR report.TargetDollars10 != upd.TargetDollars10
			OR report.TargetDollars11 != upd.TargetDollars11
			OR report.TargetDollars12 != upd.TargetDollars12
			OR report.BudgetDollars01 != upd.BudgetDollars01
			OR report.BudgetDollars02 != upd.BudgetDollars02
			OR report.BudgetDollars03 != upd.BudgetDollars03
			OR report.BudgetDollars04 != upd.BudgetDollars04
			OR report.BudgetDollars05 != upd.BudgetDollars05
			OR report.BudgetDollars06 != upd.BudgetDollars06
			OR report.BudgetDollars07 != upd.BudgetDollars07
			OR report.BudgetDollars08 != upd.BudgetDollars08
			OR report.BudgetDollars09 != upd.BudgetDollars09
			OR report.BudgetDollars10 != upd.BudgetDollars10
			OR report.BudgetDollars11 != upd.BudgetDollars11
			OR report.BudgetDollars12 != upd.BudgetDollars12
		)

	
	UPDATE report
	SET 
		report.ProjectedUnits01   = upd.ProjectionUnits01,
		report.ProjectedUnits02   = upd.ProjectionUnits02,
		report.ProjectedUnits03   = upd.ProjectionUnits03,
		report.ProjectedUnits04   = upd.ProjectionUnits04,
		report.ProjectedUnits05   = upd.ProjectionUnits05,
		report.ProjectedUnits06   = upd.ProjectionUnits06,
		report.ProjectedUnits07   = upd.ProjectionUnits07,
		report.ProjectedUnits08   = upd.ProjectionUnits08,
		report.ProjectedUnits09   = upd.ProjectionUnits09,
		report.ProjectedUnits10   = upd.ProjectionUnits10,
		report.ProjectedUnits11   = upd.ProjectionUnits11,
		report.ProjectedUnits12   = upd.ProjectionUnits12,
		report.ProjectedDollars01 = upd.ProjectionDollars01,
		report.ProjectedDollars02 = upd.ProjectionDollars02,
		report.ProjectedDollars03 = upd.ProjectionDollars03,
		report.ProjectedDollars04 = upd.ProjectionDollars04,
		report.ProjectedDollars05 = upd.ProjectionDollars05,
		report.ProjectedDollars06 = upd.ProjectionDollars06,
		report.ProjectedDollars07 = upd.ProjectionDollars07,
		report.ProjectedDollars08 = upd.ProjectionDollars08,
		report.ProjectedDollars09 = upd.ProjectionDollars09,
		report.ProjectedDollars10 = upd.ProjectionDollars10,
		report.ProjectedDollars11 = upd.ProjectionDollars11,
		report.ProjectedDollars12 = upd.ProjectionDollars12
	FROM [fp].[FactReportingAPCharges] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Projection upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND (
			   report.ProjectedUnits01   != upd.ProjectionUnits01
			OR report.ProjectedUnits02   != upd.ProjectionUnits02
			OR report.ProjectedUnits03   != upd.ProjectionUnits03
			OR report.ProjectedUnits04   != upd.ProjectionUnits04
			OR report.ProjectedUnits05   != upd.ProjectionUnits05
			OR report.ProjectedUnits06   != upd.ProjectionUnits06
			OR report.ProjectedUnits07   != upd.ProjectionUnits07
			OR report.ProjectedUnits08   != upd.ProjectionUnits08
			OR report.ProjectedUnits09   != upd.ProjectionUnits09
			OR report.ProjectedUnits10   != upd.ProjectionUnits10
			OR report.ProjectedUnits11   != upd.ProjectionUnits11
			OR report.ProjectedUnits12   != upd.ProjectionUnits12
			OR report.ProjectedDollars01 != upd.ProjectionDollars01
			OR report.ProjectedDollars02 != upd.ProjectionDollars02
			OR report.ProjectedDollars03 != upd.ProjectionDollars03
			OR report.ProjectedDollars04 != upd.ProjectionDollars04
			OR report.ProjectedDollars05 != upd.ProjectionDollars05
			OR report.ProjectedDollars06 != upd.ProjectionDollars06
			OR report.ProjectedDollars07 != upd.ProjectionDollars07
			OR report.ProjectedDollars08 != upd.ProjectionDollars08
			OR report.ProjectedDollars09 != upd.ProjectionDollars09
			OR report.ProjectedDollars10 != upd.ProjectionDollars10
			OR report.ProjectedDollars11 != upd.ProjectionDollars11
			OR report.ProjectedDollars12 != upd.ProjectionDollars12
		)
END
GO


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

-- fp.procFactEncounterBaselineAndHistoryToReportingTransfer
CREATE   PROCEDURE [fp].[procFactEncounterBaselineAndHistoryToReportingTransfer]  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI         Description
	** 1    2021-12-09   BW        JAZZ-29137  Initial Creation
	** 2    2022-06-29   BW        JAZZ-39340  Switching from MSDRGID to MSDRGRollupID
	** 3    2022-07-18   MY        JAZZ-37944  Add Initial Baseline
	** 4	11-28-2022   MY        JAZZ-43418  Add FiscalTimeID to Update
	*************************************************************/
 
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAPEncounters.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAPEncounters, where SQL will then replicate
	-- to Snowflake. 
	--
	-- It's also important to note that this functionality is currently only availible on demand and is not automatically synced.
	-- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. 
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#encounterSource'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	DECLARE @FiscalYearID INT = (SELECT FiscalYearID FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID);

	CREATE TABLE #SRC (
		EntityID INT,
		DepartmentID INT,
		ServiceLineID INT,
		ServiceLineRollupID INT,
		PatientClassID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		PayorID INT,
		PayorGroupID INT,
		MSDRGID INT,
		CPTID INT,
		ProviderID INT,
		PhysicianSpecialtyID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		ActualEncountersYTD DECIMAL(19, 8),
		ActualEncounters DECIMAL(19, 8),
		BudgetEncounters DECIMAL(19, 8),
		InitialEncounters DECIMAL(19, 8)
	)

	SELECT
		EntityID,
		DepartmentID,
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		FiscalTimeID,
		Value
	INTO #encounterSource
	FROM [fp].[viewFactEncounterHistory_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.BudgetConfigID = @BudgetConfigID
	 	AND Value != 0 

	SELECT
		EntityID,
		DepartmentID,
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		FiscalTimeID,
		OriginalValue
	INTO #baselineEncounterSource
	FROM [fp].[viewFactEncounter_Unpivoted_BaselineOnly] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.BudgetConfigID = @BudgetConfigID
	 	AND OriginalValue != 0 
	
	CREATE CLUSTERED INDEX inx_stat ON #encounterSource (
		TimeClassID,
		EntityID,
		DepartmentID,		
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID		
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, ServiceLineID,	ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, 
	ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		DepartmentID,
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		FiscalMonthID,
		FiscalYearID, 
		FiscalTimeID
	FROM #encounterSource VW
	UNION ALL 
	SELECT DISTINCT
		EntityID, 
		DepartmentID,
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		FiscalMonthID,
		FiscalYearID, 
		FiscalTimeID
	FROM #baselineEncounterSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		FiscalMonthID,
		FiscalYearID, 
		FiscalTimeID	
	)			
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Initial Baseline
	UPDATE src
	SET
		InitialEncounters = ap.OriginalValue
	FROM #SRC src
		INNER JOIN #baselineEncounterSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.ServiceLineID = ap.ServiceLineID
			AND src.ServiceLineRollupID = ap.ServiceLineRollupID
			AND src.PatientClassID = ap.PatientClassID
			AND src.AgeCohortID = ap.AgeCohortID
			AND src.PatientClassID = ap.PatientClassID
			AND src.MedicalSurgicalID = ap.MedicalSurgicalID
			AND src.PayorID = ap.PayorID
			AND src.PayorGroupID = ap.PayorGroupID
			AND src.MSDRGID = ap.MSDRGID
			AND src.CPTID = ap.CPTID
			AND src.ProviderID = ap.ProviderID
			AND src.CPTID = ap.CPTID
			AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2
			AND ap.FiscalYearID = @FiscalYearID

	-- Update ActualYTD Encounters
	UPDATE src
	SET
		ActualEncountersYTD = ap.Value
	FROM #SRC src
		INNER JOIN #encounterSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.ServiceLineID = ap.ServiceLineID
			AND src.ServiceLineRollupID = ap.ServiceLineRollupID
			AND src.PatientClassID = ap.PatientClassID
			AND src.AgeCohortID = ap.AgeCohortID
			AND src.PatientClassID = ap.PatientClassID
			AND src.MedicalSurgicalID = ap.MedicalSurgicalID
			AND src.PayorID = ap.PayorID
			AND src.PayorGroupID = ap.PayorGroupID
			AND src.MSDRGID = ap.MSDRGID
			AND src.CPTID = ap.CPTID
			AND src.ProviderID = ap.ProviderID
			AND src.CPTID = ap.CPTID
			AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 1
			AND ap.FiscalYearID = @FiscalYearID - 1

	-- Update CurrentYearBudget Encounters
	UPDATE src
	SET
		BudgetEncounters = ap.Value
	FROM #SRC src
		INNER JOIN #encounterSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.ServiceLineID = ap.ServiceLineID
			AND src.ServiceLineRollupID = ap.ServiceLineRollupID
			AND src.PatientClassID = ap.PatientClassID
			AND src.AgeCohortID = ap.AgeCohortID
			AND src.PatientClassID = ap.PatientClassID
			AND src.MedicalSurgicalID = ap.MedicalSurgicalID
			AND src.PayorID = ap.PayorID
			AND src.PayorGroupID = ap.PayorGroupID
			AND src.MSDRGID = ap.MSDRGID
			AND src.CPTID = ap.CPTID
			AND src.ProviderID = ap.ProviderID
			AND src.CPTID = ap.CPTID
			AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2
			AND ap.FiscalYearID = @FiscalYearID - 1

	-- Update PriorYearActual Encounters
	UPDATE src
	SET
		ActualEncounters = ap.Value
	FROM #SRC src
		INNER JOIN #encounterSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.ServiceLineID = ap.ServiceLineID
			AND src.ServiceLineRollupID = ap.ServiceLineRollupID
			AND src.PatientClassID = ap.PatientClassID
			AND src.AgeCohortID = ap.AgeCohortID
			AND src.PatientClassID = ap.PatientClassID
			AND src.MedicalSurgicalID = ap.MedicalSurgicalID
			AND src.PayorID = ap.PayorID
			AND src.PayorGroupID = ap.PayorGroupID
			AND src.MSDRGID = ap.MSDRGID
			AND src.CPTID = ap.CPTID
			AND src.ProviderID = ap.ProviderID
			AND src.CPTID = ap.CPTID
			AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 1
			AND ap.FiscalYearID = @FiscalYearID - 2
	
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	--
	-- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until
	-- we add it so we don't re-introduce this bug.
	--
	-- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE
	-- EXISTING PROCS AND UPDATE IT FOR THIS.
	-------------------------------------------------------------------------------------------------------
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, 
			FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetEncounters, ActualEncountersYTD, ActualEncounters, InitalEncounters
		FROM #SRC 
		ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC, FiscalMonthID;
		
		SELECT '#encounterSource' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, 
			TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, Value
		FROM #encounterSource
		ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC, FiscalMonthID;
		
		SELECT '#baselineEncounterSource' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, 
			TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue
		FROM #baselineEncounterSource
		ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC, FiscalMonthID;

		RETURN
	END

	SELECT EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, 
		PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetEncounters, ActualEncountersYTD, ActualEncounters
	INTO #HistorySRC
	FROM #SRC
	WHERE FiscalYearID < @FiscalYearID
	
	-- Publish the data from the temp table to fp.FactReportingAPEncounters. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue

	-- Publish History First
	;WITH TGT AS 
	(
		SELECT EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, 
			PayorGroupID, MSDRGRollupID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetEncounters, ActualEncountersYTD, ActualEncounters, InitialEncounters 
		FROM [fp].[FactReportingAPEncounters] FRE

	)
			MERGE TGT AS target
			USING #HistorySRC AS source
				ON (
						target.EntityID			   = source.EntityID
						AND target.DepartmentID		   = source.DepartmentID
						AND target.ServiceLineID	   = source.ServiceLineID
						AND target.ServiceLineRollupID = source.ServiceLineRollupID
						AND target.PatientClassID	   = source.PatientClassID
						AND target.AgeCohortID		   = source.AgeCohortID
						AND target.MedicalSurgicalID   = source.MedicalSurgicalID
						AND target.PayorID			   = source.PayorID
						AND target.PayorGroupID		   = source.PayorGroupID
						AND target.MSDRGRollupID	   = source.MSDRGID
						AND target.CPTID			   = source.CPTID
						AND target.ProviderID		   = source.ProviderID
						AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID
						AND target.FiscalMonthID	   = source.FiscalMonthID
						AND target.FiscalYearID		   = source.FiscalYearID
						AND target.FiscalTimeID		   = source.FiscalTimeID

						)
			WHEN MATCHED AND (
				target.BudgetEncounters <> source.BudgetEncounters
				OR target.ActualEncountersYTD <> source.ActualEncountersYTD 
				OR target.ActualEncounters <> source.ActualEncounters )
				THEN
				UPDATE SET
				target.BudgetEncounters = ISNULL(source.BudgetEncounters, 0),
				target.ActualEncountersYTD = ISNULL(source.ActualEncountersYTD, 0),
				target.ActualEncounters = ISNULL(source.ActualEncounters, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
							  EntityID
							, DepartmentID
							, ServiceLineID
							, ServiceLineRollupID
							, PatientClassID
							, AgeCohortID
							, MedicalSurgicalID
							, PayorID
							, PayorGroupID
							, MSDRGRollupID
							, CPTID
							, ProviderID
							, PhysicianSpecialtyID
							, FiscalMonthID
							, FiscalYearID
							, FiscalTimeID
							, BudgetEncounters 
							, ActualEncountersYTD
							, ActualEncounters
						)
					VALUES (
						  source.EntityID
						, source.DepartmentID
						, source.ServiceLineID
						, source.ServiceLineRollupID
						, source.PatientClassID
						, source.AgeCohortID
						, source.MedicalSurgicalID
						, source.PayorID
						, source.PayorGroupID
						, source.MSDRGID
						, source.CPTID
						, source.ProviderID
						, source.PhysicianSpecialtyID
						, source.FiscalMonthID
						, source.FiscalYearID
						, source.FiscalTimeID
						, ISNULL(source.BudgetEncounters, 0)
						, ISNULL(source.ActualEncountersYTD, 0)
						, ISNULL(source.ActualEncounters, 0)
					);	

	
	SELECT EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, 
		PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialEncounters
	INTO #BaselineSRC
	FROM #SRC
	WHERE FiscalYearID = @FiscalYearID

	-- Publish Initials (we need to do these seperately because otherwise Baseline will wipe out Target/Budget)
	;WITH TGT AS 
	(
		SELECT EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, 
		PayorGroupID, MSDRGRollupID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialEncounters 
		FROM [fp].[FactReportingAPEncounters] FRE

	)
			MERGE TGT AS target
			USING #BaselineSRC AS source
				ON (
						target.EntityID			   = source.EntityID
						AND target.DepartmentID		   = source.DepartmentID
						AND target.ServiceLineID	   = source.ServiceLineID
						AND target.ServiceLineRollupID = source.ServiceLineRollupID
						AND target.PatientClassID	   = source.PatientClassID
						AND target.AgeCohortID		   = source.AgeCohortID
						AND target.MedicalSurgicalID   = source.MedicalSurgicalID
						AND target.PayorID			   = source.PayorID
						AND target.PayorGroupID		   = source.PayorGroupID
						AND target.MSDRGRollupID	   = source.MSDRGID
						AND target.CPTID			   = source.CPTID
						AND target.ProviderID		   = source.ProviderID
						AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID
						AND target.FiscalMonthID	   = source.FiscalMonthID
						AND target.FiscalYearID		   = source.FiscalYearID
						AND target.FiscalTimeID		   = source.FiscalTimeID

						)
			WHEN MATCHED AND	(
				target.InitialEncounters <> source.InitialEncounters)
				THEN
				UPDATE SET
				target.InitialEncounters = ISNULL(source.InitialEncounters, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
							  EntityID
							, DepartmentID
							, ServiceLineID
							, ServiceLineRollupID
							, PatientClassID
							, AgeCohortID
							, MedicalSurgicalID
							, PayorID
							, PayorGroupID
							, MSDRGRollupID
							, CPTID
							, ProviderID
							, PhysicianSpecialtyID
							, FiscalMonthID
							, FiscalYearID
							, FiscalTimeID
							, InitialEncounters
						)
					VALUES (
						  source.EntityID
						, source.DepartmentID
						, source.ServiceLineID
						, source.ServiceLineRollupID
						, source.PatientClassID
						, source.AgeCohortID
						, source.MedicalSurgicalID
						, source.PayorID
						, source.PayorGroupID
						, source.MSDRGID
						, source.CPTID
						, source.ProviderID
						, source.PhysicianSpecialtyID
						, source.FiscalMonthID
						, source.FiscalYearID
						, source.FiscalTimeID
						, ISNULL(source.InitialEncounters, 0)
					);	
END
GO


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

-- fp.procFactEncounterToReportingTransfer
CREATE   PROCEDURE fp.procFactEncounterToReportingTransfer  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI         Description
	** 1    2021-12-07   BW        JAZZ-29137  Initial Creation
	** 2    2022-06-15   MY        JAZZ-38632  Add Targeting
	** 3    2022-06-29   BW        JAZZ-39340  Switching from MSDRGID to MSDRGRollupID
	** 4	11-28-2022   MY        JAZZ-43418  Add FiscalTimeID to Update
	** 5    2022-12-19   MD        JAZZ-47250  Include encounter data that doesn't have corresponding charge data
	** 6    2023-02-23   MY        JAZZ-49629  Handing zeroing out for AA data marts
	** 7    2023-02-28   BW        JAZZ-49992  Updated for new data model, use [fp].[ServiceLineEncounter]
	*************************************************************/
 
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAPEncounters.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAPEncounters, where SQL will then replicate
	-- to Snowflake. 
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#encounterSource'
	EXEC [dbo].[procSysDropTempTable] '#ChargeVolumeDepartments'
	EXEC [dbo].[procSysDropTempTable] '#allServiceLineDimensionality'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT);

	CREATE TABLE #allServiceLineDimensionality (SLEEntityID INT, SLEServiceLineID INT, MapEntityID INT, MapServiceLineID INT)
	INSERT INTO #allServiceLineDimensionality (SLEEntityID, SLEServiceLineID, MapEntityID, MapServiceLineID)	
	SELECT DISTINCT sle.EntityID as SLEEntity, sle.ServiceLineID as SLEServiceLine, 
		map.EntityID as MapEntity, map.ServiceLineID as MapServiceLine
	FROM fp.ServiceLineEncounter sle
	left join fp.ServiceLineEncounterChargeVolumeMapping map 
		on sle.EntityID = map.EntityID
		and sle.ServiceLineID = map.ServiceLineID
		and sle.BudgetConfigID = map.BudgetConfigID
	WHERE sle.BudgetConfigID = @BudgetConfigID	

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED)
			INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
	END ELSE 
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED)
		WHERE map.BudgetConfigID  = @BudgetConfigID	
		-- JAZZ-47250 - Adding this union to account for SL data that doesn't have reflecting charge data
		UNION 
		SELECT SLEEntityID, SLEServiceLineID
		FROM #allServiceLineDimensionality
		WHERE MapEntityID IS NULL
	END

	CREATE TABLE #SRC (
		EntityID INT,
		DepartmentID INT,
		ServiceLineID INT,
		ServiceLineRollupID INT,
		PatientClassID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		PayorID INT,
		PayorGroupID INT,
		MSDRGID INT,
		CPTID INT,
		ProviderID INT,
		PhysicianSpecialtyID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		BudgetEncounters DECIMAL(19, 8),
		ProjectedEncounters DECIMAL(19, 8),
		TargetEncounters DECIMAL(19, 8)
	)

	SELECT
		VW.EntityID,
		DepartmentID,
		VW.ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		FiscalTimeID,
		OriginalValue,
		Value,
		ManagerValue
	INTO #encounterSource
	FROM [fp].[viewFactEncounter_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #encounterTargeting tgt ON VW.EntityID = tgt.EntityID AND VW.ServiceLineID = tgt.ServiceLineID
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.BudgetConfigID = @BudgetConfigID
	 	AND (Value != 0 OR ManagerValue != 0)
	
	CREATE CLUSTERED INDEX inx_stat ON #encounterSource (
		TimeClassID,
		EntityID,
		DepartmentID,		
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID		
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, ServiceLineID,	ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID,
		FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		DepartmentID,
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID
	FROM #encounterSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID		
	)			
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Budget/Target Encounters
	UPDATE src
	SET
		BudgetEncounters = ap.ManagerValue,
		TargetEncounters = ap.Value
	FROM #SRC src
		INNER JOIN #encounterSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.ServiceLineID = ap.ServiceLineID
			AND src.ServiceLineRollupID = ap.ServiceLineRollupID
			AND src.PatientClassID = ap.PatientClassID
			AND src.AgeCohortID = ap.AgeCohortID
			AND src.PatientClassID = ap.PatientClassID
			AND src.MedicalSurgicalID = ap.MedicalSurgicalID
			AND src.PayorID = ap.PayorID
			AND src.PayorGroupID = ap.PayorGroupID
			AND src.MSDRGID = ap.MSDRGID
			AND src.CPTID = ap.CPTID
			AND src.ProviderID = ap.ProviderID
			AND src.CPTID = ap.CPTID
			AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2
	
	-- Update Projected Encounters
	UPDATE src
	SET
		ProjectedEncounters = ap.Value
	FROM #SRC src
		INNER JOIN #encounterSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.ServiceLineID = ap.ServiceLineID
			AND src.ServiceLineRollupID = ap.ServiceLineRollupID
			AND src.PatientClassID = ap.PatientClassID
			AND src.AgeCohortID = ap.AgeCohortID
			AND src.PatientClassID = ap.PatientClassID
			AND src.MedicalSurgicalID = ap.MedicalSurgicalID
			AND src.PayorID = ap.PayorID
			AND src.PayorGroupID = ap.PayorGroupID
			AND src.MSDRGID = ap.MSDRGID
			AND src.CPTID = ap.CPTID
			AND src.ProviderID = ap.ProviderID
			AND src.CPTID = ap.CPTID
			AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 12
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID,
			FiscalTimeID, BudgetEncounters, ProjectedEncounters, TargetEncounters
		FROM #SRC 
		ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalYearID DESC,
			FiscalTimeID, FiscalMonthID;
		
		SELECT '#encounterSource' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, TimeClassID, FiscalMonthID, FiscalYearID,
			FiscalTimeID, OriginalValue, Value, ManagerValue
		FROM #encounterSource
		ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC,
			FiscalTimeID, FiscalMonthID;
		
		RETURN
	END
	
	-- Publish the data from the temp table to fp.FactReportingAPEncounters. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue
	;WITH TGT AS 
	(
		SELECT FRE.EntityID, FRE.DepartmentID, FRE.ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, 
			PayorGroupID, MSDRGRollupID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID,
			FiscalTimeID, BudgetEncounters, ProjectedEncounters, TargetEncounters 
		FROM [fp].[FactReportingAPEncounters] FRE
			INNER JOIN #encounterTargeting tgt ON FRE.EntityID = tgt.EntityID AND FRE.ServiceLineID = tgt.ServiceLineID

	)
			MERGE TGT AS target
			USING #SRC AS source
				ON (
						target.EntityID			   = source.EntityID
						AND target.DepartmentID		   = source.DepartmentID
						AND target.ServiceLineID	   = source.ServiceLineID
						AND target.ServiceLineRollupID = source.ServiceLineRollupID
						AND target.PatientClassID	   = source.PatientClassID
						AND target.AgeCohortID		   = source.AgeCohortID
						AND target.MedicalSurgicalID   = source.MedicalSurgicalID
						AND target.PayorID			   = source.PayorID
						AND target.PayorGroupID		   = source.PayorGroupID
						AND target.MSDRGRollupID	   = source.MSDRGID
						AND target.CPTID			   = source.CPTID
						AND target.ProviderID		   = source.ProviderID
						AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID
						AND target.FiscalMonthID	   = source.FiscalMonthID
						AND target.FiscalYearID		   = source.FiscalYearID
						AND target.FiscalTimeID		   = source.FiscalTimeID

						)
			WHEN MATCHED AND	(
				target.BudgetEncounters <> source.BudgetEncounters
				OR target.ProjectedEncounters <> source.ProjectedEncounters
				OR target.TargetEncounters <> source.TargetEncounters)
				THEN
				UPDATE SET
				target.BudgetEncounters = ISNULL(source.BudgetEncounters, 0),
				target.ProjectedEncounters = ISNULL(source.ProjectedEncounters, 0),
				target.TargetEncounters = ISNULL(source.TargetEncounters, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
							  EntityID
							, DepartmentID
							, ServiceLineID
							, ServiceLineRollupID
							, PatientClassID
							, AgeCohortID
							, MedicalSurgicalID
							, PayorID
							, PayorGroupID
							, MSDRGRollupID
							, CPTID
							, ProviderID
							, PhysicianSpecialtyID
							, FiscalMonthID
							, FiscalYearID
							, FiscalTimeID
							, BudgetEncounters
							, ProjectedEncounters
							, TargetEncounters
						)
					VALUES (
						  source.EntityID
						, source.DepartmentID
						, source.ServiceLineID
						, source.ServiceLineRollupID
						, source.PatientClassID
						, source.AgeCohortID
						, source.MedicalSurgicalID
						, source.PayorID
						, source.PayorGroupID
						, source.MSDRGID
						, source.CPTID
						, source.ProviderID
						, source.PhysicianSpecialtyID
						, source.FiscalMonthID
						, source.FiscalYearID
						, source.FiscalTimeID
						, ISNULL(source.BudgetEncounters, 0)
						, ISNULL(source.ProjectedEncounters, 0)
						, ISNULL(source.TargetEncounters, 0)
					);	
					
	-------------------------------------------------------------------------------------------------------
	-- JAZZ-49629 : Handing zeroing out for AA data marts
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above.
	-------------------------------------------------------------------------------------------------------

	-- Get all records that were adjusted
	SELECT DISTINCT chg.ServiceLineEncounterID
	INTO #adjustedRecords
	FROM [fp].[ServiceLineEncounterChangeHistory] chg
		INNER JOIN [fp].[ServiceLineEncounter] fgl ON chg.ServiceLineEncounterID = fgl.ServiceLineEncounterID
		INNER JOIN #encounterTargeting tgt ON fgl.EntityID = tgt.EntityID AND fgl.ServiceLineID = tgt.ServiceLineID
	WHERE chg.BudgetConfigID = @BudgetConfigID

	SELECT
		VW.EntityID,
		DepartmentID,
		VW.ServiceLineID,
		ServiceLineRollupID,
		PatientClassID,
		AgeCohortID,
		MedicalSurgicalID,
		PayorID,
		PayorGroupID,
		MSDRGID,
		CPTID,
		ProviderID,
		PhysicianSpecialtyID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		Value,
		ManagerValue
	INTO #tempUnpivoted
	FROM [fp].[viewFactEncounter_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #encounterTargeting tgt ON VW.EntityID = tgt.EntityID AND VW.ServiceLineID = tgt.ServiceLineID
		INNER JOIN #adjustedRecords adj ON VW.ServiceLineEncounterID = adj.ServiceLineEncounterID
		INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID 
	WHERE VW.BudgetConfigID = @BudgetConfigID		
		AND (
			   (VW.FiscalYearID = bc.FiscalYearID AND VW.TimeClassID = 2)
			OR (VW.FiscalYearID = bc.FiscalYearID - 1 AND VW.TimeClassID = 12)
		)
	 	AND (
			   (VW.TimeClassID = 2 AND (Value = 0 OR ManagerValue = 0))
			OR (VW.TimeClassID = 12 AND Value = 0)			   
		)
		
	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		frgl.RowID,
		cv.Value, 
		cv.ManagerValue
	INTO #dataToUpdate_Budgeted
	FROM [fp].[FactReportingAPEncounters] frgl
		INNER JOIN #encounterTargeting tgt ON frgl.EntityID = tgt.EntityID AND frgl.ServiceLineID = tgt.ServiceLineID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.PatientClassID 		= frgl.PatientClassID
			AND cv.ServiceLineID 		= frgl.ServiceLineID
			AND cv.ServiceLineRollupID 	= frgl.ServiceLineRollupID
			AND cv.AgeCohortID 			= frgl.AgeCohortID
			AND cv.MedicalSurgicalID 	= frgl.MedicalSurgicalID
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.PayorID 				= frgl.PayorID
			AND cv.PayorGroupID 		= frgl.PayorGroupID
			AND cv.CPTID 				= frgl.CPTID
			AND cv.ProviderID 			= frgl.ProviderID
			AND cv.PhysicianSpecialtyID = frgl.PhysicianSpecialtyID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
	WHERE 1 = 1
		AND cv.TimeClassID = 2
		AND (
			   cv.ManagerValue   != frgl.BudgetEncounters
			OR cv.Value			 != frgl.TargetEncounters
		)

	SELECT 
		frgl.RowID,
		cv.Value
	INTO #dataToUpdate_Projected
	FROM [fp].[FactReportingAPEncounters] frgl
		INNER JOIN #encounterTargeting tgt ON frgl.EntityID = tgt.EntityID AND frgl.ServiceLineID = tgt.ServiceLineID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.PatientClassID 		= frgl.PatientClassID
			AND cv.ServiceLineID 		= frgl.ServiceLineID
			AND cv.ServiceLineRollupID 	= frgl.ServiceLineRollupID
			AND cv.AgeCohortID 			= frgl.AgeCohortID
			AND cv.MedicalSurgicalID 	= frgl.MedicalSurgicalID
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.PayorID 				= frgl.PayorID
			AND cv.PayorGroupID 		= frgl.PayorGroupID
			AND cv.CPTID 				= frgl.CPTID
			AND cv.ProviderID 			= frgl.ProviderID
			AND cv.PhysicianSpecialtyID = frgl.PhysicianSpecialtyID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
	WHERE 1 = 1
		AND cv.TimeClassID = 12
		AND cv.Value != frgl.ProjectedEncounters

	-- Update the records
	UPDATE report
	SET 
		report.BudgetEncounters   = upd.ManagerValue,
		report.TargetEncounters   = upd.Value
	FROM [fp].[FactReportingAPEncounters] report
		INNER JOIN #encounterTargeting tgt ON report.EntityID = tgt.EntityID AND report.ServiceLineID = tgt.ServiceLineID
		INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND (
			   report.TargetEncounters   != upd.Value
			OR report.BudgetEncounters   != upd.ManagerValue
		)

	UPDATE report
	SET 
		report.ProjectedEncounters = upd.Value
	FROM [fp].[FactReportingAPEncounters] report
		INNER JOIN #encounterTargeting tgt ON report.EntityID = tgt.EntityID AND report.ServiceLineID = tgt.ServiceLineID
		INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND report.ProjectedEncounters != upd.Value
END
GO


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

-- fp.procFactGeneralLedgerBaselineAndHistoryToReportingTransfer
CREATE   PROCEDURE [fp].[procFactGeneralLedgerBaselineAndHistoryToReportingTransfer]  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2020-07-24   MY        JAZZ-2849   Initial Creation
	** 2    2022-06-15   MY        JAZZ-38632  Add Targeting
	** 3    2022-07-18   MY        JAZZ-37944  Add Initial Baseline
	** 4	11-28-2022   MY        JAZZ-43418  Add FiscalTimeID to Update
	*************************************************************/
	
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate
	-- to Snowflake. 
	--
	-- It's also important to note that this functionality is currently only availible on demand and is not automatically synced.
	-- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. 
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#generalLedgerSource'
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END	

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		FinancialReportingID INT,
		VariabilityID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		InitialDollars DECIMAL(19, 8) DEFAULT(0)
	)

	SELECT
		gl.GeneralLedgerID, 
		gl.BudgetConfigID, 
		gl.EntityGroupConfigID, 
		gl.EntityID, 
		gl.DepartmentID, 
		gl.AccountID, 
		gl.FinancialReportingID, 
		gl.APEModelSectionID, 
		gl.VariabilityID, 
		34 AS UnitTypeID, 	
		bc.FiscalYearID,
		m.FiscalMonthID,
		gl.TargetLockType,
		gl.BudgetLockType,
		gl.ProjectionLockType,
		InitialBudget
	INTO #glPivoted
	FROM fp.GeneralLedger gl
		INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID		
		CROSS APPLY (
			VALUES
				(01, InitialBudget01),
				(02, InitialBudget02),
				(03, InitialBudget03),
				(04, InitialBudget04),
				(05, InitialBudget05),
				(06, InitialBudget06),
				(07, InitialBudget07),
				(08, InitialBudget08),
				(09, InitialBudget09),
				(10, InitialBudget10),
				(11, InitialBudget11),
				(12, InitialBudget12)		
		) AS CrossApplied (MonthSortOrder, InitialBudget)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	WHERE gl.BudgetConfigID = @BudgetConfigID

	SELECT
		EntityID,
		VW.DepartmentID,
		AccountID,
		FinancialReportingID,
		VariabilityID,
		UnitTypeID,
		2 AS TimeClassID,
		vw.FiscalMonthID,
		vw.FiscalYearID,
		FiscalTimeID,
		InitialBudget AS OriginalValue
	INTO #generalLedgerSource
	FROM #glPivoted vw
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.BudgetConfigID = @BudgetConfigID
	 	AND (InitialBudget != 0)
	
	CREATE CLUSTERED INDEX inx_stat ON #generalLedgerSource (
		TimeClassID,
		EntityID,
		DepartmentID,		
		AccountID,
		FinancialReportingID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID		
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		VW.DepartmentID, 
		AccountID, 
		FinancialReportingID, 
		VariabilityID,
		FiscalMonthID, 
		FiscalYearID,
		FiscalTimeID
	FROM #generalLedgerSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		AccountID,
		FinancialReportingID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID	
	)			
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Budget/Target Dollars
	UPDATE src
	SET
		InitialDollars = ap.OriginalValue
	FROM #SRC src
		INNER JOIN #generalLedgerSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.AccountID = ap.AccountID
			AND src.FinancialReportingID = ap.FinancialReportingID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2
	
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	--
	-- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until
	-- we add it so we don't re-introduce this bug.
	--
	-- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE
	-- EXISTING PROCS AND UPDATE IT FOR THIS.
	-------------------------------------------------------------------------------------------------------
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialDollars
		FROM #SRC;
		
		SELECT '#generalLedgerSource' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue
		FROM #generalLedgerSource
		
		RETURN
	END
	
	-- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue
	;WITH TGT AS 
	(
		SELECT EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialDollars
		FROM [fp].[FactReportingAP] FRS	
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID
	)
	MERGE TGT AS target
	USING #SRC AS source
		ON (
				target.EntityID				= source.EntityID
			AND target.DepartmentID			= source.DepartmentID
			AND target.AccountID			= source.AccountID
			AND target.FinancialReportingID = source.FinancialReportingID
			AND target.VariabilityID		= source.VariabilityID
			AND target.FiscalMonthID		= source.FiscalMonthID
			AND target.FiscalYearID			= source.FiscalYearID
			AND target.FiscalTimeID			= source.FiscalTimeID
			)
		WHEN MATCHED AND 
			(	
				target.InitialDollars <> source.InitialDollars
			 )
		THEN
			UPDATE SET
				target.InitialDollars = ISNULL(source.InitialDollars, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID,
					DepartmentID,
					AccountID,
					FinancialReportingID,
					VariabilityID,
					FiscalMonthID,
					FiscalYearID, 
					FiscalTimeID,
					InitialDollars
				)
				VALUES (
					 source.EntityID,
					 source.DepartmentID,
					 source.AccountID,
					 source.FinancialReportingID,
					 source.VariabilityID,
					 source.FiscalMonthID,
					 source.FiscalYearID, 
					 source.FiscalTimeID,
					 ISNULL(source.InitialDollars, 0)
				);

END
GO


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

-- fp.procFactGeneralLedgerToReportingTransfer
CREATE   PROCEDURE [fp].[procFactGeneralLedgerToReportingTransfer]  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2020-07-24   MY        JAZZ-2849   Initial Creation
	** 2    2022-06-15   MY        JAZZ-38632  Add Targeting
	** 3	11-28-2022   MY        JAZZ-43418  Add FiscalTimeID to Update
	** 4	01-26-2023   MD        JAZZ-49070  Update projection to use ManagerValue
	** 5    2023-02-23   MY        JAZZ-49629  Handing zeroing out for AA data marts
	** 6    2023-08-17   MY        JAZZ-58757  Handing zeroing out for AA data marts
	*************************************************************/
	
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate
	-- to Snowflake.  
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#generalLedgerSource'
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END	

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		FinancialReportingID INT,
		VariabilityID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		BudgetDollars DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars DECIMAL(19, 8) DEFAULT(0),
		TargetDollars DECIMAL(19, 8) DEFAULT(0)
	)

	SELECT
		gl.GeneralLedgerID, 
		gl.BudgetConfigID, 
		gl.EntityGroupConfigID, 
		gl.EntityID, 
		gl.DepartmentID, 
		gl.AccountID, 
		gl.FinancialReportingID, 
		gl.APEModelSectionID, 
		gl.VariabilityID, 
		34 AS UnitTypeID, 	
		bc.FiscalYearID,
		m.FiscalMonthID,
		gl.TargetLockType,
		gl.BudgetLockType,
		gl.ProjectionLockType,
		InitialBudget, 
		Target, 
		Budget, 
		Projection
	INTO #glPivoted
	FROM fp.GeneralLedger gl
		INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID		
		CROSS APPLY (
			VALUES
				(01, InitialBudget01, TargetAdjusted01, BudgetAdjusted01, ProjectionAdjusted01),
				(02, InitialBudget02, TargetAdjusted02, BudgetAdjusted02, ProjectionAdjusted02),
				(03, InitialBudget03, TargetAdjusted03, BudgetAdjusted03, ProjectionAdjusted03),
				(04, InitialBudget04, TargetAdjusted04, BudgetAdjusted04, ProjectionAdjusted04),
				(05, InitialBudget05, TargetAdjusted05, BudgetAdjusted05, ProjectionAdjusted05),
				(06, InitialBudget06, TargetAdjusted06, BudgetAdjusted06, ProjectionAdjusted06),
				(07, InitialBudget07, TargetAdjusted07, BudgetAdjusted07, ProjectionAdjusted07),
				(08, InitialBudget08, TargetAdjusted08, BudgetAdjusted08, ProjectionAdjusted08),
				(09, InitialBudget09, TargetAdjusted09, BudgetAdjusted09, ProjectionAdjusted09),
				(10, InitialBudget10, TargetAdjusted10, BudgetAdjusted10, ProjectionAdjusted10),
				(11, InitialBudget11, TargetAdjusted11, BudgetAdjusted11, ProjectionAdjusted11),
				(12, InitialBudget12, TargetAdjusted12, BudgetAdjusted12, ProjectionAdjusted12)		
		) AS CrossApplied (MonthSortOrder, InitialBudget, Target, Budget, Projection)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	WHERE gl.BudgetConfigID = @BudgetConfigID

	SELECT
		EntityID,
		vw.DepartmentID,
		AccountID,
		FinancialReportingID,
		VariabilityID,
		UnitTypeID,
		2 AS TimeClassID,
		vw.FiscalMonthID,
		vw.FiscalYearID,
		FiscalTimeID,
		InitialBudget AS OriginalValue,
		Target AS Value,
		Budget AS ManagerValue
	INTO #generalLedgerSource
	FROM #glPivoted vw
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = vw.DepartmentID		
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE vw.BudgetConfigID = @BudgetConfigID
	 	AND (Target != 0 OR Budget != 0)

	INSERT INTO #generalLedgerSource (EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID,
		TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue)
	SELECT
		EntityID,
		vw.DepartmentID,
		AccountID,
		FinancialReportingID,
		VariabilityID,
		UnitTypeID,
		12 AS TimeClassID,
		vw.FiscalMonthID,
		vw.FiscalYearID - 1,
		FiscalTimeID,
		0 AS OriginalValue,
		Projection AS Value,
		Projection AS ManagerValue
	FROM #glPivoted vw
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = vw.DepartmentID		
		INNER JOIN fw.DimFiscalTime dft ON vw.FiscalYearID - 1 = dft.FiscalYearID AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE vw.BudgetConfigID = @BudgetConfigID
	 	AND (Projection != 0)
	
	CREATE CLUSTERED INDEX inx_stat ON #generalLedgerSource (
		TimeClassID,
		EntityID,
		DepartmentID,		
		AccountID,
		FinancialReportingID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID	
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		VW.DepartmentID, 
		AccountID, 
		FinancialReportingID, 
		VariabilityID,
		FiscalMonthID, 
		FiscalYearID,
		FiscalTimeID
	FROM #generalLedgerSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		AccountID,
		FinancialReportingID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID	
	)			
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Budget/Target Dollars
	UPDATE src
	SET
		BudgetDollars = ap.ManagerValue,
		TargetDollars = ap.Value
	FROM #SRC src
		INNER JOIN #generalLedgerSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.AccountID = ap.AccountID
			AND src.FinancialReportingID = ap.FinancialReportingID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2
	
	-- Update Projected Dollars
	UPDATE src
	SET
		ProjectedDollars = ap.ManagerValue
	FROM #SRC src
		INNER JOIN #generalLedgerSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.AccountID = ap.AccountID
			AND src.FinancialReportingID = ap.FinancialReportingID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 12
		
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetDollars, ProjectedDollars, TargetDollars
		FROM #SRC;
		
		SELECT '#generalLedgerSource' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue
		FROM #generalLedgerSource
		
		RETURN
	END
	
	-- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue
	;WITH TGT AS 
	(
		SELECT EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetDollars, ProjectedDollars, TargetDollars
		FROM [fp].[FactReportingAP] FRS	
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID
	)
	MERGE TGT AS target
	USING #SRC AS source
		ON (
				target.EntityID				= source.EntityID
			AND target.DepartmentID			= source.DepartmentID
			AND target.AccountID			= source.AccountID
			AND target.FinancialReportingID = source.FinancialReportingID
			AND target.VariabilityID		= source.VariabilityID
			AND target.FiscalMonthID		= source.FiscalMonthID
			AND target.FiscalYearID			= source.FiscalYearID
			AND target.FiscalTimeID			= source.FiscalTimeID
			)
		WHEN MATCHED AND 
			(	
				target.BudgetDollars <> source.BudgetDollars
			 OR target.ProjectedDollars <> source.ProjectedDollars
			 OR target.TargetDollars <> source.TargetDollars
			 )
		THEN
			UPDATE SET
				target.BudgetDollars = ISNULL(source.BudgetDollars, 0),
				target.ProjectedDollars = ISNULL(source.ProjectedDollars, 0),
				target.TargetDollars = ISNULL(source.TargetDollars, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID,
					DepartmentID,
					AccountID,
					FinancialReportingID,
					VariabilityID,
					FiscalMonthID,
					FiscalYearID, 
					FiscalTimeID,
					BudgetDollars,
					ProjectedDollars,
					TargetDollars
				)
				VALUES (
					 source.EntityID,
					 source.DepartmentID,
					 source.AccountID,
					 source.FinancialReportingID,
					 source.VariabilityID,
					 source.FiscalMonthID,
					 source.FiscalYearID, 
					 source.FiscalTimeID,
					 ISNULL(source.BudgetDollars, 0),
					 ISNULL(source.ProjectedDollars, 0),
					 ISNULL(source.TargetDollars, 0)
				);


	-------------------------------------------------------------------------------------------------------
	-- JAZZ-49629 : Handing zeroing out for AA data marts
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above.
	-------------------------------------------------------------------------------------------------------
	
	-- Get all records that were adjusted
	SELECT DISTINCT chg.GeneralLedgerID
	INTO #adjustedRecords
	FROM [fp].[GeneralLedgerChangeHistory] chg
		INNER JOIN [fp].[GeneralLedger] fgl ON chg.GeneralLedgerID = fgl.GeneralLedgerID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
	WHERE chg.BudgetConfigID = @BudgetConfigID

	SELECT
		EntityID,
		VW.DepartmentID,
		AccountID,
		FinancialReportingID,
		VariabilityID,
		UnitTypeID,
		2 AS TimeClassID,
		vw.FiscalMonthID,
		vw.FiscalYearID,
		0 AS OriginalValue,
		Target AS Value,
		Budget AS ManagerValue
	INTO #tempUnpivoted
	FROM #glPivoted vw 
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID	
		INNER JOIN #adjustedRecords adj ON VW.GeneralLedgerID = adj.GeneralLedgerID
		INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID		
	WHERE VW.BudgetConfigID = @BudgetConfigID
		AND (Target = 0 OR Budget = 0)

	INSERT INTO #tempUnpivoted (EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID,
		UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue)
	SELECT
		EntityID,
		VW.DepartmentID,
		AccountID,
		FinancialReportingID,
		VariabilityID,
		UnitTypeID,
		12 AS TimeClassID,
		vw.FiscalMonthID,
		vw.FiscalYearID - 1,
		0 AS OriginalValue,
		Projection AS Value,
		Projection AS ManagerValue
	FROM #glPivoted vw 
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID	
		INNER JOIN #adjustedRecords adj ON VW.GeneralLedgerID = adj.GeneralLedgerID
		INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID		
	WHERE VW.BudgetConfigID = @BudgetConfigID
		AND Projection = 0

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		frgl.RowID,
		cv.Value, 
		cv.ManagerValue
	INTO #dataToUpdate_Budgeted
	FROM [fp].[FactReportingAP] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID	
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.AccountID 			= frgl.AccountID
			AND cv.FinancialReportingID = frgl.FinancialReportingID
			AND cv.VariabilityID 		= frgl.VariabilityID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
	WHERE 1 = 1
		AND cv.TimeClassID = 2
		AND (
			   cv.ManagerValue   != frgl.BudgetDollars
			OR cv.Value			 != frgl.TargetDollars
		)

	SELECT 
		frgl.RowID,
		cv.Value, 
		cv.ManagerValue
	INTO #dataToUpdate_Projected
	FROM [fp].[FactReportingAP] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID	
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.AccountID 			= frgl.AccountID
			AND cv.FinancialReportingID = frgl.FinancialReportingID
			AND cv.VariabilityID 		= frgl.VariabilityID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
	WHERE 1 = 1
		AND cv.TimeClassID = 12
		AND cv.ManagerValue != frgl.ProjectedDollars

	-- Update the records
	UPDATE report
	SET 
		report.BudgetDollars = upd.ManagerValue,
		report.TargetDollars = upd.Value
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND (
			   report.TargetDollars   != upd.Value
			OR report.BudgetDollars   != upd.ManagerValue
		)

	UPDATE report
	SET 
		report.ProjectedDollars = upd.Value
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND report.ProjectedDollars != upd.Value
END
GO


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

-- fp.procFactReportFinancialStatementInsert
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	08-25-2023  MY      JAZZ-59500		Updated view to restructure
*************************************************************/
CREATE   PROC [fp].[procFactReportFinancialStatementInsert]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE
AS
	EXEC fp.procProcessReportFactStatistics_TargetBudget @BudgetConfigID, @SourceDimensionality;
	EXEC fp.procProcessReportFactStatistics_Initial @BudgetConfigID, @SourceDimensionality;
	EXEC fp.ProcReportFactStatisticsHistoryBackup @BudgetConfigID, @SourceDimensionality;

	EXEC fp.procProcessReportFactStaffing_TargetBudget @BudgetConfigID, @SourceDimensionality;
	EXEC fp.procProcessReportFactStaffing_Initial @BudgetConfigID, @SourceDimensionality;
	EXEC fp.ProcReportFactStaffingHistoryBackup @BudgetConfigID, @SourceDimensionality;
	
	EXEC fp.procProcessReportFactGeneralLedger @BudgetConfigID, @SourceDimensionality;
	EXEC fp.procProcessReportFactGeneralLedger_Initial @BudgetConfigID, @SourceDimensionality;
	EXEC fp.ProcReportFactGeneralLedgerHistoryBackup @BudgetConfigID, @SourceDimensionality;

	-- Note: the annualization factor here is wrong, it technically comes from GetAnnualizationFactor, however
	-- with the way this proc is called we can't pass this in here. I'm also not entirely sure this proc is used
	-- as it hasn't been updated from a while ago and we didn't get any bugs for it. I am adding this here just in case.
	-- However, if this is causing issues we'll need to add tests for this proc for one to catch things, but also
	-- take the code that is getting the annualization factor and pull it into SQL.
	DECLARE @AnnualizationFactor DECIMAL(19, 8) = 1;
	EXEC fp.ProcReportFactStatisticsISBackup @BudgetConfigID, @SourceDimensionality;
GO


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

-- fp.procFactReportFinancialStatementInsert_archive
CREATE PROC fp.procFactReportFinancialStatementInsert_archive
WITH RECOMPILE
AS
	declare @ActiveConfigID int
	select @ActiveConfigID = BudgetConfigID from fp.BudgetConfig where IsActive = 1;

    DROP TABLE fp.FactReportGeneralLedger_archive;
	SELECT * INTO fp.FactReportGeneralLedger_archive FROM [fp].[viewFactGeneralLedger_Unpivoted_source] where BudgetConfigID != @ActiveConfigID and (OriginalValue != 0 or Value != 0 or ManagerValue != 0);
	CREATE CLUSTERED INDEX IDX_FactReportGeneralLedger_archive ON fp.FactReportGeneralLedger_archive (GeneralLedgerID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,AccountID,FinancialReportingID,APEModelSectionID,VariabilityID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID);

    DROP TABLE fp.FactReportGeneralLedgerHistory_archive;
	SELECT * INTO fp.FactReportGeneralLedgerHistory_archive FROM [fp].[viewFactGeneralLedgerHistory_Unpivoted_source] where BudgetConfigID != @ActiveConfigID and Value != 0;
	CREATE CLUSTERED INDEX IDX_FactReportGeneralLedgerHistory_archive ON fp.FactReportGeneralLedgerHistory_archive (GeneralLedgerID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,AccountID,FinancialReportingID,APEModelSectionID,VariabilityID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID);

    DROP TABLE fp.FactReportStaffing_archive;
	SELECT * INTO fp.FactReportStaffing_archive FROM [fp].viewFactStaffing_Unpivoted_source where BudgetConfigID != @ActiveConfigID and (OriginalValue != 0 or Value != 0 or ManagerValue != 0);
	CREATE CLUSTERED INDEX IDX_FactReportStaffing_archive ON fp.FactReportStaffing_archive (BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,FiscalMonthID,FiscalYearID);

    DROP TABLE fp.FactReportStaffingHistory_archive;
	SELECT * INTO fp.FactReportStaffingHistory_archive FROM [fp].viewFactStaffingHistory_Unpivoted_source where BudgetConfigID != @ActiveConfigID and Value != 0;
	CREATE CLUSTERED INDEX IDX_FactReportStaffingHistory_archive ON fp.FactReportStaffingHistory_archive (StaffingID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,ProductiveClassID,VariabilityID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID);

    DROP TABLE fp.FactReportStatistics_archive;
	SELECT * INTO fp.FactReportStatistics_archive FROM [fp].viewFactStatistics_Unpivoted_source where BudgetConfigID != @ActiveConfigID and (OriginalValue != 0 or Value != 0 or ManagerValue != 0);
	CREATE CLUSTERED INDEX IDX_FactReportStatistics_archive ON fp.FactReportStatistics_archive (BudgetConfigID,EntityID,DepartmentID,AccountID,PatientClassID,PayorID,FinancialReportingID,UnitTypeID,TimeClassID,FiscalMonthID,FiscalYearID);

    DROP TABLE fp.FactReportStatisticsHistory_archive;
	SELECT * INTO fp.FactReportStatisticsHistory_archive FROM [fp].viewFactStatisticsHistory_Unpivoted_source where BudgetConfigID != @ActiveConfigID and Value != 0;
	CREATE CLUSTERED INDEX IDX_FactReportStatisticsHistory_archive ON fp.FactReportStatisticsHistory_archive (StatisticsID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,AccountID,FinancialReportingID,PayorID,PatientClassID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID);
GO


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

-- fp.procFactStaffingBaselineAndHistoryToReportingTransfer
CREATE   PROCEDURE [fp].[procFactStaffingBaselineAndHistoryToReportingTransfer]  
	@EntityGroupConfigID INT,
	@SqlJoin NVARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2020-07-24   MY        JAZZ-2849   Initial Creation
	** 2    2022-06-15   MY        JAZZ-38632  Add Targeting
	** 3    2022-07-18   MY        JAZZ-37944  Add Initial Baseline
	** 4    2022-07-27   MY        JAZZ-37944  Add NULL check for when the Staffing > GL Crosswalk is not filled out
	** 5	11-28-2022   MY        JAZZ-43418  Add FiscalTimeID to Update
	** 6    2023-12-07   BW        JAZZ-63600  Data model restructure
	*************************************************************/
	
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate
	-- to Snowflake. 
	--
	-- It's also important to note that this functionality is currently only availible on demand and is not automatically synced.
	-- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. 
	--
	-- More information can be found here: https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116214472/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#staffingSource'
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] bc INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE bc.IsActive = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID)) BEGIN RETURN END

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	

	CREATE TABLE #SRC (
		EntityGroupConfigID INT,
		EntityID INT,
		DepartmentID INT,
		JobCodeID INT,
		ProductiveClassID INT,
		PayCodeGroupID INT,
		EmployeeID INT,
		VariabilityID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		InitialDollars DECIMAL(19, 8) DEFAULT(0),
		InitialHours DECIMAL(19, 8) DEFAULT(0),
		InitialFTEs DECIMAL(19, 8) DEFAULT(0),
		GLAccountID INT -- This is used purely in reporting and all we're doing is updating it based on the crosswalk
	)

	SELECT
		EntityGroupConfigID,
		EntityID,
		VW.DepartmentID,
		JobCodeID,
		ProductiveClassID,
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		UnitTypeID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		FiscalTimeID,
		OriginalValue
	INTO #staffingSource
	FROM [fp].[viewFactStaffing_Unpivoted_BaselineOnly] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.EntityGroupConfigID = @EntityGroupConfigID
		AND UnitTypeID IN (34, 51, 144) -- We only want the dollars, hours, and FTEs. We don't want rates.
	 	AND (OriginalValue != 0)
	
	CREATE CLUSTERED INDEX inx_stat ON #staffingSource (
		TimeClassID,
		UnitTypeID,
		EntityID,
		DepartmentID,		
		JobCodeID,
		ProductiveClassID,
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID	
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		VW.DepartmentID, 
		JobCodeID, 
		ProductiveClassID, 
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		FiscalMonthID, 
		FiscalYearID,
		FiscalTimeID
	FROM #staffingSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		JobCodeID,
		ProductiveClassID,
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID	
	)			
	
	DECLARE @SQL NVARCHAR(MAX) = '
    UPDATE staff
    SET staff.GLAccountID = pax.AccountID
    FROM #SRC staff
		 ' + @SqlJoin + '
    WHERE pax.UnitTypeID = 34'
	
	EXEC(@SQL);	
		
	IF @IsDebug = 1
		PRINT @SQL
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Budget/Target Dollars
	UPDATE src
	SET
		InitialDollars = ap.OriginalValue
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 34
		
	-- Update Budget/Target Hours
	UPDATE src
	SET
		InitialHours = ap.OriginalValue
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 51
	
	-- Update Budget/Target FTEs
	UPDATE src
	SET
		InitialFTEs = ap.OriginalValue
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 144
				
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	--
	-- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until
	-- we add it so we don't re-introduce this bug.
	--
	-- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE
	-- EXISTING PROCS AND UPDATE IT FOR THIS.
	-------------------------------------------------------------------------------------------------------
		
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, GLAccountID,
			InitialDollars,
			InitialHours,
			InitialFTEs
		FROM #SRC;
		
		SELECT '#staffingSource' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue
		FROM #staffingSource
		
		RETURN
	END
	
	-- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue
	;WITH TGT AS 
	(
		SELECT EntityID, FRS.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, AccountID,
			InitialDollars,
			InitialHours,
			InitialFTEs
		FROM [fp].[FactReportingAP] FRS	
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID
	)
	MERGE TGT AS target
	USING #SRC AS source
		ON (
				target.EntityID				= source.EntityID
			AND target.DepartmentID			= source.DepartmentID
			AND target.JobCodeID			= source.JobCodeID
			AND target.ProductiveClassID 	= source.ProductiveClassID
			AND target.PayCodeGroupID	 	= source.PayCodeGroupID
			AND target.EmployeeID		 	= source.EmployeeID
			AND target.VariabilityID		= source.VariabilityID
			AND target.FiscalMonthID		= source.FiscalMonthID
			AND target.FiscalYearID			= source.FiscalYearID
			AND target.FiscalTimeID			= source.FiscalTimeID
			AND target.AccountID			= ISNULL(source.GLAccountID, 0)
			)
		WHEN MATCHED AND 
			(	
			   	target.InitialDollars <> source.InitialDollars			 
			 OR	target.InitialHours <> source.InitialHours			 
			 OR	target.InitialFTEs <> source.InitialFTEs			 
			 OR target.AccountID <> ISNULL(source.GLAccountID, 0)
			 )
		THEN
			UPDATE SET
				target.InitialDollars = ISNULL(source.InitialDollars, 0),				
				target.InitialHours = ISNULL(source.InitialHours, 0),				
				target.InitialFTEs = ISNULL(source.InitialFTEs, 0),				
				target.AccountID = ISNULL(source.GLAccountID, 0) -- We need to update the account in the event it gets changed
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID,
					DepartmentID,
					JobCodeID,
					ProductiveClassID, 
					PayCodeGroupID,
					EmployeeID,
					VariabilityID,
					FiscalMonthID,
					FiscalYearID, 
					FiscalTimeID,
					AccountID,
					InitialDollars,				
					InitialHours,				
					InitialFTEs
				)
				VALUES (
					 source.EntityID,
					 source.DepartmentID,
					 source.JobCodeID,
					 source.ProductiveClassID,
					 source.PayCodeGroupID,
					 source.EmployeeID,
					 source.VariabilityID,
					 source.FiscalMonthID,
					 source.FiscalYearID, 
					 source.FiscalTimeID,
					 ISNULL(source.GLAccountID, 0),
					 ISNULL(source.InitialDollars, 0),					 
					 ISNULL(source.InitialHours, 0),					 
					 ISNULL(source.InitialFTEs, 0)
				);

END
GO


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

-- fp.procFactStaffingToReportingTransfer
CREATE   PROCEDURE [fp].[procFactStaffingToReportingTransfer]  
	@EntityGroupConfigID INT,
	@SqlJoin NVARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2020-07-24   MY        JAZZ-2849   Initial Creation
	** 2    2022-06-15   MY        JAZZ-38632  Add Targeting
	** 3    2022-07-27   MY        JAZZ-37944  Add NULL check for when the Staffing > GL Crosswalk is not filled out
	** 4	11-28-2022   MY        JAZZ-43418  Add FiscalTimeID to Update
	** 5    2023-02-23   MY        JAZZ-49629  Handing zeroing out for AA data marts
	** 6    2023-12-07   BW        JAZZ-63600  Data model restructure
	** 7    2024-12-12   MY        JAZZ-79803  SQL Optimization recommendation per MP
	*************************************************************/
	
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate
	-- to Snowflake. 
	--
	-- More information can be found here: https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116214472/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#staffingSource'
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] bc INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE bc.IsActive = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID)) BEGIN RETURN END

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	

	CREATE TABLE #SRC (
		EntityGroupConfigID INT,
		EntityID INT,
		DepartmentID INT,
		JobCodeID INT,
		ProductiveClassID INT,
		PayCodeGroupID INT,
		EmployeeID INT,
		VariabilityID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		BudgetDollars DECIMAL(19, 8) DEFAULT(0),
		ProjectedDollars DECIMAL(19, 8) DEFAULT(0),
		TargetDollars DECIMAL(19, 8) DEFAULT(0),
		BudgetHours DECIMAL(19, 8) DEFAULT(0),
		ProjectedHours DECIMAL(19, 8) DEFAULT(0),
		TargetHours DECIMAL(19, 8) DEFAULT(0),
		BudgetFTEs DECIMAL(19, 8) DEFAULT(0),
		ProjectedFTEs DECIMAL(19, 8) DEFAULT(0),
		TargetFTEs DECIMAL(19, 8) DEFAULT(0),
		GLAccountID INT -- This is used purely in reporting and all we're doing is updating it based on the crosswalk
	)

	SELECT
		EntityGroupConfigID,
		EntityID,
		VW.DepartmentID,
		JobCodeID,
		ProductiveClassID,
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		UnitTypeID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		FiscalTimeID,
		OriginalValue,
		Value,
		ManagerValue
	INTO #staffingSource
	FROM [fp].[viewFactStaffing_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.EntityGroupConfigID = @EntityGroupConfigID
		AND UnitTypeID IN (34, 51, 144) -- We only want the dollars, hours, and FTEs. We don't want rates.
	 	AND (Value != 0 OR ManagerValue != 0)
	
	CREATE CLUSTERED INDEX inx_stat ON #staffingSource (
		TimeClassID,
		UnitTypeID,
		EntityID,
		DepartmentID,		
		JobCodeID,
		ProductiveClassID,
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID	
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		VW.DepartmentID, 
		JobCodeID, 
		ProductiveClassID, 
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		FiscalMonthID, 
		FiscalYearID, 
		FiscalTimeID
	FROM #staffingSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		JobCodeID,
		ProductiveClassID,
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		FiscalMonthID,
		FiscalYearID, 
		FiscalTimeID
	)			
	
	UPDATE STATISTICS #SRC; -- JAZZ-79803: Recommendation per MP

	DECLARE @SQL NVARCHAR(MAX) = '
    UPDATE staff
    SET staff.GLAccountID = pax.AccountID
    FROM #SRC staff
		 ' + @SqlJoin + '
    WHERE pax.UnitTypeID = 34
	OPTION (RECOMPILE)'     -- JAZZ-79803: Recommendation per MP
	
	EXEC(@SQL);	
		
	IF @IsDebug = 1
		PRINT @SQL
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Budget/Target Dollars
	UPDATE src
	SET
		BudgetDollars = ap.ManagerValue,
		TargetDollars = ap.Value
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 34
	
	-- Update Projected Dollars
	UPDATE src
	SET
		ProjectedDollars = ap.Value
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 12 AND ap.UnitTypeID = 34
	
	-- Update Budget/Target Hours
	UPDATE src
	SET
		BudgetHours = ap.ManagerValue,
		TargetHours = ap.Value
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 51
	
	-- Update Projected Hours
	UPDATE src
	SET
		ProjectedHours = ap.Value
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 12 AND ap.UnitTypeID = 51
	
	-- Update Budget/Target FTEs
	UPDATE src
	SET
		BudgetFTEs = ap.ManagerValue,
		TargetFTEs = ap.Value
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 144
	
	-- Update Projected FTEs
	UPDATE src
	SET
		ProjectedFTEs = ap.Value
	FROM #SRC src
		INNER JOIN #staffingSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.JobCodeID = ap.JobCodeID
			AND src.ProductiveClassID = ap.ProductiveClassID
			AND src.PayCodeGroupID = ap.PayCodeGroupID
			AND src.EmployeeID = ap.EmployeeID
			AND src.VariabilityID = ap.VariabilityID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 12 AND ap.UnitTypeID = 144
			
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	--
	-- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until
	-- we add it so we don't re-introduce this bug.
	--
	-- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE
	-- EXISTING PROCS AND UPDATE IT FOR THIS.
	-------------------------------------------------------------------------------------------------------
		
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, GLAccountID,
			BudgetDollars, ProjectedDollars, TargetDollars,
			BudgetHours, ProjectedHours, TargetHours,
			BudgetFTEs, ProjectedFTEs, TargetFTEs
		FROM #SRC;
		
		SELECT '#staffingSource' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue
		FROM #staffingSource
		
		RETURN
	END
	
	-- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue
	;WITH TGT AS 
	(
		SELECT EntityID, FRS.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, AccountID,
			BudgetDollars, ProjectedDollars, TargetDollars,
			BudgetHours, ProjectedHours, TargetHours,
			BudgetFTEs, ProjectedFTEs, TargetFTEs
		FROM [fp].[FactReportingAP] FRS	
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID
	)
	MERGE TGT AS target
	USING #SRC AS source
		ON (
				target.EntityID				= source.EntityID
			AND target.DepartmentID			= source.DepartmentID
			AND target.JobCodeID			= source.JobCodeID
			AND target.ProductiveClassID 	= source.ProductiveClassID
			AND target.PayCodeGroupID	 	= source.PayCodeGroupID
			AND target.EmployeeID		 	= source.EmployeeID
			AND target.VariabilityID		= source.VariabilityID
			AND target.FiscalMonthID		= source.FiscalMonthID
			AND target.FiscalYearID			= source.FiscalYearID
			AND target.FiscalTimeID			= source.FiscalTimeID
			AND target.AccountID			= ISNULL(source.GLAccountID, 0)
			)
		WHEN MATCHED AND 
			(	
			   	target.BudgetDollars <> source.BudgetDollars
			 OR target.ProjectedDollars <> source.ProjectedDollars
			 OR target.TargetDollars <> source.TargetDollars
			 
			 OR	target.BudgetHours <> source.BudgetHours
			 OR target.ProjectedHours <> source.ProjectedHours
			 OR target.TargetHours <> source.TargetHours
			 
			 OR	target.BudgetFTEs <> source.BudgetFTEs
			 OR target.ProjectedFTEs <> source.ProjectedFTEs
			 OR target.TargetFTEs <> source.TargetFTEs
			 
			 OR target.AccountID <> ISNULL(source.GLAccountID, 0)
			 )
		THEN
			UPDATE SET
				target.BudgetDollars = ISNULL(source.BudgetDollars, 0),
				target.ProjectedDollars = ISNULL(source.ProjectedDollars, 0),
				target.TargetDollars = ISNULL(source.TargetDollars, 0),
				
				target.BudgetHours = ISNULL(source.BudgetHours, 0),
				target.ProjectedHours = ISNULL(source.ProjectedHours, 0),
				target.TargetHours = ISNULL(source.TargetHours, 0),
				
				target.BudgetFTEs = ISNULL(source.BudgetFTEs, 0),
				target.ProjectedFTEs = ISNULL(source.ProjectedFTEs, 0),
				target.TargetFTEs = ISNULL(source.TargetFTEs, 0),
				
				target.AccountID = ISNULL(source.GLAccountID, 0) -- We need to update the account in the event it gets changed
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID,
					DepartmentID,
					JobCodeID,
					ProductiveClassID, 
					PayCodeGroupID,
					EmployeeID,
					VariabilityID,
					FiscalMonthID,
					FiscalYearID,
					FiscalTimeID,
					AccountID,
					BudgetDollars,
					ProjectedDollars,
					TargetDollars,					
					BudgetHours,
					ProjectedHours,
					TargetHours,					
					BudgetFTEs,
					ProjectedFTEs,
					TargetFTEs
				)
				VALUES (
					 source.EntityID,
					 source.DepartmentID,
					 source.JobCodeID,
					 source.ProductiveClassID,
					 source.PayCodeGroupID,
					 source.EmployeeID,
					 source.VariabilityID,
					 source.FiscalMonthID,
					 source.FiscalYearID,
					 source.FiscalTimeID,
					 ISNULL(source.GLAccountID, 0), -- While unlikely, we'll get a null error if the crosswalk isn't configured.
					 ISNULL(source.BudgetDollars, 0),
					 ISNULL(source.ProjectedDollars, 0),
					 ISNULL(source.TargetDollars, 0),
					 
					 ISNULL(source.BudgetHours, 0),
					 ISNULL(source.ProjectedHours, 0),
					 ISNULL(source.TargetHours, 0),
					 
					 ISNULL(source.BudgetFTEs, 0),
					 ISNULL(source.ProjectedFTEs, 0),
					 ISNULL(source.TargetFTEs, 0)
				);
					
	-------------------------------------------------------------------------------------------------------
	-- JAZZ-49629 : Handing zeroing out for AA data marts
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above.
	-------------------------------------------------------------------------------------------------------
	
	-- Get all records that were adjusted
	SELECT DISTINCT chg.StaffingID
	INTO #adjustedRecords
	FROM [fp].[StaffingChangeHistory] chg
		INNER JOIN [fp].[Staffing] fgl ON chg.StaffingID = fgl.StaffingID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
	WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID

	SELECT
		EntityGroupConfigID,
		EntityID,
		VW.DepartmentID,
		JobCodeID,
		ProductiveClassID,
		PayCodeGroupID,
		EmployeeID,
		VariabilityID,
		UnitTypeID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		Value,
		ManagerValue
	INTO #tempUnpivoted
	FROM [fp].[viewFactStaffing_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN #adjustedRecords adj ON VW.StaffingID = adj.StaffingID
		INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID
	WHERE VW.EntityGroupConfigID = @EntityGroupConfigID
		AND UnitTypeID IN (34, 51, 144) -- We only want the dollars, hours, and FTEs. We don't want rates.	 			
		AND (
			   (VW.FiscalYearID = bc.FiscalYearID AND VW.TimeClassID = 2)
			OR (VW.FiscalYearID = bc.FiscalYearID - 1 AND VW.TimeClassID = 12)
		)
	 	AND (
			   (VW.TimeClassID = 2 AND (Value = 0 OR ManagerValue = 0))
			OR (VW.TimeClassID = 12 AND Value = 0)			   
		)

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		frgl.RowID,
		cv.UnitTypeID,
		cv.Value, 
		cv.ManagerValue
	INTO #dataToUpdate_Budgeted
	FROM [fp].[FactReportingAP] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.JobCodeID 			= frgl.JobCodeID
			AND cv.ProductiveClassID 	= frgl.ProductiveClassID
			AND cv.PayCodeGroupID 		= frgl.PayCodeGroupID
			AND cv.EmployeeID 			= frgl.EmployeeID
			AND cv.VariabilityID 		= frgl.VariabilityID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
	WHERE 1 = 1
		AND cv.TimeClassID = 2
		AND (
			   (cv.UnitTypeID = 34  AND (Value != frgl.TargetDollars OR ManagerValue != frgl.BudgetDollars))			
			OR (cv.UnitTypeID = 51  AND (Value != frgl.TargetHours OR ManagerValue != frgl.BudgetHours))	
			OR (cv.UnitTypeID = 144 AND (Value != frgl.TargetFTEs OR ManagerValue != frgl.BudgetFTEs))
		)
		
	SELECT 
		frgl.RowID,
		cv.UnitTypeID,
		cv.Value, 
		cv.ManagerValue
	INTO #dataToUpdate_Projected
	FROM [fp].[FactReportingAP] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.JobCodeID 			= frgl.JobCodeID
			AND cv.ProductiveClassID 	= frgl.ProductiveClassID
			AND cv.PayCodeGroupID 		= frgl.PayCodeGroupID
			AND cv.EmployeeID 			= frgl.EmployeeID
			AND cv.VariabilityID 		= frgl.VariabilityID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
	WHERE 1 = 1
		AND cv.TimeClassID = 12
		AND (
			   (cv.UnitTypeID = 34  AND Value != frgl.ProjectedDollars)			
			OR (cv.UnitTypeID = 51  AND Value != frgl.ProjectedHours)	
			OR (cv.UnitTypeID = 144 AND Value != frgl.ProjectedFTEs)
		)

	-- Update the records
	-- Budget
	UPDATE report
	SET 
		report.TargetDollars   = upd.Value,
		report.BudgetDollars   = upd.ManagerValue
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND upd.UnitTypeID = 34
		AND (
			   report.TargetDollars   != upd.Value
			OR report.BudgetDollars   != upd.ManagerValue
		)
			
	UPDATE report
	SET 
		report.TargetHours   = upd.Value,
		report.BudgetHours   = upd.ManagerValue
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND upd.UnitTypeID = 51
		AND (
			   report.TargetHours   != upd.Value
			OR report.BudgetHours   != upd.ManagerValue
		)
			
	UPDATE report
	SET 
		report.TargetFTEs   = upd.Value,
		report.BudgetFTEs   = upd.ManagerValue
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND upd.UnitTypeID = 144
		AND (
			   report.TargetFTEs   != upd.Value
			OR report.BudgetFTEs   != upd.ManagerValue
		)

	-- Projection
	UPDATE report
	SET 
		report.ProjectedDollars = upd.Value
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND upd.UnitTypeID = 34
		AND report.ProjectedDollars != upd.Value
			
	UPDATE report
	SET 
		report.ProjectedHours = upd.Value
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND upd.UnitTypeID = 51
		AND report.ProjectedHours != upd.Value
			
	UPDATE report
	SET 
		report.ProjectedFTEs = upd.Value
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND upd.UnitTypeID = 144
		AND report.ProjectedFTEs != upd.Value
END
GO


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

-- fp.procFactStatisticsBaselineAndHistoryToReportingTransfer
CREATE   PROCEDURE [fp].[procFactStatisticsBaselineAndHistoryToReportingTransfer]  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2020-07-24   MY        JAZZ-2849   Initial Creation
	** 2    2022-06-15   MY        JAZZ-38632  Add Targeting
	** 3    2022-07-18   MY        JAZZ-37944  Add Initial Baseline
	** 4	11-28-2022   MY	       JAZZ-43418  Add FiscalTimeID to Update
	*************************************************************/
	
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate
	-- to Snowflake. 
	--
	-- It's also important to note that this functionality is currently only availible on demand and is not automatically synced.
	-- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. 
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#statisticsSource'
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactStatistics] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END	

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		PatientClassID INT,
		PayorID INT,
		FinancialReportingID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		InitialUnits DECIMAL(19, 8) DEFAULT(0)
	)

	SELECT
		EntityID,
		VW.DepartmentID,
		AccountID,
		PatientClassID,
		PayorID,
		FinancialReportingID,
		UnitTypeID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		FiscalTimeID,
		OriginalValue
	INTO #statisticsSource
	FROM [fp].[viewFactStatistics_Unpivoted_BaselineOnly] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.BudgetConfigID = @BudgetConfigID
	 AND (OriginalValue != 0)
	
	CREATE CLUSTERED INDEX inx_stat ON #statisticsSource (
		TimeClassID,
		EntityID,
		DepartmentID,		
		AccountID,
		PatientClassID,
		PayorID,
		FinancialReportingID,
		FiscalMonthID,
		FiscalYearID		
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		VW.DepartmentID, 
		AccountID, 
		PatientClassID, 
		PayorID, 
		FinancialReportingID, 
		FiscalMonthID, 
		FiscalYearID,
		FiscalTimeID
	FROM #statisticsSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		AccountID,
		PatientClassID,
		PayorID,
		FinancialReportingID,
		FiscalMonthID,
		FiscalYearID,
		FiscalTimeID		
	)			
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Budget/Target Units
	UPDATE src
	SET
		InitialUnits = ap.OriginalValue
	FROM #SRC src
		INNER JOIN #statisticsSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.AccountID = ap.AccountID
			AND src.PatientClassID = ap.PatientClassID
			AND src.PayorID = ap.PayorID
			AND src.FinancialReportingID = ap.FinancialReportingID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2
		
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	--
	-- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until
	-- we add it so we don't re-introduce this bug.
	--
	-- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE
	-- EXISTING PROCS AND UPDATE IT FOR THIS.
	-------------------------------------------------------------------------------------------------------
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialUnits
		FROM #SRC;
		
		SELECT '#statisticsSource' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue
		FROM #statisticsSource
		
		RETURN
	END
	
	-- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue
	;WITH TGT AS 
	(
		SELECT EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialUnits
		FROM [fp].[FactReportingAP] FRS	
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID
	)
	MERGE TGT AS target
	USING #SRC AS source
		ON (
				target.EntityID				= source.EntityID
			AND target.DepartmentID			= source.DepartmentID
			AND target.AccountID			= source.AccountID
			AND target.PatientClassID		= source.PatientClassID
			AND target.PayorID				= source.PayorID
			AND target.FinancialReportingID = source.FinancialReportingID
			AND target.FiscalMonthID		= source.FiscalMonthID
			AND target.FiscalYearID			= source.FiscalYearID
			AND target.FiscalTimeID			= source.FiscalTimeID
			)
		WHEN MATCHED AND 
			(	
				target.InitialUnits <> source.InitialUnits
			 )
		THEN
			UPDATE SET
				target.InitialUnits = ISNULL(source.InitialUnits, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID,
					DepartmentID,
					AccountID,
					PatientClassID,
					PayorID,
					FinancialReportingID,
					FiscalMonthID,
					FiscalYearID,
					FiscalTimeID,
					InitialUnits
				)
				VALUES (
					 source.EntityID,
					 source.DepartmentID,
					 source.AccountID,
					 source.PatientClassID,
					 source.PayorID,
					 source.FinancialReportingID,
					 source.FiscalMonthID,
					 source.FiscalYearID,
					 source.FiscalTimeID,
					 ISNULL(source.InitialUnits, 0)
				);

END
GO


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

-- fp.procFactStatisticsToReportingTransfer
CREATE   PROCEDURE fp.procFactStatisticsToReportingTransfer  
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2020-07-24   MY        JAZZ-2849   Initial Creation
	** 2    2022-06-15   MY        JAZZ-38632  Add Targeting
	** 3	11-28-2022   MY        JAZZ-43418  Add FiscalTimeID to Update
	** 5    2023-02-23   MY        JAZZ-49629  Handing zeroing out for AA data marts
	*************************************************************/
	
	-- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP.
	-- This new proc and table are only used in the new advanced analytics solution that leverages
	-- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate
	-- to Snowflake. 
	--
	-- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics
	
	SET NOCOUNT ON;
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#statisticsSource'
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactStatistics] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END	

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		PatientClassID INT,
		PayorID INT,
		FinancialReportingID INT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		FiscalTimeID INT,
		BudgetUnits DECIMAL(19, 8) DEFAULT(0),
		ProjectedUnits DECIMAL(19, 8) DEFAULT(0),
		TargetUnits DECIMAL(19, 8) DEFAULT(0)
	)

	SELECT
		EntityID,
		VW.DepartmentID,
		AccountID,
		PatientClassID,
		PayorID,
		FinancialReportingID,
		UnitTypeID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		FiscalTimeID,
		OriginalValue,
		Value,
		ManagerValue
	INTO #statisticsSource
	FROM [fp].[viewFactStatistics_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID
			AND VW.FiscalMonthID = dft.FiscalMonthID
	WHERE VW.BudgetConfigID = @BudgetConfigID
	 AND (Value != 0 OR ManagerValue != 0)
	
	CREATE CLUSTERED INDEX inx_stat ON #statisticsSource (
		TimeClassID,
		EntityID,
		DepartmentID,		
		AccountID,
		PatientClassID,
		PayorID,
		FinancialReportingID,
		FiscalMonthID,
		FiscalYearID		
	)	

	-- Populate the dimensionality first
	INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID)
	SELECT DISTINCT
		EntityID, 
		VW.DepartmentID, 
		AccountID, 
		PatientClassID, 
		PayorID, 
		FinancialReportingID, 
		FiscalMonthID, 
		FiscalYearID,
		FiscalTimeID
	FROM #statisticsSource VW

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		EntityID,
		DepartmentID,		
		AccountID,
		PatientClassID,
		PayorID,
		FinancialReportingID,
		FiscalMonthID,
		FiscalYearID, 
		FiscalTimeID	
	)			
	
	-- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. 
	-- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END
	-- because then when it hits a row that doesn't match that, it's gonna set the target to 0.
	
	-- Update Budget/Target Units
	UPDATE src
	SET
		BudgetUnits = ap.ManagerValue,
		TargetUnits = ap.Value
	FROM #SRC src
		INNER JOIN #statisticsSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.AccountID = ap.AccountID
			AND src.PatientClassID = ap.PatientClassID
			AND src.PayorID = ap.PayorID
			AND src.FinancialReportingID = ap.FinancialReportingID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 2
	
	-- Update Projected Units
	UPDATE src
	SET
		ProjectedUnits = ap.Value
	FROM #SRC src
		INNER JOIN #statisticsSource ap ON
				src.EntityID = ap.EntityID
			AND src.DepartmentID = ap.DepartmentID
			AND src.AccountID = ap.AccountID
			AND src.PatientClassID = ap.PatientClassID
			AND src.PayorID = ap.PayorID
			AND src.FinancialReportingID = ap.FinancialReportingID
			AND src.FiscalYearID = ap.FiscalYearID
			AND src.FiscalMonthID = ap.FiscalMonthID
	WHERE ap.TimeClassID = 12
			
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetUnits, ProjectedUnits, TargetUnits
		FROM #SRC;
		
		SELECT '#statisticsSource' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue
		FROM #statisticsSource
		
		RETURN
	END
	
	-- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates	
	-- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself.
    -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we
    -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue
	;WITH TGT AS 
	(
		SELECT EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, BudgetUnits, ProjectedUnits, TargetUnits, FiscalTimeID
		FROM [fp].[FactReportingAP] FRS	
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID
	)
	MERGE TGT AS target
	USING #SRC AS source
		ON (
				target.EntityID				= source.EntityID
			AND target.DepartmentID			= source.DepartmentID
			AND target.AccountID			= source.AccountID
			AND target.PatientClassID		= source.PatientClassID
			AND target.PayorID				= source.PayorID
			AND target.FinancialReportingID = source.FinancialReportingID
			AND target.FiscalMonthID		= source.FiscalMonthID
			AND target.FiscalYearID			= source.FiscalYearID
			AND target.FiscalTimeID			= source.FiscalTimeID
			)
		WHEN MATCHED AND 
			(	
				target.BudgetUnits <> source.BudgetUnits
			 OR target.ProjectedUnits <> source.ProjectedUnits
			 OR target.TargetUnits <> source.TargetUnits
			 )
		THEN
			UPDATE SET
				target.BudgetUnits = ISNULL(source.BudgetUnits, 0),
				target.ProjectedUnits = ISNULL(source.ProjectedUnits, 0),
				target.TargetUnits = ISNULL(source.TargetUnits, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					EntityID,
					DepartmentID,
					AccountID,
					PatientClassID,
					PayorID,
					FinancialReportingID,
					FiscalMonthID,
					FiscalYearID,
					FiscalTimeID,
					BudgetUnits,
					ProjectedUnits,
					TargetUnits
				)
				VALUES (
					 source.EntityID,
					 source.DepartmentID,
					 source.AccountID,
					 source.PatientClassID,
					 source.PayorID,
					 source.FinancialReportingID,
					 source.FiscalMonthID,
					 source.FiscalYearID,
					 source.FiscalTimeID,
					 ISNULL(source.BudgetUnits, 0),
					 ISNULL(source.ProjectedUnits, 0),
					 ISNULL(source.TargetUnits, 0)
				);
					
	-------------------------------------------------------------------------------------------------------
	-- JAZZ-49629 : Handing zeroing out for AA data marts
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above.
	-------------------------------------------------------------------------------------------------------

	-- Get all records that were adjusted
	SELECT DISTINCT chg.StatisticsID
	INTO #adjustedRecords
	FROM [fp].[StatisticsChangeHistory] chg
		INNER JOIN [fp].[FactStatistics] fgl ON chg.StatisticsID = fgl.StatisticsID
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
	WHERE chg.BudgetConfigID = @BudgetConfigID

	SELECT
		EntityID,
		VW.DepartmentID,
		AccountID,
		PatientClassID,
		PayorID,
		FinancialReportingID,
		UnitTypeID,
		TimeClassID,
		VW.FiscalMonthID,
		VW.FiscalYearID,
		Value,
		ManagerValue
	INTO #tempUnpivoted
	FROM [fp].[viewFactStatistics_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once.
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID
		INNER JOIN #adjustedRecords adj ON VW.StatisticsID = adj.StatisticsID
		INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID
	WHERE VW.BudgetConfigID = @BudgetConfigID
		AND UnitTypeID = 140 -- Units
		AND (
			   (VW.FiscalYearID = bc.FiscalYearID AND VW.TimeClassID = 2)
			OR (VW.FiscalYearID = bc.FiscalYearID - 1 AND VW.TimeClassID = 12)
		)
	 	AND (
			   (VW.TimeClassID = 2 AND (Value = 0 OR ManagerValue = 0))
			OR (VW.TimeClassID = 12 AND Value = 0)			   
		)
		
	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		frgl.RowID,
		cv.Value, 
		cv.ManagerValue
	INTO #dataToUpdate_Budgeted
	FROM [fp].[FactReportingAP] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.AccountID 			= frgl.AccountID
			AND cv.PatientClassID 		= frgl.PatientClassID
			AND cv.PayorID 				= frgl.PayorID
			AND cv.FinancialReportingID = frgl.FinancialReportingID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
	WHERE 1 = 1
		AND cv.TimeClassID = 2
		AND (
			   cv.ManagerValue   != frgl.BudgetUnits
			OR cv.Value			 != frgl.TargetUnits
		)

	SELECT 
		frgl.RowID,
		cv.Value
	INTO #dataToUpdate_Projected
	FROM [fp].[FactReportingAP] frgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted cv ON
				cv.EntityID 			= frgl.EntityID 
			AND cv.DepartmentID 		= frgl.DepartmentID
			AND cv.AccountID 			= frgl.AccountID
			AND cv.PatientClassID 		= frgl.PatientClassID
			AND cv.PayorID 				= frgl.PayorID
			AND cv.FinancialReportingID = frgl.FinancialReportingID
			AND cv.FiscalYearID 		= frgl.FiscalYearID
			AND cv.FiscalMonthID 		= frgl.FiscalMonthID
	WHERE 1 = 1
		AND cv.TimeClassID = 12
		AND cv.Value != frgl.ProjectedUnits

	-- Update the records
	UPDATE report
	SET 
		report.BudgetUnits = upd.ManagerValue,
		report.TargetUnits = upd.Value
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND (
			   report.TargetUnits != upd.Value
			OR report.BudgetUnits != upd.ManagerValue
		)

	UPDATE report
	SET 
		report.ProjectedUnits = upd.Value
	FROM [fp].[FactReportingAP] report
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID
		INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID
	WHERE 1 = 1
		AND report.ProjectedUnits != upd.Value

END
GO


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

-- fp.procFindAdvancedPlanningPerformanceFlaws
CREATE PROCEDURE [fp].[procFindAdvancedPlanningPerformanceFlaws]
	@SchemaName NVARCHAR(10) = '',   -- Provide the schema you wish to check
	@SpecificObj NVARCHAR(1000) = '' -- If you are looking for a specific object, specify it here, otherwise the entire schema will be checked
AS
BEGIN

	/*
	Script Owner: Mike Y.

	Script Notes:
	 - This is not a performant script, so ignore the amount of cursors, can always tweak it later
	 - There are false positives, will work on trying to narrow that down as we use this
	 - Will add more checks as time goes on.
	 
	Left to do:
	 - Use Search Arguments  ( will look /search for table scan at SQL level in Perf Env as a first step)
	 - Avoid using table variables, cursors or function calls that evaluate each row in where clause
	 
	Change Log:
	  08/15/2019 - Initial
	*/

	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb.dbo.#objects') IS NOT NULL
	    DROP TABLE #objects	
		
	CREATE TABLE #Results (
		Name NVARCHAR(MAX),
		ObjectType NVARCHAR(MAX),
		Severity SMALLINT,
		Category NVARCHAR(MAX),
		Description NVARCHAR(MAX)
	)			
				
	SELECT * 
	INTO #objects
	FROM [sys].[objects] 
	WHERE type IN ('U', 'P', 'V') -- https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-objects-transact-sql?view=sql-server-2017
		AND schema_id = SCHEMA_ID(@SchemaName)
		AND (@SpecificObj = '' OR object_id = OBJECT_ID(@SchemaName + '.' + @SpecificObj))

	IF ((SELECT COUNT(*) FROM #objects) = 0)
	BEGIN
		SELECT @SchemaName + '.' + @SpecificObj + ' was not found in this database' AS Error
		RETURN;
	END

	-- Rule 1 do not join on source dimensionality
	CREATE TABLE #TargetingJoin (
		Name NVARCHAR(MAX),
		ObjectType NVARCHAR(MAX)
	)
	
	-- Rule 2 do not join with Department IS NULL
	CREATE TABLE #DepartmentNull (
		Name NVARCHAR(MAX),
		ObjectType NVARCHAR(MAX)
	)
	
	-- Loop through any procs
	DECLARE @ObjectId INT,
			@SchemaId INT,
			@Type NVARCHAR(MAX)
	
	DECLARE crsObjs CURSOR FAST_FORWARD FOR SELECT Object_Id, Schema_Id, Type_Desc FROM #objects WHERE Type != 'U' 
	OPEN crsObjs
	FETCH NEXT FROM crsObjs INTO @ObjectId, @SchemaId, @Type
	DECLARE @sql NVARCHAR(MAX)
	WHILE (@@fetch_status = 0) 
	BEGIN
		SELECT @sql = OBJECT_DEFINITION(@ObjectId)
		
		INSERT INTO #Results (Name, ObjectType, Category, Description, Severity)
		SELECT SCHEMA_NAME(@SchemaId) + '.' + OBJECT_NAME(@ObjectId), @Type, Category, Description, Severity FROM [fp].[funcFindTSQLPerformanceFlaws_AdvancedPlanning](@sql);
			
		FETCH next FROM crsObjs INTO @ObjectId, @SchemaId, @Type
		
	END
	CLOSE crsObjs
	DEALLOCATE crsObjs

	DECLARE @TableName NVARCHAR(MAX);

	-- Populate results tables
	
	-- Severity
	-- 3 - High
	-- 2 - Medium
	-- 1 - Low
	
	SELECT Name, CASE WHEN Severity = 3 THEN 'High'
					  WHEN Severity = 2 THEN 'Medium'
					  WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, 
		   ObjectType, Category, Description 
	FROM #Results 
	ORDER BY Name, Category, ObjectType
	
END
GO


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

-- fp.procFlexDeductionsByGrossCharges
/**************************************************************
** Change History
**************************************************************
** 1	2019-03-08	IP		B-22295			Removed using table variables, small optimizations
** 2	2019-03-14	IP		TK-71351		Fixed crash of [fp].[procFlexDeductionsByGrossCharges] because of missing table #flexed
** 3	2019-03-14	IP		TK-71378		Fixed crash of budgeting engine because of returning debug info [fp].[procFlexDeductionsByGrossCharges] (removed debug info)
** 4 	2019-03-26  IP  	B-22466			Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 5 	2019-08-20  MY  	TK-77476		Short circuted flexing if there is nothing to flex
** 6 	2020-04-15	NN		D-09426			Fix Change History during flexing
** 7 	2022-09-07	NT		JAZZ-40956		Include all gross charges accounts and not just variable revenue accounts when calculating percent of charges
** 8	2023-08-03	NT      JAZZ-58154		Data restructure changes
** 9	2023-08-22	MY      JAZZ-58154		procGLApplyRate fix for Restructure
*************************************************************/
CREATE   PROCEDURE [fp].[procFlexDeductionsByGrossCharges]
	 @EntityGroupConfigID int,
	 @MonthsLoaded int,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
 AS
 BEGIN
 
 	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL  DROP TABLE #FilterByDepartment
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
 
	IF OBJECT_ID('tempdb..#itemsToFlex') IS NOT NULL  DROP TABLE #itemsToFlex
	IF OBJECT_ID('tempdb..#budget_basisIDs') IS NOT NULL  DROP TABLE #budget_basisIDs
	IF OBJECT_ID('tempdb..#projection_basisIDs') IS NOT NULL  DROP TABLE #projection_basisIDs
	IF OBJECT_ID('tempdb..#Filter') IS NOT NULL  DROP TABLE #Filter
	IF OBJECT_ID('tempdb..#flexed') IS NOT NULL  DROP TABLE #flexed

	CREATE TABLE #itemsToFlex(DepartmentID int, GLAccountID int)
	CREATE TABLE #budget_basisIDs (GeneralLedgerID INT);
	CREATE TABLE #projection_basisIDs (GeneralLedgerID  INT);

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
  	BEGIN
		INSERT INTO #itemsToFlex(DepartmentID, GLAccountID)
		SELECT DISTINCT fsc.DepartmentID, fsc.GLAccountID
	    FROM [fp].[GeneralLedger] gl
	        INNER JOIN [fp].[FlexConfigMapping] fsc ON fsc.DepartmentID = gl.DepartmentID AND fsc.GLAccountID = gl.AccountID
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID 
	    WHERE fsc.FlexingTypeID = 6  -- Deductions
	        AND fsc.EntityGroupConfigID = @EntityGroupConfigID
	        AND gl.EntityGroupConfigID = @EntityGroupConfigID
  	END ELSE BEGIN
		INSERT INTO #itemsToFlex(DepartmentID, GLAccountID)
		SELECT DISTINCT fsc.DepartmentID, fsc.GLAccountID
	    FROM [fp].[GeneralLedger] gl
	        INNER JOIN [fp].[FlexConfigMapping] fsc ON fsc.DepartmentID = gl.DepartmentID AND fsc.GLAccountID = gl.AccountID
	    WHERE fsc.FlexingTypeID = 6  -- Deductions
	        AND fsc.EntityGroupConfigID = @EntityGroupConfigID
	        AND gl.EntityGroupConfigID = @EntityGroupConfigID
  	END
  	
  	DECLARE @BudgetConfigID INT
	SELECT @BudgetConfigID = BudgetConfigID 
	FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID 
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
  	
 	DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0)
 
 	--grossOrPercent -> 1 = gross charges, 2 = Percent of charges
  	SELECT EntityGroupConfigID = @EntityGroupConfigID, 
  			APEModelSectionID = 1,
  			CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN null ELSE 2 END AS VariabilityID, --we will only include variable revenue accounts if the FF is off
  			DepartmentID, 
  			null as Account, 
  			1 as grossOrPercent 
	INTO #Filter
	from #itemsToFlex
	UNION 
	SELECT EntityGroupConfigID = @EntityGroupConfigID, 
	       APEModelSectionID = 4,
	       VariabilityID = 2, -- we only include variable deduction accounts for rate
	       DepartmentID,
	       GLAccountID, 
	       2 as grossOrPercent 
	from #itemsToFlex

	IF ((SELECT COUNT(*) FROM #itemsToFlex) = 0)
	BEGIN
		RETURN -- There were no results so no need to proceed
	END
	
	SELECT x.* 
	INTO #flexed
	FROM (
		SELECT 
			gl.GeneralLedgerID, gl.VariabilityID,
			SUM(CASE WHEN grossOrPercent = 1 THEN TargetAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue01,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue02,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue03,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue04,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue05,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue06,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue07,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue08,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue09,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue10,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue11,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue12,
		
			SUM(CASE WHEN grossOrPercent = 1 THEN BudgetAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue01,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue02,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue03,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue04,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue05,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue06,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue07,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue08,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue09,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue10,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue11,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue12,
			
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue01,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue02,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue03,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue04,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue05,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue06,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue07,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue08,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue09,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue10,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue11,
			SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue12,
			MAX(F.DepartmentID) OVER (PARTITION BY gl.DepartmentID) AS DeptFilter,
		    MAX(F.Account) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) AS AccFilter
	 FROM [fp].[GeneralLedger] gl WITH(NOLOCK)
	 INNER JOIN #Filter F ON F.APEModelSectionID = gl.APEModelSectionID
		AND F.DepartmentID = gl.DepartmentID
		AND ISNULL(F.Account, gl.AccountID) = gl.AccountID
		AND gl.EntityGroupConfigID = F.EntityGroupConfigID
		AND ISNULL(F.VariabilityID, gl.VariabilityID) = gl.VariabilityID
	 WHERE gl.EntityGroupConfigID = @EntityGroupConfigID
	 ) x
	 INNER JOIN #itemsToFlex itf on itf.DepartmentID = x.DeptFilter and itf.GLAccountID = x.AccFilter
	 AND x.VariabilityID = 2 --this is to make sure we only flex variable deductions
	 ORDER BY GeneralLedgerID

	IF (@IsDebug = 0) 
	BEGIN
	
		UPDATE basis
	    SET TargetAdjusted01 = FlexedTargetValue01 * TargetPercentAdjustmentFactor01,
			TargetAdjusted02 = FlexedTargetValue02 * TargetPercentAdjustmentFactor02,
			TargetAdjusted03 = FlexedTargetValue03 * TargetPercentAdjustmentFactor03,
			TargetAdjusted04 = FlexedTargetValue04 * TargetPercentAdjustmentFactor04,
			TargetAdjusted05 = FlexedTargetValue05 * TargetPercentAdjustmentFactor05,
			TargetAdjusted06 = FlexedTargetValue06 * TargetPercentAdjustmentFactor06,
			TargetAdjusted07 = FlexedTargetValue07 * TargetPercentAdjustmentFactor07,
			TargetAdjusted08 = FlexedTargetValue08 * TargetPercentAdjustmentFactor08,
			TargetAdjusted09 = FlexedTargetValue09 * TargetPercentAdjustmentFactor09,
			TargetAdjusted10 = FlexedTargetValue10 * TargetPercentAdjustmentFactor10,
			TargetAdjusted11 = FlexedTargetValue11 * TargetPercentAdjustmentFactor11,
			TargetAdjusted12 = FlexedTargetValue12 * TargetPercentAdjustmentFactor12,
			
			BudgetAdjusted01 = FlexedBudgetValue01 * BudgetPercentAdjustmentFactor01,
			BudgetAdjusted02 = FlexedBudgetValue02 * BudgetPercentAdjustmentFactor02,
			BudgetAdjusted03 = FlexedBudgetValue03 * BudgetPercentAdjustmentFactor03,
			BudgetAdjusted04 = FlexedBudgetValue04 * BudgetPercentAdjustmentFactor04,
			BudgetAdjusted05 = FlexedBudgetValue05 * BudgetPercentAdjustmentFactor05,
			BudgetAdjusted06 = FlexedBudgetValue06 * BudgetPercentAdjustmentFactor06,
			BudgetAdjusted07 = FlexedBudgetValue07 * BudgetPercentAdjustmentFactor07,
			BudgetAdjusted08 = FlexedBudgetValue08 * BudgetPercentAdjustmentFactor08,
			BudgetAdjusted09 = FlexedBudgetValue09 * BudgetPercentAdjustmentFactor09,
			BudgetAdjusted10 = FlexedBudgetValue10 * BudgetPercentAdjustmentFactor10,
			BudgetAdjusted11 = FlexedBudgetValue11 * BudgetPercentAdjustmentFactor11,
			BudgetAdjusted12 = FlexedBudgetValue12 * BudgetPercentAdjustmentFactor12
	
	    OUTPUT 
	        INSERTED.GeneralLedgerID
	    INTO
	       #budget_basisIDs (GeneralLedgerID)
	    FROM [fp].[GeneralLedger] basis
		INNER JOIN #flexed flexed ON basis.GeneralLedgerID = flexed.GeneralLedgerID
		WHERE ( basis.TargetAdjusted01 != flexed.FlexedTargetValue01 * TargetPercentAdjustmentFactor01 OR 
				basis.TargetAdjusted02 != flexed.FlexedTargetValue02 * TargetPercentAdjustmentFactor02 OR 
				basis.TargetAdjusted03 != flexed.FlexedTargetValue03 * TargetPercentAdjustmentFactor03 OR 
				basis.TargetAdjusted04 != flexed.FlexedTargetValue04 * TargetPercentAdjustmentFactor04 OR 
				basis.TargetAdjusted05 != flexed.FlexedTargetValue05 * TargetPercentAdjustmentFactor05 OR 
				basis.TargetAdjusted06 != flexed.FlexedTargetValue06 * TargetPercentAdjustmentFactor06 OR 
				basis.TargetAdjusted07 != flexed.FlexedTargetValue07 * TargetPercentAdjustmentFactor07 OR 
				basis.TargetAdjusted08 != flexed.FlexedTargetValue08 * TargetPercentAdjustmentFactor08 OR 
				basis.TargetAdjusted09 != flexed.FlexedTargetValue09 * TargetPercentAdjustmentFactor09 OR 
				basis.TargetAdjusted10 != flexed.FlexedTargetValue10 * TargetPercentAdjustmentFactor10 OR 
				basis.TargetAdjusted11 != flexed.FlexedTargetValue11 * TargetPercentAdjustmentFactor11 OR 
				basis.TargetAdjusted12 != flexed.FlexedTargetValue12 * TargetPercentAdjustmentFactor12 OR
			
				basis.BudgetAdjusted01 != flexed.FlexedBudgetValue01 * BudgetPercentAdjustmentFactor01 OR 
				basis.BudgetAdjusted02 != flexed.FlexedBudgetValue02 * BudgetPercentAdjustmentFactor02 OR 
				basis.BudgetAdjusted03 != flexed.FlexedBudgetValue03 * BudgetPercentAdjustmentFactor03 OR 
				basis.BudgetAdjusted04 != flexed.FlexedBudgetValue04 * BudgetPercentAdjustmentFactor04 OR 
				basis.BudgetAdjusted05 != flexed.FlexedBudgetValue05 * BudgetPercentAdjustmentFactor05 OR 
				basis.BudgetAdjusted06 != flexed.FlexedBudgetValue06 * BudgetPercentAdjustmentFactor06 OR 
				basis.BudgetAdjusted07 != flexed.FlexedBudgetValue07 * BudgetPercentAdjustmentFactor07 OR 
				basis.BudgetAdjusted08 != flexed.FlexedBudgetValue08 * BudgetPercentAdjustmentFactor08 OR 
				basis.BudgetAdjusted09 != flexed.FlexedBudgetValue09 * BudgetPercentAdjustmentFactor09 OR 
				basis.BudgetAdjusted10 != flexed.FlexedBudgetValue10 * BudgetPercentAdjustmentFactor10 OR 
				basis.BudgetAdjusted11 != flexed.FlexedBudgetValue11 * BudgetPercentAdjustmentFactor11 OR 
				basis.BudgetAdjusted12 != flexed.FlexedBudgetValue12 * BudgetPercentAdjustmentFactor12)
				
		UPDATE basis
	    SET basis.ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1  THEN basis.ProjectionAdjusted01 ELSE flexed.FlexedProjectionValue01 * ProjectionPercentAdjustmentFactor01 END,
			basis.ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2  THEN basis.ProjectionAdjusted02 ELSE flexed.FlexedProjectionValue02 * ProjectionPercentAdjustmentFactor02 END,
			basis.ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3  THEN basis.ProjectionAdjusted03 ELSE flexed.FlexedProjectionValue03 * ProjectionPercentAdjustmentFactor03 END,
			basis.ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4  THEN basis.ProjectionAdjusted04 ELSE flexed.FlexedProjectionValue04 * ProjectionPercentAdjustmentFactor04 END,
			basis.ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5  THEN basis.ProjectionAdjusted05 ELSE flexed.FlexedProjectionValue05 * ProjectionPercentAdjustmentFactor05 END,
			basis.ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6  THEN basis.ProjectionAdjusted06 ELSE flexed.FlexedProjectionValue06 * ProjectionPercentAdjustmentFactor06 END,
			basis.ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7  THEN basis.ProjectionAdjusted07 ELSE flexed.FlexedProjectionValue07 * ProjectionPercentAdjustmentFactor07 END,
			basis.ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8  THEN basis.ProjectionAdjusted08 ELSE flexed.FlexedProjectionValue08 * ProjectionPercentAdjustmentFactor08 END,
			basis.ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9  THEN basis.ProjectionAdjusted09 ELSE flexed.FlexedProjectionValue09 * ProjectionPercentAdjustmentFactor09 END,
			basis.ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.ProjectionAdjusted10 ELSE flexed.FlexedProjectionValue10 * ProjectionPercentAdjustmentFactor10 END,
			basis.ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.ProjectionAdjusted11 ELSE flexed.FlexedProjectionValue11 * ProjectionPercentAdjustmentFactor11 END,
			basis.ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.ProjectionAdjusted12 ELSE flexed.FlexedProjectionValue12 * ProjectionPercentAdjustmentFactor12 END
	    OUTPUT 
	        INSERTED.GeneralLedgerID
	    INTO  #projection_basisIDs (GeneralLedgerID)
	    FROM [fp].[GeneralLedger] basis
			INNER JOIN #flexed flexed ON basis.GeneralLEdgerID = flexed.GeneralLedgerID
	    WHERE 
			   (basis.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded >= 1   THEN basis.ProjectionAdjusted01 ELSE flexed.FlexedProjectionValue01 * ProjectionPercentAdjustmentFactor01 END OR 
				basis.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded >= 2   THEN basis.ProjectionAdjusted02 ELSE flexed.FlexedProjectionValue02 * ProjectionPercentAdjustmentFactor02 END OR 
				basis.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded >= 3   THEN basis.ProjectionAdjusted03 ELSE flexed.FlexedProjectionValue03 * ProjectionPercentAdjustmentFactor03 END OR 
				basis.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded >= 4   THEN basis.ProjectionAdjusted04 ELSE flexed.FlexedProjectionValue04 * ProjectionPercentAdjustmentFactor04 END OR 
				basis.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded >= 5   THEN basis.ProjectionAdjusted05 ELSE flexed.FlexedProjectionValue05 * ProjectionPercentAdjustmentFactor05 END OR 
				basis.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded >= 6   THEN basis.ProjectionAdjusted06 ELSE flexed.FlexedProjectionValue06 * ProjectionPercentAdjustmentFactor06 END OR 
				basis.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded >= 7   THEN basis.ProjectionAdjusted07 ELSE flexed.FlexedProjectionValue07 * ProjectionPercentAdjustmentFactor07 END OR 
				basis.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded >= 8   THEN basis.ProjectionAdjusted08 ELSE flexed.FlexedProjectionValue08 * ProjectionPercentAdjustmentFactor08 END OR 
				basis.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded >= 9   THEN basis.ProjectionAdjusted09 ELSE flexed.FlexedProjectionValue09 * ProjectionPercentAdjustmentFactor09 END OR 
				basis.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded >= 10  THEN basis.ProjectionAdjusted10 ELSE flexed.FlexedProjectionValue10 * ProjectionPercentAdjustmentFactor10 END OR 
				basis.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded >= 11  THEN basis.ProjectionAdjusted11 ELSE flexed.FlexedProjectionValue11 * ProjectionPercentAdjustmentFactor11 END OR 
				basis.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded >= 12  THEN basis.ProjectionAdjusted12 ELSE flexed.FlexedProjectionValue12 * ProjectionPercentAdjustmentFactor12 END)


		-- returns the info on the rows that were flexed in order to fix the change history
		SELECT bdg.GeneralLedgerID, m.FiscalMonthID, CAST(2 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CrossApplied.Value			
		FROM #budget_basisIDs ids
			INNER JOIN [fp].[GeneralLedger] bdg ON ids.GeneralLedgerID = bdg.GeneralLedgerID 
			CROSS APPLY (
				VALUES
					(TargetAdjusted01, 1),
					(TargetAdjusted02, 2),
					(TargetAdjusted03, 3),
					(TargetAdjusted04, 4),
					(TargetAdjusted05, 5),
					(TargetAdjusted06, 6),
					(TargetAdjusted07, 7),
					(TargetAdjusted08, 8),
					(TargetAdjusted09, 9),
					(TargetAdjusted10, 10),
					(TargetAdjusted11, 11),
					(TargetAdjusted12, 12)
			) CrossApplied (Value, MonthSortOrder)
			INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
		UNION ALL	
		SELECT bdg.GeneralLedgerID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CrossApplied.Value			
		FROM #budget_basisIDs ids
			INNER JOIN [fp].[GeneralLedger] bdg ON ids.GeneralLedgerID = bdg.GeneralLedgerID 
			CROSS APPLY (
				VALUES
					(BudgetAdjusted01, 1),
					(BudgetAdjusted02, 2),
					(BudgetAdjusted03, 3),
					(BudgetAdjusted04, 4),
					(BudgetAdjusted05, 5),
					(BudgetAdjusted06, 6),
					(BudgetAdjusted07, 7),
					(BudgetAdjusted08, 8),
					(BudgetAdjusted09, 9),
					(BudgetAdjusted10, 10),
					(BudgetAdjusted11, 11),
					(BudgetAdjusted12, 12)
			) CrossApplied (Value, MonthSortOrder)
			INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
		UNION ALL
		SELECT proj.GeneralLedgerID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(12 AS TINYINT) AS TimeClassID, CrossApplied.Value			
		FROM #projection_basisIDs ids
			INNER JOIN [fp].[GeneralLedger] proj ON ids.GeneralLedgerID = proj.GeneralLedgerID 
			CROSS APPLY (
				VALUES
					(ProjectionAdjusted01, 1),
					(ProjectionAdjusted02, 2),
					(ProjectionAdjusted03, 3),
					(ProjectionAdjusted04, 4),
					(ProjectionAdjusted05, 5),
					(ProjectionAdjusted06, 6),
					(ProjectionAdjusted07, 7),
					(ProjectionAdjusted08, 8),
					(ProjectionAdjusted09, 9),
					(ProjectionAdjusted10, 10),
					(ProjectionAdjusted11, 11),
					(ProjectionAdjusted12, 12)
			) CrossApplied (Value, MonthSortOrder)
			INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder

	END ELSE BEGIN
		SELECT 'ItemsToFlex', * FROM #itemsToFlex
		SELECT 'Filter', * FROM #filter
		SELECT 'Flexed', * FROM #flexed
	END
 END
GO


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

-- fp.procFlexDeductionsByGrossCharges_InitialValue
CREATE   PROCEDURE [fp].[procFlexDeductionsByGrossCharges_InitialValue]
	 @EntityGroupConfigID int,
	 @MonthsLoaded int,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
 AS
 	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2	2021-04-13	 NN		 JAZZ-14121	Remove null joins on targeting
	 ** 3   2022-09-07   NT	    JAZZ-40956  Include all gross charges accounts and not just variable revenue accounts when calculating percent of charges
	 ** 4	8-2-2023     NT     JAZZ-58154	Data restructure changes
	 *************************************************************/
 BEGIN
	CREATE TABLE #itemsToFlex(DepartmentID int, GLAccountID int)
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)	
		where gl.EntityGroupConfigID = @EntityGroupConfigID
	END
	
	-- populate a temp
	INSERT INTO #itemsToFlex(DepartmentID, GLAccountID)
	SELECT DISTINCT fsc.DepartmentID, fsc.GLAccountID
    FROM [fp].[GeneralLedger] gl
        INNER JOIN [fp].[FlexConfigMapping] fsc ON fsc.DepartmentID = gl.DepartmentID AND fsc.GLAccountID = gl.AccountID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID
    WHERE fsc.FlexingTypeID = 6  -- Deductions
        AND fsc.EntityGroupConfigID = @EntityGroupConfigID
        AND gl.EntityGroupConfigID = @EntityGroupConfigID
	
	DECLARE @BudgetConfigID INT
	SELECT @BudgetConfigID = BudgetConfigID 
	FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID 
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
	
	DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0)
 
	SELECT 
		fgl.DepartmentID,
		SUM(fgl.InitialBudget01) AS BudgetValue01,
		SUM(fgl.InitialBudget02) AS BudgetValue02,
		SUM(fgl.InitialBudget03) AS BudgetValue03,
		SUM(fgl.InitialBudget04) AS BudgetValue04,
		SUM(fgl.InitialBudget05) AS BudgetValue05,
		SUM(fgl.InitialBudget06) AS BudgetValue06,
		SUM(fgl.InitialBudget07) AS BudgetValue07,
		SUM(fgl.InitialBudget08) AS BudgetValue08,
		SUM(fgl.InitialBudget09) AS BudgetValue09,
		SUM(fgl.InitialBudget10) AS BudgetValue10,
		SUM(fgl.InitialBudget11) AS BudgetValue11,
		SUM(fgl.InitialBudget12) AS BudgetValue12,
		SUM(fgl.InitialProjection01) AS ProjectionValue01,
		SUM(fgl.InitialProjection02) AS ProjectionValue02,
		SUM(fgl.InitialProjection03) AS ProjectionValue03,
		SUM(fgl.InitialProjection04) AS ProjectionValue04,
		SUM(fgl.InitialProjection05) AS ProjectionValue05,
		SUM(fgl.InitialProjection06) AS ProjectionValue06,
		SUM(fgl.InitialProjection07) AS ProjectionValue07,
		SUM(fgl.InitialProjection08) AS ProjectionValue08,
		SUM(fgl.InitialProjection09) AS ProjectionValue09,
		SUM(fgl.InitialProjection10) AS ProjectionValue10,
		SUM(fgl.InitialProjection11) AS ProjectionValue11,
		SUM(fgl.InitialProjection12) AS ProjectionValue12
	INTO #grossCharges
	 FROM [fp].[GeneralLedger] fgl WITH(NOLOCK)
	 	INNER JOIN (SELECT DISTINCT DepartmentID FROM #itemsToFlex) flex ON fgl.DepartmentID = flex.DepartmentID
	 WHERE 
			fgl.EntityGroupConfigID = @EntityGroupConfigID
	 	AND fgl.APEModelSectionID = 1 -- Revenue
		AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2)
	 GROUP BY fgl.DepartmentID
	
	SELECT 
		fgl.DepartmentID, 
		fgl.AccountID,
		SUM(fgl.InitialBudgetPercentOfCharge01) AS BudgetValue01,
		SUM(fgl.InitialBudgetPercentOfCharge02) AS BudgetValue02,
		SUM(fgl.InitialBudgetPercentOfCharge03) AS BudgetValue03,
		SUM(fgl.InitialBudgetPercentOfCharge04) AS BudgetValue04,
		SUM(fgl.InitialBudgetPercentOfCharge05) AS BudgetValue05,
		SUM(fgl.InitialBudgetPercentOfCharge06) AS BudgetValue06,
		SUM(fgl.InitialBudgetPercentOfCharge07) AS BudgetValue07,
		SUM(fgl.InitialBudgetPercentOfCharge08) AS BudgetValue08,
		SUM(fgl.InitialBudgetPercentOfCharge09) AS BudgetValue09,
		SUM(fgl.InitialBudgetPercentOfCharge10) AS BudgetValue10,
		SUM(fgl.InitialBudgetPercentOfCharge11) AS BudgetValue11,
		SUM(fgl.InitialBudgetPercentOfCharge12) AS BudgetValue12,
		SUM(fgl.InitialProjectionPercentOfCharge01) AS ProjectionValue01,
		SUM(fgl.InitialProjectionPercentOfCharge02) AS ProjectionValue02,
		SUM(fgl.InitialProjectionPercentOfCharge03) AS ProjectionValue03,
		SUM(fgl.InitialProjectionPercentOfCharge04) AS ProjectionValue04,
		SUM(fgl.InitialProjectionPercentOfCharge05) AS ProjectionValue05,
		SUM(fgl.InitialProjectionPercentOfCharge06) AS ProjectionValue06,
		SUM(fgl.InitialProjectionPercentOfCharge07) AS ProjectionValue07,
		SUM(fgl.InitialProjectionPercentOfCharge08) AS ProjectionValue08,
		SUM(fgl.InitialProjectionPercentOfCharge09) AS ProjectionValue09,
		SUM(fgl.InitialProjectionPercentOfCharge10) AS ProjectionValue10,
		SUM(fgl.InitialProjectionPercentOfCharge11) AS ProjectionValue11,
		SUM(fgl.InitialProjectionPercentOfCharge12) AS ProjectionValue12
	INTO #percentOfCharges
	 FROM [fp].[GeneralLedger] fgl WITH(NOLOCK)
	 	INNER JOIN #itemsToFlex flex ON fgl.DepartmentID = flex.DepartmentID AND fgl.AccountID = flex.GLAccountID
	 WHERE 
			fgl.EntityGroupConfigID = @EntityGroupConfigID
	 	AND fgl.APEModelSectionID = 4 -- Deductions
		AND fgl.VariabilityID = 2
	 GROUP BY fgl.DepartmentID, fgl.AccountID
	
	SELECT poc.DepartmentID, poc.AccountID,
 		SUM(poc.BudgetValue01 * charges.BudgetValue01) As FlexedBudgetValue01,
		SUM(poc.BudgetValue02 * charges.BudgetValue02) As FlexedBudgetValue02,
		SUM(poc.BudgetValue03 * charges.BudgetValue03) As FlexedBudgetValue03,
		SUM(poc.BudgetValue04 * charges.BudgetValue04) As FlexedBudgetValue04,
		SUM(poc.BudgetValue05 * charges.BudgetValue05) As FlexedBudgetValue05,
		SUM(poc.BudgetValue06 * charges.BudgetValue06) As FlexedBudgetValue06,
		SUM(poc.BudgetValue07 * charges.BudgetValue07) As FlexedBudgetValue07,
		SUM(poc.BudgetValue08 * charges.BudgetValue08) As FlexedBudgetValue08,
		SUM(poc.BudgetValue09 * charges.BudgetValue09) As FlexedBudgetValue09,
		SUM(poc.BudgetValue10 * charges.BudgetValue10) As FlexedBudgetValue10,
		SUM(poc.BudgetValue11 * charges.BudgetValue11) As FlexedBudgetValue11,
		SUM(poc.BudgetValue12 * charges.BudgetValue12) As FlexedBudgetValue12,
		SUM(poc.ProjectionValue01 * charges.ProjectionValue01) As FlexedProjectionValue01,
		SUM(poc.ProjectionValue02 * charges.ProjectionValue02) As FlexedProjectionValue02,
		SUM(poc.ProjectionValue03 * charges.ProjectionValue03) As FlexedProjectionValue03,
		SUM(poc.ProjectionValue04 * charges.ProjectionValue04) As FlexedProjectionValue04,
		SUM(poc.ProjectionValue05 * charges.ProjectionValue05) As FlexedProjectionValue05,
		SUM(poc.ProjectionValue06 * charges.ProjectionValue06) As FlexedProjectionValue06,
		SUM(poc.ProjectionValue07 * charges.ProjectionValue07) As FlexedProjectionValue07,
		SUM(poc.ProjectionValue08 * charges.ProjectionValue08) As FlexedProjectionValue08,
		SUM(poc.ProjectionValue09 * charges.ProjectionValue09) As FlexedProjectionValue09,
		SUM(poc.ProjectionValue10 * charges.ProjectionValue10) As FlexedProjectionValue10,
		SUM(poc.ProjectionValue11 * charges.ProjectionValue11) As FlexedProjectionValue11,
		SUM(poc.ProjectionValue12 * charges.ProjectionValue12) As FlexedProjectionValue12
	INTO #flexed
    FROM 
         #itemsToFlex fm
         INNER JOIN #percentOfCharges poc ON poc.DepartmentID = fm.DepartmentID AND poc.AccountID = fm.GLAccountID
         INNER JOIN #grossCharges charges ON poc.DepartmentID = charges.DepartmentID
	GROUP BY poc.DepartmentID, poc.AccountID
	
	IF (@IsDebug = 0) 
	BEGIN
	
		UPDATE fgl
	    SET InitialBudget01 = FlexedBudgetValue01,
			InitialBudget02 = FlexedBudgetValue02,
			InitialBudget03 = FlexedBudgetValue03,
			InitialBudget04 = FlexedBudgetValue04,
			InitialBudget05 = FlexedBudgetValue05,
			InitialBudget06 = FlexedBudgetValue06,
			InitialBudget07 = FlexedBudgetValue07,
			InitialBudget08 = FlexedBudgetValue08,
			InitialBudget09 = FlexedBudgetValue09,
			InitialBudget10 = FlexedBudgetValue10,
			InitialBudget11 = FlexedBudgetValue11,
			InitialBudget12 = FlexedBudgetValue12,
			InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN InitialProjection01 ELSE flexed.FlexedProjectionValue01 END,
			InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjection02 ELSE flexed.FlexedProjectionValue02 END,
			InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjection03 ELSE flexed.FlexedProjectionValue03 END,
			InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjection04 ELSE flexed.FlexedProjectionValue04 END,
			InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjection05 ELSE flexed.FlexedProjectionValue05 END,
			InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjection06 ELSE flexed.FlexedProjectionValue06 END,
			InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjection07 ELSE flexed.FlexedProjectionValue07 END,
			InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjection08 ELSE flexed.FlexedProjectionValue08 END,
			InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjection09 ELSE flexed.FlexedProjectionValue09 END,
			InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjection10 ELSE flexed.FlexedProjectionValue10 END,
			InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjection11 ELSE flexed.FlexedProjectionValue11 END,
			InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjection12 ELSE flexed.FlexedProjectionValue12 END
	    FROM [fp].[GeneralLedger] fgl
			INNER JOIN #itemsToFlex fm ON fm.DepartmentID = fgl.DepartmentID AND fm.GLAccountID = fgl.AccountID
		    LEFT JOIN #flexed flexed ON fgl.DepartmentID = flexed.DepartmentID AND fgl.AccountID = flexed.AccountID
	    WHERE fgl.VariabilityID = 2
	        AND fgl.EntityGroupConfigID = @EntityGroupConfigID
			AND (fgl.InitialBudget01 != flexed.FlexedBudgetValue01 OR 
				fgl.InitialBudget02 != flexed.FlexedBudgetValue02 OR 
				fgl.InitialBudget03 != flexed.FlexedBudgetValue03 OR 
				fgl.InitialBudget04 != flexed.FlexedBudgetValue04 OR 
				fgl.InitialBudget05 != flexed.FlexedBudgetValue05 OR 
				fgl.InitialBudget06 != flexed.FlexedBudgetValue06 OR 
				fgl.InitialBudget07 != flexed.FlexedBudgetValue07 OR 
				fgl.InitialBudget08 != flexed.FlexedBudgetValue08 OR 
				fgl.InitialBudget09 != flexed.FlexedBudgetValue09 OR 
				fgl.InitialBudget10 != flexed.FlexedBudgetValue10 OR 
				fgl.InitialBudget11 != flexed.FlexedBudgetValue11 OR 
				fgl.InitialBudget12 != flexed.FlexedBudgetValue12 OR 
				fgl.InitialProjection01 != flexed.FlexedProjectionValue01 OR
				fgl.InitialProjection02 != flexed.FlexedProjectionValue02 OR
				fgl.InitialProjection03 != flexed.FlexedProjectionValue03 OR
				fgl.InitialProjection04 != flexed.FlexedProjectionValue04 OR
				fgl.InitialProjection05 != flexed.FlexedProjectionValue05 OR
				fgl.InitialProjection06 != flexed.FlexedProjectionValue06 OR
				fgl.InitialProjection07 != flexed.FlexedProjectionValue07 OR
				fgl.InitialProjection08 != flexed.FlexedProjectionValue08 OR
				fgl.InitialProjection09 != flexed.FlexedProjectionValue09 OR
				fgl.InitialProjection10 != flexed.FlexedProjectionValue10 OR
				fgl.InitialProjection11 != flexed.FlexedProjectionValue11 OR
				fgl.InitialProjection12 != flexed.FlexedProjectionValue12)
							
	END ELSE BEGIN
	
		SELECT 'ItemsToFlex', * FROM #itemsToFlex
		SELECT 'GrossCharges', * FROM #grossCharges
		SELECT 'PercentOfCharges', * FROM #percentOfCharges
		SELECT 'Flexed', * FROM #flexed
	
	END
	
 END
GO


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

-- fp.procFlexDependentByDriverStatistics
CREATE   PROCEDURE [fp].[procFlexDependentByDriverStatistics]
	 @EntityGroupConfigID int,
	 @MonthsLoaded int,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
 AS
BEGIN
 	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1 	2020-12-16  MY  	JAZZ-11325	Initial
	** 2 	2021-02-18  BK  	JAZZ-15007	Add distinct to fix flexing inflation problem
	** 3 	2021-04-21  BK  	JAZZ-18500	Add ProviderID to flexing join
	** 4 	2022-09-30	JB		JAZZ-43489	Remove FlexedValue references
	** 5 	2023-06-29  MY  	JAZZ-53442	Update stats flexing to support x-department stats flexing
	** 6 	2023-02-29  MY  	JAZZ-68469	Cross Department Flexing Stats - Adjustments to source dept/acct 
										    changing dependent rate rather than value
	*************************************************************/	
	
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'
	EXEC [dbo].[procSysDropTempTable] '#itemsToFlex'
	EXEC [dbo].[procSysDropTempTable] '#driverBudget'
	EXEC [dbo].[procSysDropTempTable] '#budget_basisIDs'
	EXEC [dbo].[procSysDropTempTable] '#projection_basisIDs'
	EXEC [dbo].[procSysDropTempTable] '#budgetFlexed'
	EXEC [dbo].[procSysDropTempTable] '#driverProjection'
	EXEC [dbo].[procSysDropTempTable] '#dependentBudget'
	EXEC [dbo].[procSysDropTempTable] '#dependentProjection'
	EXEC [dbo].[procSysDropTempTable] '#projectionFlexed'
	
	DECLARE @BudgetConfigID INT = (SELECT DISTINCT TOP 1 BudgetConfigID 
								   FROM fp.EntityGroupConfig egc 
										INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID 
								   WHERE egc.EntityGroupConfigID = @EntityGroupConfigID)

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'),
			@Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent')
 
	CREATE TABLE #itemsToFlex(DependentDepartmentID INT, DependentStatisticAccountID INT, 
							  DriverDepartmentID INT, DriverStatisticAccountID INT)
  
	-- populate a temporary list of items to flex
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #itemsToFlex(DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID)
		SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID
		FROM [fp].[FlexConfigMapping] fsc
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID
		WHERE fsc.FlexingTypeID = 8  -- Stats by Stats
			AND fsc.EntityGroupConfigID = @EntityGroupConfigID
	END ELSE BEGIN
		INSERT INTO #itemsToFlex(DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID)
		SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID
		FROM [fp].[FlexConfigMapping] fsc
		WHERE fsc.FlexingTypeID = 8  -- Stats by Stats
			AND fsc.EntityGroupConfigID = @EntityGroupConfigID
	END
 
	CREATE TABLE #budget_basisIDs (StatisticsID INT, BudgetPhaseID INT);
	CREATE TABLE #projection_basisIDs (StatisticsID INT, BudgetPhaseID INT);
 
	-------------------------------------------------------------------------
	-- Perform Budget Flexing 
	-------------------------------------------------------------------------
	SELECT 
		fcm.DependentDepartmentID AS DepartmentID, 
		fcm.DependentStatisticAccountID AS AccountID, 
		fs.ProviderID, 
		fsb.BudgetPhaseID,
		SUM(fsb.AdjustedValue01) as NewValue01,
		SUM(fsb.AdjustedValue02) as NewValue02,
		SUM(fsb.AdjustedValue03) as NewValue03,
		SUM(fsb.AdjustedValue04) as NewValue04,
		SUM(fsb.AdjustedValue05) as NewValue05,
		SUM(fsb.AdjustedValue06) as NewValue06,
		SUM(fsb.AdjustedValue07) as NewValue07,
		SUM(fsb.AdjustedValue08) as NewValue08,
		SUM(fsb.AdjustedValue09) as NewValue09,
		SUM(fsb.AdjustedValue10) as NewValue10,
		SUM(fsb.AdjustedValue11) as NewValue11,
		SUM(fsb.AdjustedValue12) as NewValue12
	into #driverBudget
	FROM [fp].[FactStatistics] fs 
		INNER JOIN [fp].[FactStatisticsBudget] fsb ON fs.StatisticsID = fsb.StatisticsID
		INNER JOIN #itemsToFlex fcm ON fs.DepartmentID = fcm.DriverDepartmentID AND fs.AccountID = fcm.DriverStatisticAccountID
	WHERE fs.BudgetConfigID = @BudgetConfigID 
		AND fs.SubSectionID = @Driver
	GROUP BY fcm.DependentDepartmentID, fcm.DependentStatisticAccountID, fs.ProviderID, fsb.BudgetPhaseID
 
	SELECT 
		fs.DepartmentID, 
		fs.AccountID,
		fs.ProviderID, 
		fsb.BudgetPhaseID,
		fsb.RateAdjustedValue01,
		fsb.RateAdjustedValue02,
		fsb.RateAdjustedValue03,
		fsb.RateAdjustedValue04,
		fsb.RateAdjustedValue05,
		fsb.RateAdjustedValue06,
		fsb.RateAdjustedValue07,
		fsb.RateAdjustedValue08,
		fsb.RateAdjustedValue09,
		fsb.RateAdjustedValue10,
		fsb.RateAdjustedValue11,
		fsb.RateAdjustedValue12
	INTO #dependentBudget
	FROM [fp].[FactStatistics] fs
		INNER JOIN [fp].[FactStatisticsBudget] fsb on fs.StatisticsID = fsb.StatisticsID
		INNER JOIN (SELECT DISTINCT DependentDepartmentID, DependentStatisticAccountID FROM #itemsToFlex) fcm ON fs.DepartmentID = fcm.DependentDepartmentID AND fs.AccountID = fcm.DependentStatisticAccountID -- We must do distinct here otherwise accounts flexed by multiple drivers would show up multiple times and skew the numbers
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.UnitTypeID = 140
		AND fs.SubSectionID = @Dependent
 
	SELECT 
		rate.DepartmentID, 
		rate.AccountID, 
		rate.ProviderID, 
		rate.BudgetPhaseID,
		SUM(rate.RateAdjustedValue01 * stat.NewValue01) As FlexedValue01,
		SUM(rate.RateAdjustedValue02 * stat.NewValue02) As FlexedValue02,
		SUM(rate.RateAdjustedValue03 * stat.NewValue03) As FlexedValue03,
		SUM(rate.RateAdjustedValue04 * stat.NewValue04) As FlexedValue04,
		SUM(rate.RateAdjustedValue05 * stat.NewValue05) As FlexedValue05,
		SUM(rate.RateAdjustedValue06 * stat.NewValue06) As FlexedValue06,
		SUM(rate.RateAdjustedValue07 * stat.NewValue07) As FlexedValue07,
		SUM(rate.RateAdjustedValue08 * stat.NewValue08) As FlexedValue08,
		SUM(rate.RateAdjustedValue09 * stat.NewValue09) As FlexedValue09,
		SUM(rate.RateAdjustedValue10 * stat.NewValue10) As FlexedValue10,
		SUM(rate.RateAdjustedValue11 * stat.NewValue11) As FlexedValue11,
		SUM(rate.RateAdjustedValue12 * stat.NewValue12) As FlexedValue12
	INTO #budgetFlexed
    FROM #dependentBudget rate
         INNER JOIN #driverBudget stat ON rate.AccountID = stat.AccountID 
			AND rate.DepartmentID = stat.DepartmentID 
			AND rate.BudgetPhaseID = stat.BudgetPhaseID 
			AND rate.ProviderID = stat.ProviderID
     GROUP BY rate.DepartmentID, rate.AccountID, rate.ProviderID, rate.BudgetPhaseID
  
	IF (@IsDebug = 0)
	BEGIN
 
		-- flex budget data and reset the adjusted value as well
		UPDATE basis
	    SET 
			basis.AdjustedValue01 = dependentFlexed.FlexedValue01,
			basis.AdjustedValue02 = dependentFlexed.FlexedValue02,
			basis.AdjustedValue03 = dependentFlexed.FlexedValue03,
			basis.AdjustedValue04 = dependentFlexed.FlexedValue04,
			basis.AdjustedValue05 = dependentFlexed.FlexedValue05,
			basis.AdjustedValue06 = dependentFlexed.FlexedValue06,
			basis.AdjustedValue07 = dependentFlexed.FlexedValue07,
			basis.AdjustedValue08 = dependentFlexed.FlexedValue08,
			basis.AdjustedValue09 = dependentFlexed.FlexedValue09,
			basis.AdjustedValue10 = dependentFlexed.FlexedValue10,
			basis.AdjustedValue11 = dependentFlexed.FlexedValue11,
			basis.AdjustedValue12 = dependentFlexed.FlexedValue12
	    OUTPUT 
	        INSERTED.StatisticsID, INSERTED.BudgetPhaseID
	    INTO
	        #budget_basisIDs (StatisticsID, BudgetPhaseID) 
	    FROM [fp].[FactStatisticsBudget] basis
			 INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = basis.StatisticsID
	    	 INNER JOIN #budgetFlexed dependentFlexed
	            ON fs.DepartmentID = dependentFlexed.DepartmentID
					  AND fs.AccountID = dependentFlexed.AccountID
					  AND fs.ProviderID = dependentFlexed.ProviderID
					  AND basis.BudgetPhaseID = dependentFlexed.BudgetPhaseID
	    WHERE fs.UnitTypeID = 140
			AND fs.EntityGroupConfigID = @EntityGroupConfigID
			AND (
				basis.AdjustedValue01 != dependentFlexed.FlexedValue01
			OR basis.AdjustedValue02 != dependentFlexed.FlexedValue02
			OR basis.AdjustedValue03 != dependentFlexed.FlexedValue03
			OR basis.AdjustedValue04 != dependentFlexed.FlexedValue04
			OR basis.AdjustedValue05 != dependentFlexed.FlexedValue05
			OR basis.AdjustedValue06 != dependentFlexed.FlexedValue06
			OR basis.AdjustedValue07 != dependentFlexed.FlexedValue07
			OR basis.AdjustedValue08 != dependentFlexed.FlexedValue08
			OR basis.AdjustedValue09 != dependentFlexed.FlexedValue09
			OR basis.AdjustedValue10 != dependentFlexed.FlexedValue10
			OR basis.AdjustedValue11 != dependentFlexed.FlexedValue11
			OR basis.AdjustedValue12 != dependentFlexed.FlexedValue12
			)
	
	END ELSE BEGIN	
		SELECT 'ItemsToFlex', * FROM #itemsToFlex
		SELECT 'DependentBudget', * FROM #dependentBudget	
		SELECT 'DriverBudget', * FROM #driverBudget	
		SELECT 'BudgetFlexed', * FROM #budgetFlexed	
	END
	 
	-------------------------------------------------------------------------
	-- Perform Projection Flexing 
	-------------------------------------------------------------------------
 	SELECT 
		fcm.DependentDepartmentID AS DepartmentID, 
		fcm.DependentStatisticAccountID AS AccountID, 
		fs.ProviderID, 
		fsb.BudgetPhaseID,
		SUM(fsb.AdjustedValue01) as NewValue01,
		SUM(fsb.AdjustedValue02) as NewValue02,
		SUM(fsb.AdjustedValue03) as NewValue03,
		SUM(fsb.AdjustedValue04) as NewValue04,
		SUM(fsb.AdjustedValue05) as NewValue05,
		SUM(fsb.AdjustedValue06) as NewValue06,
		SUM(fsb.AdjustedValue07) as NewValue07,
		SUM(fsb.AdjustedValue08) as NewValue08,
		SUM(fsb.AdjustedValue09) as NewValue09,
		SUM(fsb.AdjustedValue10) as NewValue10,
		SUM(fsb.AdjustedValue11) as NewValue11,
		SUM(fsb.AdjustedValue12) as NewValue12
	into #driverProjection
	FROM [fp].[FactStatistics] fs 
		INNER JOIN [fp].[FactStatisticsProjection] fsb ON fs.StatisticsID = fsb.StatisticsID
		INNER JOIN #itemsToFlex fcm ON fs.DepartmentID = fcm.DriverDepartmentID AND fs.AccountID = fcm.DriverStatisticAccountID
	WHERE fs.BudgetConfigID = @BudgetConfigID  
		AND fs.SubSectionID = @Driver
	GROUP BY fcm.DependentDepartmentID, fcm.DependentStatisticAccountID, fs.ProviderID, fsb.BudgetPhaseID

 	SELECT 
		fs.DepartmentID, 
		fs.AccountID, 
		fs.ProviderID, 
		fsb.BudgetPhaseID,
		fsb.RateAdjustedValue01,
		fsb.RateAdjustedValue02,
		fsb.RateAdjustedValue03,
		fsb.RateAdjustedValue04,
		fsb.RateAdjustedValue05,
		fsb.RateAdjustedValue06,
		fsb.RateAdjustedValue07,
		fsb.RateAdjustedValue08,
		fsb.RateAdjustedValue09,
		fsb.RateAdjustedValue10,
		fsb.RateAdjustedValue11,
		fsb.RateAdjustedValue12
	INTO #dependentProjection
	FROM [fp].[FactStatistics] fs
		INNER JOIN [fp].[FactStatisticsProjection] fsb on fs.StatisticsID = fsb.StatisticsID
		INNER JOIN (SELECT DISTINCT DependentDepartmentID, DependentStatisticAccountID FROM #itemsToFlex) fcm ON fs.DepartmentID = fcm.DependentDepartmentID AND fs.AccountID = fcm.DependentStatisticAccountID -- We must do distinct here otherwise accounts flexed by multiple drivers would show up multiple times and skew the numbers
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.UnitTypeID = 140
		AND fs.SubSectionID = @Dependent
 
	SELECT 
		rate.DepartmentID, 
		rate.AccountID, 
		rate.ProviderID, 
		rate.BudgetPhaseID,
		SUM(rate.RateAdjustedValue01 * stat.NewValue01) As FlexedValue01,
		SUM(rate.RateAdjustedValue02 * stat.NewValue02) As FlexedValue02,
		SUM(rate.RateAdjustedValue03 * stat.NewValue03) As FlexedValue03,
		SUM(rate.RateAdjustedValue04 * stat.NewValue04) As FlexedValue04,
		SUM(rate.RateAdjustedValue05 * stat.NewValue05) As FlexedValue05,
		SUM(rate.RateAdjustedValue06 * stat.NewValue06) As FlexedValue06,
		SUM(rate.RateAdjustedValue07 * stat.NewValue07) As FlexedValue07,
		SUM(rate.RateAdjustedValue08 * stat.NewValue08) As FlexedValue08,
		SUM(rate.RateAdjustedValue09 * stat.NewValue09) As FlexedValue09,
		SUM(rate.RateAdjustedValue10 * stat.NewValue10) As FlexedValue10,
		SUM(rate.RateAdjustedValue11 * stat.NewValue11) As FlexedValue11,
		SUM(rate.RateAdjustedValue12 * stat.NewValue12) As FlexedValue12
	INTO #projectionFlexed
    FROM #dependentProjection rate
         INNER JOIN #driverProjection stat ON rate.AccountID = stat.AccountID 
			AND rate.DepartmentID = stat.DepartmentID 
			AND rate.BudgetPhaseID = stat.BudgetPhaseID 
			AND rate.ProviderID = stat.ProviderID
     GROUP BY rate.DepartmentID, rate.AccountID, rate.ProviderID, rate.BudgetPhaseID

	-- flex projection data and reset the adjusted value as well
	DECLARE @i int = @MonthsLoaded + 1
	DECLARE @MonthsLoadedString CHAR(10)
	SELECT @MonthsLoadedString = CAST(@i as CHAR(2));
		
	DECLARE @sql varchar(max) = 'UPDATE basis SET '
	WHILE (@i <= 12)
	BEGIN 
		SET @sql = @sql + 'basis.AdjustedValue' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+' = dependentFlexed.FlexedValue' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+CASE WHEN @i<12 THEN ',' ELSE '' END
		SET @i = @i+1
	END
	SET @sql = @sql + '
		OUTPUT 
	    INSERTED.StatisticsID, INSERTED.BudgetPhaseID
	INTO
	    #projection_basisIDs (StatisticsID, BudgetPhaseID) 		
	FROM [fp].[FactStatisticsProjection] basis
			INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = basis.StatisticsID
	    	INNER JOIN #projectionFlexed dependentFlexed
	        ON fs.DepartmentID = dependentFlexed.DepartmentID
			    and fs.AccountID = dependentFlexed.AccountID
			    and fs.ProviderID = dependentFlexed.ProviderID
				and basis.BudgetPhaseID = dependentFlexed.BudgetPhaseID
	WHERE fs.UnitTypeID = 140
	    AND fs.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + '
		AND ((basis.AdjustedValue01 != dependentFlexed.FlexedValue01 AND ' + @MonthsLoadedString + ' <= 1 )
		OR (basis.AdjustedValue02 != dependentFlexed.FlexedValue02 AND ' + @MonthsLoadedString + ' <= 2 )   
		OR (basis.AdjustedValue03 != dependentFlexed.FlexedValue03 AND ' + @MonthsLoadedString + ' <= 3 )   
		OR (basis.AdjustedValue04 != dependentFlexed.FlexedValue04 AND ' + @MonthsLoadedString + ' <= 4 )   
		OR (basis.AdjustedValue05 != dependentFlexed.FlexedValue05 AND ' + @MonthsLoadedString + ' <= 5 )   
		OR (basis.AdjustedValue06 != dependentFlexed.FlexedValue06 AND ' + @MonthsLoadedString + ' <= 6 )   
		OR (basis.AdjustedValue07 != dependentFlexed.FlexedValue07 AND ' + @MonthsLoadedString + ' <= 7 )   
		OR (basis.AdjustedValue08 != dependentFlexed.FlexedValue08 AND ' + @MonthsLoadedString + ' <= 8 )   
		OR (basis.AdjustedValue09 != dependentFlexed.FlexedValue09 AND ' + @MonthsLoadedString + ' <= 9 )   
		OR (basis.AdjustedValue10 != dependentFlexed.FlexedValue10 AND ' + @MonthsLoadedString + ' <= 10 )   
		OR (basis.AdjustedValue11 != dependentFlexed.FlexedValue11 AND ' + @MonthsLoadedString + ' <= 11 )   
		OR (basis.AdjustedValue12 != dependentFlexed.FlexedValue12 AND ' + @MonthsLoadedString + ' <= 12 )   
		)
		'

	IF (@IsDebug = 0)
	BEGIN 
		EXEC (@sql) 			
	END ELSE BEGIN	
		PRINT @sql
		SELECT 'ProjectionFlexed', * FROM #projectionFlexed	
	END

	IF (@IsDebug = 0)
	BEGIN
		-- returns the info on the rows that were flexed in order to fix the change history
		SELECT DISTINCT StatisticsID
			,m.FiscalMonthID
			,BudgetPhaseID
			,TimeClassID
			,f.Value
		FROM (
			SELECT bdgt.StatisticsID
				,bdgt.AdjustedValue01
				,bdgt.AdjustedValue02
				,bdgt.AdjustedValue03
				,bdgt.AdjustedValue04
				,bdgt.AdjustedValue05
				,bdgt.AdjustedValue06
				,bdgt.AdjustedValue07
				,bdgt.AdjustedValue08
				,bdgt.AdjustedValue09
				,bdgt.AdjustedValue10
				,bdgt.AdjustedValue11
				,bdgt.AdjustedValue12
				,bdgt.BudgetPhaseID
				,cast(2 AS TINYINT) AS TimeClassID
			FROM #budget_basisIDs ids
			INNER JOIN [fp].[FactStatisticsBudget] bdgt
				ON ids.StatisticsID = bdgt.StatisticsID
				AND ids.BudgetPhaseID = bdgt.BudgetPhaseID
			UNION ALL
			SELECT
				 bdgt.StatisticsID
				,bdgt.AdjustedValue01
				,bdgt.AdjustedValue02
				,bdgt.AdjustedValue03
				,bdgt.AdjustedValue04
				,bdgt.AdjustedValue05
				,bdgt.AdjustedValue06
				,bdgt.AdjustedValue07
				,bdgt.AdjustedValue08
				,bdgt.AdjustedValue09
				,bdgt.AdjustedValue10
				,bdgt.AdjustedValue11
				,bdgt.AdjustedValue12
				,bdgt.BudgetPhaseID
				,cast(12 AS TINYINT) AS TimeClassID
			FROM #projection_basisIDs ids
			INNER JOIN [fp].[FactStatisticsProjection] bdgt
				ON ids.StatisticsID = bdgt.StatisticsID 
				AND ids.BudgetPhaseID = bdgt.BudgetPhaseID
			) gl
		UNPIVOT(Value FOR FiscalMonth IN (AdjustedValue01,AdjustedValue02,AdjustedValue03,AdjustedValue04,AdjustedValue05,AdjustedValue06,AdjustedValue07,AdjustedValue08,AdjustedValue09,AdjustedValue10,AdjustedValue11,AdjustedValue12				)) AS f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	END ELSE BEGIN	
		SELECT '#budget_basisIDs', * FROM #budget_basisIDs	
		SELECT '#projection_basisIDs', * FROM #projection_basisIDs	
	END
 END
GO


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

-- fp.procFlexDependentByDriverStatistics_InitialValue
CREATE   PROCEDURE [fp].[procFlexDependentByDriverStatistics_InitialValue]
	 @EntityGroupConfigID int,
	 @MonthsLoaded int,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0	
 AS
 	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI				Description
	 ** 1 	2020-12-16  MY  	JAZZ-11325	Initial
	 ** 2 	2021-02-18  BK  	JAZZ-15007	Add distinct to fix flexing inflation problem
	 ** 3 	2021-04-21  BK  	JAZZ-18500	Add ProviderID to flexing join
	 ** 4 	2023-06-29  MY  	JAZZ-53442	Update stats flexing to support x-department stats flexing
	 ** 5 	2023-02-29  MY  	JAZZ-68469	Cross Department Flexing Stats - Adjustments to source dept/acct 
										    changing dependent rate rather than value
	 *************************************************************/
	
 BEGIN

	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'
	EXEC [dbo].[procSysDropTempTable] '#itemsToFlex'
	EXEC [dbo].[procSysDropTempTable] '#flexedValues'
	EXEC [dbo].[procSysDropTempTable] '#driver'
	EXEC [dbo].[procSysDropTempTable] '#dependent'
	EXEC [dbo].[procSysDropTempTable] '#driverDepartments'
	EXEC [dbo].[procSysDropTempTable] '#dependentDepartments'
 
	DECLARE @BudgetConfigID INT = (SELECT DISTINCT TOP 1 BudgetConfigID 
								   FROM fp.EntityGroupConfig egc 
										INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID 
								   WHERE egc.EntityGroupConfigID = @EntityGroupConfigID)

	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'),
		@Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent')
 		 
	CREATE TABLE #itemsToFlex(DependentDepartmentID INT, DependentStatisticAccountID INT, DriverDepartmentID INT, DriverStatisticAccountID INT)
 
	-- populate a temporary list of items to flex
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #itemsToFlex (DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID)
		SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID
		FROM [fp].[FlexConfigMapping] fsc 
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID
		WHERE fsc.FlexingTypeID = 8  -- Stats by Stats
			AND fsc.EntityGroupConfigID = @EntityGroupConfigID
	END ELSE BEGIN
		INSERT INTO #itemsToFlex (DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID)
		SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID
		FROM [fp].[FlexConfigMapping] fsc
		WHERE fsc.FlexingTypeID = 8  -- Stats by Stats
			AND fsc.EntityGroupConfigID = @EntityGroupConfigID
	END

	SELECT DISTINCT DriverDepartmentID
	INTO #driverDepartments
	FROM #itemsToFlex

	SELECT DISTINCT DependentDepartmentID
	INTO #dependentDepartments
	FROM #itemsToFlex

	SELECT 
		fs.DepartmentID, 
		fs.AccountID, 
		fs.ProviderID,
		SUM(fs.InitialBudget01) AS NewBudgetValue01,
		SUM(fs.InitialBudget02) AS NewBudgetValue02,
		SUM(fs.InitialBudget03) AS NewBudgetValue03,
		SUM(fs.InitialBudget04) AS NewBudgetValue04,
		SUM(fs.InitialBudget05) AS NewBudgetValue05,
		SUM(fs.InitialBudget06) AS NewBudgetValue06,
		SUM(fs.InitialBudget07) AS NewBudgetValue07,
		SUM(fs.InitialBudget08) AS NewBudgetValue08,
		SUM(fs.InitialBudget09) AS NewBudgetValue09,
		SUM(fs.InitialBudget10) AS NewBudgetValue10,
		SUM(fs.InitialBudget11) AS NewBudgetValue11,
		SUM(fs.InitialBudget12) AS NewBudgetValue12,
		SUM(fs.InitialProjection01) AS NewProjectionValue01,
		SUM(fs.InitialProjection02) AS NewProjectionValue02,
		SUM(fs.InitialProjection03) AS NewProjectionValue03,
		SUM(fs.InitialProjection04) AS NewProjectionValue04,
		SUM(fs.InitialProjection05) AS NewProjectionValue05,
		SUM(fs.InitialProjection06) AS NewProjectionValue06,
		SUM(fs.InitialProjection07) AS NewProjectionValue07,
		SUM(fs.InitialProjection08) AS NewProjectionValue08,
		SUM(fs.InitialProjection09) AS NewProjectionValue09,
		SUM(fs.InitialProjection10) AS NewProjectionValue10,
		SUM(fs.InitialProjection11) AS NewProjectionValue11,
		SUM(fs.InitialProjection12) AS NewProjectionValue12
	INTO #driver
	FROM [fp].[FactStatistics] fs
		INNER JOIN #driverDepartments driver ON fs.DepartmentID = driver.DriverDepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID 
		AND fs.SubSectionID = @Driver
	GROUP BY fs.DepartmentID, fs.AccountID, fs.ProviderID

	SELECT 
		stat.DepartmentID,
		stat.AccountID,
		stat.ProviderID,
		stat.InitialBudgetRate01,
		stat.InitialBudgetRate02,
		stat.InitialBudgetRate03,
		stat.InitialBudgetRate04,
		stat.InitialBudgetRate05,
		stat.InitialBudgetRate06,
		stat.InitialBudgetRate07,
		stat.InitialBudgetRate08,
		stat.InitialBudgetRate09,
		stat.InitialBudgetRate10,
		stat.InitialBudgetRate11,
		stat.InitialBudgetRate12,
		stat.InitialProjectionRate01,
		stat.InitialProjectionRate02,
		stat.InitialProjectionRate03,
		stat.InitialProjectionRate04,
		stat.InitialProjectionRate05,
		stat.InitialProjectionRate06,
		stat.InitialProjectionRate07,
		stat.InitialProjectionRate08,
		stat.InitialProjectionRate09,
		stat.InitialProjectionRate10,
		stat.InitialProjectionRate11,
		stat.InitialProjectionRate12
	INTO #dependent
	FROM [fp].[FactStatistics] stat
		INNER JOIN #dependentDepartments depend ON stat.DepartmentID = depend.DependentDepartmentID
	WHERE stat.EntityGroupConfigID = @EntityGroupConfigID
		AND stat.SubSectionID = @Dependent

	SELECT dependent.DepartmentID, dependent.AccountID, dependent.ProviderID,
		SUM(dependent.InitialBudgetRate01 * driver.NewBudgetValue01) As FlexedBudget01,
		SUM(dependent.InitialBudgetRate02 * driver.NewBudgetValue02) As FlexedBudget02,
		SUM(dependent.InitialBudgetRate03 * driver.NewBudgetValue03) As FlexedBudget03,
		SUM(dependent.InitialBudgetRate04 * driver.NewBudgetValue04) As FlexedBudget04,
		SUM(dependent.InitialBudgetRate05 * driver.NewBudgetValue05) As FlexedBudget05,
		SUM(dependent.InitialBudgetRate06 * driver.NewBudgetValue06) As FlexedBudget06,
		SUM(dependent.InitialBudgetRate07 * driver.NewBudgetValue07) As FlexedBudget07,
		SUM(dependent.InitialBudgetRate08 * driver.NewBudgetValue08) As FlexedBudget08,
		SUM(dependent.InitialBudgetRate09 * driver.NewBudgetValue09) As FlexedBudget09,
		SUM(dependent.InitialBudgetRate10 * driver.NewBudgetValue10) As FlexedBudget10,
		SUM(dependent.InitialBudgetRate11 * driver.NewBudgetValue11) As FlexedBudget11,
		SUM(dependent.InitialBudgetRate12 * driver.NewBudgetValue12) As FlexedBudget12,
		SUM(dependent.InitialProjectionRate01 * driver.NewProjectionValue01) As FlexedProjection01,
		SUM(dependent.InitialProjectionRate02 * driver.NewProjectionValue02) As FlexedProjection02,
		SUM(dependent.InitialProjectionRate03 * driver.NewProjectionValue03) As FlexedProjection03,
		SUM(dependent.InitialProjectionRate04 * driver.NewProjectionValue04) As FlexedProjection04,
		SUM(dependent.InitialProjectionRate05 * driver.NewProjectionValue05) As FlexedProjection05,
		SUM(dependent.InitialProjectionRate06 * driver.NewProjectionValue06) As FlexedProjection06,
		SUM(dependent.InitialProjectionRate07 * driver.NewProjectionValue07) As FlexedProjection07,
		SUM(dependent.InitialProjectionRate08 * driver.NewProjectionValue08) As FlexedProjection08,
		SUM(dependent.InitialProjectionRate09 * driver.NewProjectionValue09) As FlexedProjection09,
		SUM(dependent.InitialProjectionRate10 * driver.NewProjectionValue10) As FlexedProjection10,
		SUM(dependent.InitialProjectionRate11 * driver.NewProjectionValue11) As FlexedProjection11,
		SUM(dependent.InitialProjectionRate12 * driver.NewProjectionValue12) As FlexedProjection12
	INTO #flexedValues
	FROM 
			#itemsToFlex fm
			INNER JOIN #dependent dependent	ON dependent.DepartmentID = fm.DependentDepartmentID AND dependent.AccountID = fm.DependentStatisticAccountID
			INNER JOIN #driver driver ON fm.DriverStatisticAccountID = driver.AccountID AND fm.DriverDepartmentID = driver.DepartmentID
	WHERE driver.ProviderID = dependent.ProviderID
	GROUP BY dependent.DepartmentID, dependent.AccountID, dependent.ProviderID
 
 	IF (@IsDebug = 0)
 	BEGIN 
 	
		-- flex projection data and reset the adjusted value as well
		UPDATE basis
		SET 
			basis.InitialBudget01 = flexed.FlexedBudget01,
			basis.InitialBudget02 = flexed.FlexedBudget02,
			basis.InitialBudget03 = flexed.FlexedBudget03,
			basis.InitialBudget04 = flexed.FlexedBudget04,
			basis.InitialBudget05 = flexed.FlexedBudget05,
			basis.InitialBudget06 = flexed.FlexedBudget06,
			basis.InitialBudget07 = flexed.FlexedBudget07,
			basis.InitialBudget08 = flexed.FlexedBudget08,
			basis.InitialBudget09 = flexed.FlexedBudget09,
			basis.InitialBudget10 = flexed.FlexedBudget10,
			basis.InitialBudget11 = flexed.FlexedBudget11,
			basis.InitialBudget12 = flexed.FlexedBudget12,
			basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN basis.InitialProjection01 ELSE flexed.FlexedProjection01 END,
			basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN basis.InitialProjection02 ELSE flexed.FlexedProjection02 END,
			basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN basis.InitialProjection03 ELSE flexed.FlexedProjection03 END,
			basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN basis.InitialProjection04 ELSE flexed.FlexedProjection04 END,
			basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN basis.InitialProjection05 ELSE flexed.FlexedProjection05 END,
			basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN basis.InitialProjection06 ELSE flexed.FlexedProjection06 END,
			basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN basis.InitialProjection07 ELSE flexed.FlexedProjection07 END,
			basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN basis.InitialProjection08 ELSE flexed.FlexedProjection08 END,
			basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN basis.InitialProjection09 ELSE flexed.FlexedProjection09 END,
			basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE flexed.FlexedProjection10 END,
			basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE flexed.FlexedProjection11 END,
			basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE flexed.FlexedProjection12 END   	
		FROM [fp].[FactStatistics] basis
    		 INNER JOIN #flexedValues flexed
				ON basis.DepartmentID = flexed.DepartmentID
					and basis.AccountID = flexed.AccountID
					and basis.ProviderID = flexed.ProviderID
		WHERE basis.UnitTypeID = 140
			AND basis.EntityGroupConfigID = @EntityGroupConfigID
			AND (
				basis.InitialBudget01 != flexed.FlexedBudget01 OR 
				basis.InitialBudget02 != flexed.FlexedBudget02 OR 
				basis.InitialBudget03 != flexed.FlexedBudget03 OR 
				basis.InitialBudget04 != flexed.FlexedBudget04 OR 
				basis.InitialBudget05 != flexed.FlexedBudget05 OR 
				basis.InitialBudget06 != flexed.FlexedBudget06 OR 
				basis.InitialBudget07 != flexed.FlexedBudget07 OR 
				basis.InitialBudget08 != flexed.FlexedBudget08 OR 
				basis.InitialBudget09 != flexed.FlexedBudget09 OR 
				basis.InitialBudget10 != flexed.FlexedBudget10 OR 
				basis.InitialBudget11 != flexed.FlexedBudget11 OR 
				basis.InitialBudget12 != flexed.FlexedBudget12 OR 
				basis.InitialProjection01 != flexed.FlexedProjection01 OR 
				basis.InitialProjection02 != flexed.FlexedProjection02 OR 
				basis.InitialProjection03 != flexed.FlexedProjection03 OR 
				basis.InitialProjection04 != flexed.FlexedProjection04 OR 
				basis.InitialProjection05 != flexed.FlexedProjection05 OR 
				basis.InitialProjection06 != flexed.FlexedProjection06 OR 
				basis.InitialProjection07 != flexed.FlexedProjection07 OR 
				basis.InitialProjection08 != flexed.FlexedProjection08 OR 
				basis.InitialProjection09 != flexed.FlexedProjection09 OR 
				basis.InitialProjection10 != flexed.FlexedProjection10 OR 
				basis.InitialProjection11 != flexed.FlexedProjection11 OR 
				basis.InitialProjection12 != flexed.FlexedProjection12)

	END ELSE BEGIN
		SELECT '#driver', * FROM #driver
		SELECT '#dependent', * FROM #dependent
		SELECT '#FilterByDepartment', * FROM #FilterByDepartment
		SELECT '#itemsToFlex', * FROM #itemsToFlex
		SELECT '#flexedValues', * FROM #flexedValues
	END
END
GO


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

-- fp.procFlexNonStaffingByStatistics_InitialValue
CREATE   PROCEDURE [fp].[procFlexNonStaffingByStatistics_InitialValue]
	 @EntityGroupConfigID int,
	 @MonthsLoaded int,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0	
 AS	
 BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1 	 2019-03-26  IP  	 B-22466		Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	** 2	 2021-04-13	 NN		 JAZZ-14121		Remove null joins on targeting
	** 3	 2023-02-07	 MY		 JAZZ-48980		Update flexing to support x-department flexing
	** 4	 2023-08-09	 BK		 JAZZ-58152		Update for new data structure
	** 5	 2023-08-25	 MY		 JAZZ-58152		Fix missed reference
	*************************************************************/
	
	-- Confluence: https://confluence.sdt.local/display/DD/Non-Staffing+Flexing+-+1
	
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'
	EXEC [dbo].[procSysDropTempTable] '#itemsToFlex'
	EXEC [dbo].[procSysDropTempTable] '#dollarPerUos'
	EXEC [dbo].[procSysDropTempTable] '#stats'
	EXEC [dbo].[procSysDropTempTable] '#flexed'
	EXEC [dbo].[procSysDropTempTable] '#gl'

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[viewGeneralLedgerDataForStatsToNonStaffing] st WITH (READUNCOMMITTED)	
		WHERE st.EntityGroupConfigID = @EntityGroupConfigID
			AND st.FlexingTypeID = 1 -- Non-Staffing
	END
 
	CREATE TABLE #itemsToFlex (DepartmentID INT, GLAccountID INT, StatAccountID INT, SourceDepartmentID INT)
 
	-- populate a temporary list of items to flex
	INSERT INTO #itemsToFlex(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT fsc.DepartmentID, fsc.GLAccountID, fsc.StatAccountID, fsc.SourceDepartmentID
    FROM [fp].[FlexConfigMapping] fsc
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID 
    WHERE fsc.FlexingTypeID = 1  -- NonStaffing
        AND fsc.EntityGroupConfigID = @EntityGroupConfigID

	CREATE TABLE #gl (GeneralLedgerID INT, DepartmentID INT, AccountID INT,
	InitialBudget01 DECIMAL(19,8),InitialBudget02 DECIMAL(19,8),InitialBudget03 DECIMAL(19,8),InitialBudget04 DECIMAL(19,8),InitialBudget05 DECIMAL(19,8),InitialBudget06 DECIMAL(19,8), 
	InitialBudget07 DECIMAL(19,8),InitialBudget08 DECIMAL(19,8),InitialBudget09 DECIMAL(19,8),InitialBudget10 DECIMAL(19,8),InitialBudget11 DECIMAL(19,8),InitialBudget12 DECIMAL(19,8), 
	InitialProjection01 DECIMAL(19,8),InitialProjection02 DECIMAL(19,8),InitialProjection03 DECIMAL(19,8),InitialProjection04 DECIMAL(19,8),InitialProjection05 DECIMAL(19,8),InitialProjection06 DECIMAL(19,8), 
	InitialProjection07 DECIMAL(19,8),InitialProjection08 DECIMAL(19,8),InitialProjection09 DECIMAL(19,8),InitialProjection10 DECIMAL(19,8),InitialProjection11 DECIMAL(19,8),InitialProjection12 DECIMAL(19,8),
	InitialBudgetDollarsPerUOS01 DECIMAL(19,8),InitialBudgetDollarsPerUOS02 DECIMAL(19,8),InitialBudgetDollarsPerUOS03 DECIMAL(19,8),InitialBudgetDollarsPerUOS04 DECIMAL(19,8),InitialBudgetDollarsPerUOS05 DECIMAL(19,8),InitialBudgetDollarsPerUOS06 DECIMAL(19,8), 
	InitialBudgetDollarsPerUOS07 DECIMAL(19,8),InitialBudgetDollarsPerUOS08 DECIMAL(19,8),InitialBudgetDollarsPerUOS09 DECIMAL(19,8),InitialBudgetDollarsPerUOS10 DECIMAL(19,8),InitialBudgetDollarsPerUOS11 DECIMAL(19,8),InitialBudgetDollarsPerUOS12 DECIMAL(19,8), 
	InitialProjectionDollarsPerUOS01 DECIMAL(19,8),InitialProjectionDollarsPerUOS02 DECIMAL(19,8),InitialProjectionDollarsPerUOS03 DECIMAL(19,8),InitialProjectionDollarsPerUOS04 DECIMAL(19,8),InitialProjectionDollarsPerUOS05 DECIMAL(19,8),InitialProjectionDollarsPerUOS06 DECIMAL(19,8), 
	InitialProjectionDollarsPerUOS07 DECIMAL(19,8),InitialProjectionDollarsPerUOS08 DECIMAL(19,8),InitialProjectionDollarsPerUOS09 DECIMAL(19,8),InitialProjectionDollarsPerUOS10 DECIMAL(19,8),InitialProjectionDollarsPerUOS11 DECIMAL(19,8),InitialProjectionDollarsPerUOS12 DECIMAL(19,8) 
	);
 
	SELECT 
		GeneralLedgerID,
		gl.DepartmentID,
		AccountID,
		InitialBudgetDollarsPerUOS01,
		InitialBudgetDollarsPerUOS02,
		InitialBudgetDollarsPerUOS03,
		InitialBudgetDollarsPerUOS04,
		InitialBudgetDollarsPerUOS05,
		InitialBudgetDollarsPerUOS06,
		InitialBudgetDollarsPerUOS07,
		InitialBudgetDollarsPerUOS08,
		InitialBudgetDollarsPerUOS09,
		InitialBudgetDollarsPerUOS10,
		InitialBudgetDollarsPerUOS11,
		InitialBudgetDollarsPerUOS12,
		InitialProjectionDollarsPerUOS01,
		InitialProjectionDollarsPerUOS02,
		InitialProjectionDollarsPerUOS03,
		InitialProjectionDollarsPerUOS04,
		InitialProjectionDollarsPerUOS05,
		InitialProjectionDollarsPerUOS06,
		InitialProjectionDollarsPerUOS07,
		InitialProjectionDollarsPerUOS08,
		InitialProjectionDollarsPerUOS09,
		InitialProjectionDollarsPerUOS10,
		InitialProjectionDollarsPerUOS11,
		InitialProjectionDollarsPerUOS12
	INTO #dollarPerUos
	FROM [fp].[GeneralLedger] gl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID 
	WHERE gl.EntityGroupConfigID = @EntityGroupConfigID 
		AND gl.VariabilityID = 2 
		
	-- Calculate the Stats for the Source Department/Stat Account combinations found in our flexing config
	SELECT 
		fs.DepartmentID AS SourceDepartmentID, 
		fs.AccountID,
		SUM(fs.InitialBudget01) as NewBudgetValue01,
		SUM(fs.InitialBudget02) as NewBudgetValue02,
		SUM(fs.InitialBudget03) as NewBudgetValue03,
		SUM(fs.InitialBudget04) as NewBudgetValue04,
		SUM(fs.InitialBudget05) as NewBudgetValue05,
		SUM(fs.InitialBudget06) as NewBudgetValue06,
		SUM(fs.InitialBudget07) as NewBudgetValue07,
		SUM(fs.InitialBudget08) as NewBudgetValue08,
		SUM(fs.InitialBudget09) as NewBudgetValue09,
		SUM(fs.InitialBudget10) as NewBudgetValue10,
		SUM(fs.InitialBudget11) as NewBudgetValue11,
		SUM(fs.InitialBudget12) as NewBudgetValue12,
		SUM(fs.InitialProjection01) as NewProjectionValue01,
		SUM(fs.InitialProjection02) as NewProjectionValue02,
		SUM(fs.InitialProjection03) as NewProjectionValue03,
		SUM(fs.InitialProjection04) as NewProjectionValue04,
		SUM(fs.InitialProjection05) as NewProjectionValue05,
		SUM(fs.InitialProjection06) as NewProjectionValue06,
		SUM(fs.InitialProjection07) as NewProjectionValue07,
		SUM(fs.InitialProjection08) as NewProjectionValue08,
		SUM(fs.InitialProjection09) as NewProjectionValue09,
		SUM(fs.InitialProjection10) as NewProjectionValue10,
		SUM(fs.InitialProjection11) as NewProjectionValue11,
		SUM(fs.InitialProjection12) as NewProjectionValue12
	INTO #stats
	FROM [fp].[FactStatistics] fs
		INNER JOIN (SELECT DISTINCT SourceDepartmentID, StatAccountID FROM #itemsToFlex) fl ON fs.DepartmentID = fl.SourceDepartmentID AND fl.StatAccountID = fs.AccountID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
	GROUP BY fs.DepartmentID, 
		fs.AccountID

	-- Calculate the stats at an individual flex config level.
	SELECT 
		fs.DepartmentID,
		fs.SourceDepartmentID,
		fs.StatAccountID,
		fs.GLAccountID,
		SUM(NewBudgetValue01) AS NewBudgetValue01,
		SUM(NewBudgetValue02) AS NewBudgetValue02,
		SUM(NewBudgetValue03) AS NewBudgetValue03,
		SUM(NewBudgetValue04) AS NewBudgetValue04,
		SUM(NewBudgetValue05) AS NewBudgetValue05,
		SUM(NewBudgetValue06) AS NewBudgetValue06,
		SUM(NewBudgetValue07) AS NewBudgetValue07,
		SUM(NewBudgetValue08) AS NewBudgetValue08,
		SUM(NewBudgetValue09) AS NewBudgetValue09,
		SUM(NewBudgetValue10) AS NewBudgetValue10,
		SUM(NewBudgetValue11) AS NewBudgetValue11,
		SUM(NewBudgetValue12) AS NewBudgetValue12,
		SUM(NewProjectionValue01) AS NewProjectionValue01,
		SUM(NewProjectionValue02) AS NewProjectionValue02,
		SUM(NewProjectionValue03) AS NewProjectionValue03,
		SUM(NewProjectionValue04) AS NewProjectionValue04,
		SUM(NewProjectionValue05) AS NewProjectionValue05,
		SUM(NewProjectionValue06) AS NewProjectionValue06,
		SUM(NewProjectionValue07) AS NewProjectionValue07,
		SUM(NewProjectionValue08) AS NewProjectionValue08,
		SUM(NewProjectionValue09) AS NewProjectionValue09,
		SUM(NewProjectionValue10) AS NewProjectionValue10,
		SUM(NewProjectionValue11) AS NewProjectionValue11,
		SUM(NewProjectionValue12) AS NewProjectionValue12
	INTO #statsBySourceDept
	FROM #itemsToFlex fs
		INNER JOIN #stats st ON fs.SourceDepartmentID = st.SourceDepartmentID AND fs.StatAccountID = st.AccountID
	GROUP BY fs.DepartmentID,		
		fs.SourceDepartmentID,
		fs.StatAccountID,
		fs.GLAccountID
		
	-- Group all of the data together and flex them by taking the Stats * $/UOS
	SELECT 
		uos.DepartmentID, 
		uos.AccountID,
		SUM(uos.InitialBudgetDollarsPerUOS01 * stat.NewBudgetValue01) As FlexedBudget01,
		SUM(uos.InitialBudgetDollarsPerUOS02 * stat.NewBudgetValue02) As FlexedBudget02,
		SUM(uos.InitialBudgetDollarsPerUOS03 * stat.NewBudgetValue03) As FlexedBudget03,
		SUM(uos.InitialBudgetDollarsPerUOS04 * stat.NewBudgetValue04) As FlexedBudget04,
		SUM(uos.InitialBudgetDollarsPerUOS05 * stat.NewBudgetValue05) As FlexedBudget05,
		SUM(uos.InitialBudgetDollarsPerUOS06 * stat.NewBudgetValue06) As FlexedBudget06,
		SUM(uos.InitialBudgetDollarsPerUOS07 * stat.NewBudgetValue07) As FlexedBudget07,
		SUM(uos.InitialBudgetDollarsPerUOS08 * stat.NewBudgetValue08) As FlexedBudget08,
		SUM(uos.InitialBudgetDollarsPerUOS09 * stat.NewBudgetValue09) As FlexedBudget09,
		SUM(uos.InitialBudgetDollarsPerUOS10 * stat.NewBudgetValue10) As FlexedBudget10,
		SUM(uos.InitialBudgetDollarsPerUOS11 * stat.NewBudgetValue11) As FlexedBudget11,
		SUM(uos.InitialBudgetDollarsPerUOS12 * stat.NewBudgetValue12) As FlexedBudget12,
		SUM(uos.InitialProjectionDollarsPerUOS01 * stat.NewProjectionValue01) As FlexedProjection01,
		SUM(uos.InitialProjectionDollarsPerUOS02 * stat.NewProjectionValue02) As FlexedProjection02,
		SUM(uos.InitialProjectionDollarsPerUOS03 * stat.NewProjectionValue03) As FlexedProjection03,
		SUM(uos.InitialProjectionDollarsPerUOS04 * stat.NewProjectionValue04) As FlexedProjection04,
		SUM(uos.InitialProjectionDollarsPerUOS05 * stat.NewProjectionValue05) As FlexedProjection05,
		SUM(uos.InitialProjectionDollarsPerUOS06 * stat.NewProjectionValue06) As FlexedProjection06,
		SUM(uos.InitialProjectionDollarsPerUOS07 * stat.NewProjectionValue07) As FlexedProjection07,
		SUM(uos.InitialProjectionDollarsPerUOS08 * stat.NewProjectionValue08) As FlexedProjection08,
		SUM(uos.InitialProjectionDollarsPerUOS09 * stat.NewProjectionValue09) As FlexedProjection09,
		SUM(uos.InitialProjectionDollarsPerUOS10 * stat.NewProjectionValue10) As FlexedProjection10,
		SUM(uos.InitialProjectionDollarsPerUOS11 * stat.NewProjectionValue11) As FlexedProjection11,
		SUM(uos.InitialProjectionDollarsPerUOS12 * stat.NewProjectionValue12) As FlexedProjection12
	INTO #flexed
    FROM (SELECT DISTINCT f.DepartmentID, f.GLAccountID, f.StatAccountID FROM #itemsToFlex f) fm
        INNER JOIN #dollarPerUos uos ON uos.DepartmentID = fm.DepartmentID AND uos.AccountID = fm.GLAccountID
        INNER JOIN #statsBySourceDept stat ON fm.StatAccountID = stat.StatAccountID 
			AND fm.DepartmentID = stat.DepartmentID
			AND uos.AccountID = stat.GLAccountID
	GROUP BY uos.DepartmentID, 
		uos.AccountID

	IF @IsDebug = 1
	BEGIN
		SELECT '#FilterByDepartment', * FROM #FilterByDepartment
		SELECT '#itemsToFlex', * FROM #itemsToFlex
		SELECT '#dollarPerUos', * FROM #dollarPerUos
		SELECT '#stats', * FROM #stats
		SELECT '#statsBySourceDept', * FROM #statsBySourceDept
		SELECT '#flexed', * FROM #flexed
	END ELSE 
	BEGIN

		-- flex projection data and reset the adjusted value as well
		UPDATE basis
		SET 
			basis.InitialBudget01 = abb.FlexedBudget01,
			basis.InitialBudget02 = abb.FlexedBudget02,
			basis.InitialBudget03 = abb.FlexedBudget03,
			basis.InitialBudget04 = abb.FlexedBudget04,
			basis.InitialBudget05 = abb.FlexedBudget05,
			basis.InitialBudget06 = abb.FlexedBudget06,
			basis.InitialBudget07 = abb.FlexedBudget07,
			basis.InitialBudget08 = abb.FlexedBudget08,
			basis.InitialBudget09 = abb.FlexedBudget09,
			basis.InitialBudget10 = abb.FlexedBudget10,
			basis.InitialBudget11 = abb.FlexedBudget11,
			basis.InitialBudget12 = abb.FlexedBudget12,
			basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN basis.InitialProjection01 ELSE abb.FlexedProjection01 END,
			basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN basis.InitialProjection02 ELSE abb.FlexedProjection02 END,
			basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN basis.InitialProjection03 ELSE abb.FlexedProjection03 END,
			basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN basis.InitialProjection04 ELSE abb.FlexedProjection04 END,
			basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN basis.InitialProjection05 ELSE abb.FlexedProjection05 END,
			basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN basis.InitialProjection06 ELSE abb.FlexedProjection06 END,
			basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN basis.InitialProjection07 ELSE abb.FlexedProjection07 END,
			basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN basis.InitialProjection08 ELSE abb.FlexedProjection08 END,
			basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN basis.InitialProjection09 ELSE abb.FlexedProjection09 END,
			basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE abb.FlexedProjection10 END,
			basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE abb.FlexedProjection11 END,
			basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE abb.FlexedProjection12 END   	
		FROM [fp].[GeneralLedger] basis
    		 INNER JOIN #flexed abb ON basis.DepartmentID = abb.DepartmentID AND basis.AccountID = abb.AccountID
		WHERE basis.VariabilityID = 2
			AND basis.EntityGroupConfigID = @EntityGroupConfigID
			AND (
					basis.InitialBudget01 != abb.FlexedBudget01 
				OR basis.InitialBudget02 != abb.FlexedBudget02 
				OR basis.InitialBudget03 != abb.FlexedBudget03 
				OR basis.InitialBudget04 != abb.FlexedBudget04
				OR basis.InitialBudget05 != abb.FlexedBudget05 
				OR basis.InitialBudget06 != abb.FlexedBudget06 
				OR basis.InitialBudget07 != abb.FlexedBudget07 
				OR basis.InitialBudget08 != abb.FlexedBudget08 
				OR basis.InitialBudget09 != abb.FlexedBudget09 
				OR basis.InitialBudget10 != abb.FlexedBudget10 
				OR basis.InitialBudget11 != abb.FlexedBudget11 
				OR basis.InitialBudget12 != abb.FlexedBudget12 
				OR basis.InitialProjection01 != abb.FlexedProjection01 
				OR basis.InitialProjection02 != abb.FlexedProjection02 
				OR basis.InitialProjection03 != abb.FlexedProjection03 
				OR basis.InitialProjection04 != abb.FlexedProjection04 
				OR basis.InitialProjection05 != abb.FlexedProjection05 
				OR basis.InitialProjection06 != abb.FlexedProjection06 
				OR basis.InitialProjection07 != abb.FlexedProjection07 
				OR basis.InitialProjection08 != abb.FlexedProjection08 
				OR basis.InitialProjection09 != abb.FlexedProjection09 
				OR basis.InitialProjection10 != abb.FlexedProjection10 
				OR basis.InitialProjection11 != abb.FlexedProjection11 
				OR basis.InitialProjection12 != abb.FlexedProjection12
			)

	END
	
END
GO


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

-- fp.procFlexRevenueByStatistics_InitialValue
CREATE   PROCEDURE [fp].[procFlexRevenueByStatistics_InitialValue]
	 @EntityGroupConfigID INT,
	 @MonthsLoaded INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug INT = 0
 AS
 BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI			  Description
	 ** 1 	 2019-03-26  IP  	 B-22466	  Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2	 2021-04-13	 NN		 JAZZ-14121	  Remove null joins on targeting
	 ** 3	 2023-02-07	 MY		 JAZZ-48980	  Update flexing to support x-department flexing
	 ** 4 	 2023-08-01  MY	     JAZZ-58153   Update to new structure
	 *************************************************************/	

	-- Confluence: https://confluence.sdt.local/display/DD/Revenue+Flexing+-+2

	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'
	EXEC [dbo].[procSysDropTempTable] '#itemsToFlex'
	EXEC [dbo].[procSysDropTempTable] '#dollarPerUosRates'
	EXEC [dbo].[procSysDropTempTable] '#stats'
	EXEC [dbo].[procSysDropTempTable] '#flexedValues'
	
	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[GeneralLedger] st WITH (READUNCOMMITTED)	
		WHERE st.EntityGroupConfigID = @EntityGroupConfigID
			AND st.FlexingTypeID = 2 -- Revenue
	END
	
	CREATE TABLE #itemsToFlex(DepartmentID INT, GLAccountID INT, StatAccountID INT, SourceDepartmentID INT)
 
	-- populate a temporary list of items to flex
	INSERT INTO #itemsToFlex(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT fcm.DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID
    FROM [fp].[FlexConfigMapping] fcm
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcm.DepartmentID -- We only want to filter on the department being flexed, not the source departments
    WHERE FlexingTypeID = 2  -- Revenue by Stats
        AND EntityGroupConfigID = @EntityGroupConfigID
 
	-- Pull out the rates for GL
	SELECT
		GeneralLedgerID,
		fgl.DepartmentID,
		AccountID,
		InitialBudgetDollarsPerUOS01 AS InitialBudget01,
		InitialBudgetDollarsPerUOS02 AS InitialBudget02,
		InitialBudgetDollarsPerUOS03 AS InitialBudget03,
		InitialBudgetDollarsPerUOS04 AS InitialBudget04,
		InitialBudgetDollarsPerUOS05 AS InitialBudget05,
		InitialBudgetDollarsPerUOS06 AS InitialBudget06,
		InitialBudgetDollarsPerUOS07 AS InitialBudget07,
		InitialBudgetDollarsPerUOS08 AS InitialBudget08,
		InitialBudgetDollarsPerUOS09 AS InitialBudget09,
		InitialBudgetDollarsPerUOS10 AS InitialBudget10,
		InitialBudgetDollarsPerUOS11 AS InitialBudget11,
		InitialBudgetDollarsPerUOS12 AS InitialBudget12,
		InitialProjectionDollarsPerUOS01 AS InitialProjection01,
		InitialProjectionDollarsPerUOS02 AS InitialProjection02,
		InitialProjectionDollarsPerUOS03 AS InitialProjection03,
		InitialProjectionDollarsPerUOS04 AS InitialProjection04,
		InitialProjectionDollarsPerUOS05 AS InitialProjection05,
		InitialProjectionDollarsPerUOS06 AS InitialProjection06,
		InitialProjectionDollarsPerUOS07 AS InitialProjection07,
		InitialProjectionDollarsPerUOS08 AS InitialProjection08,
		InitialProjectionDollarsPerUOS09 AS InitialProjection09,
		InitialProjectionDollarsPerUOS10 AS InitialProjection10,
		InitialProjectionDollarsPerUOS11 AS InitialProjection11,
		InitialProjectionDollarsPerUOS12 AS InitialProjection12
	INTO #dollarPerUosRates
	FROM [fp].[GeneralLedger] fgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID -- We only want to filter on the department being flexed, not the source departments
    WHERE EntityGroupConfigID = @EntityGroupConfigID 
		AND VariabilityID = 2
		
	-- Calculate the Stats for the Source Department/Stat Account combinations found in our flexing config
	SELECT 
		fs.DepartmentID AS SourceDepartmentID, 
		fs.AccountID,
		SUM(fs.InitialBudget01) as NewBudgetValue01,
		SUM(fs.InitialBudget02) as NewBudgetValue02,
		SUM(fs.InitialBudget03) as NewBudgetValue03,
		SUM(fs.InitialBudget04) as NewBudgetValue04,
		SUM(fs.InitialBudget05) as NewBudgetValue05,
		SUM(fs.InitialBudget06) as NewBudgetValue06,
		SUM(fs.InitialBudget07) as NewBudgetValue07,
		SUM(fs.InitialBudget08) as NewBudgetValue08,
		SUM(fs.InitialBudget09) as NewBudgetValue09,
		SUM(fs.InitialBudget10) as NewBudgetValue10,
		SUM(fs.InitialBudget11) as NewBudgetValue11,
		SUM(fs.InitialBudget12) as NewBudgetValue12,
		SUM(fs.InitialProjection01) as NewProjectionValue01,
		SUM(fs.InitialProjection02) as NewProjectionValue02,
		SUM(fs.InitialProjection03) as NewProjectionValue03,
		SUM(fs.InitialProjection04) as NewProjectionValue04,
		SUM(fs.InitialProjection05) as NewProjectionValue05,
		SUM(fs.InitialProjection06) as NewProjectionValue06,
		SUM(fs.InitialProjection07) as NewProjectionValue07,
		SUM(fs.InitialProjection08) as NewProjectionValue08,
		SUM(fs.InitialProjection09) as NewProjectionValue09,
		SUM(fs.InitialProjection10) as NewProjectionValue10,
		SUM(fs.InitialProjection11) as NewProjectionValue11,
		SUM(fs.InitialProjection12) as NewProjectionValue12
	INTO #stats
	FROM [fp].[FactStatistics] fs
		INNER JOIN (SELECT DISTINCT SourceDepartmentID, StatAccountID FROM #itemsToFlex) fl ON fs.DepartmentID = fl.SourceDepartmentID AND fl.StatAccountID = fs.AccountID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
	GROUP BY fs.DepartmentID, 
		fs.AccountID

	-- Calculate the stats at an individual flex config level.
	SELECT 
		fs.DepartmentID,
		fs.SourceDepartmentID,
		fs.StatAccountID,
		fs.GLAccountID,
		SUM(NewBudgetValue01) AS NewBudgetValue01,
		SUM(NewBudgetValue02) AS NewBudgetValue02,
		SUM(NewBudgetValue03) AS NewBudgetValue03,
		SUM(NewBudgetValue04) AS NewBudgetValue04,
		SUM(NewBudgetValue05) AS NewBudgetValue05,
		SUM(NewBudgetValue06) AS NewBudgetValue06,
		SUM(NewBudgetValue07) AS NewBudgetValue07,
		SUM(NewBudgetValue08) AS NewBudgetValue08,
		SUM(NewBudgetValue09) AS NewBudgetValue09,
		SUM(NewBudgetValue10) AS NewBudgetValue10,
		SUM(NewBudgetValue11) AS NewBudgetValue11,
		SUM(NewBudgetValue12) AS NewBudgetValue12,
		SUM(NewProjectionValue01) AS NewProjectionValue01,
		SUM(NewProjectionValue02) AS NewProjectionValue02,
		SUM(NewProjectionValue03) AS NewProjectionValue03,
		SUM(NewProjectionValue04) AS NewProjectionValue04,
		SUM(NewProjectionValue05) AS NewProjectionValue05,
		SUM(NewProjectionValue06) AS NewProjectionValue06,
		SUM(NewProjectionValue07) AS NewProjectionValue07,
		SUM(NewProjectionValue08) AS NewProjectionValue08,
		SUM(NewProjectionValue09) AS NewProjectionValue09,
		SUM(NewProjectionValue10) AS NewProjectionValue10,
		SUM(NewProjectionValue11) AS NewProjectionValue11,
		SUM(NewProjectionValue12) AS NewProjectionValue12
	INTO #statsBySourceDept
	FROM #itemsToFlex fs
		INNER JOIN #stats st ON fs.SourceDepartmentID = st.SourceDepartmentID AND fs.StatAccountID = st.AccountID
	GROUP BY fs.DepartmentID,		
		fs.SourceDepartmentID,
		fs.StatAccountID,
		fs.GLAccountID
		
	-- Group all of the data together and flex them by taking the Stats * $/UOS
	SELECT 
		uos.DepartmentID, 
		uos.AccountID,
		SUM(uos.InitialBudget01 * stat.NewBudgetValue01) As FlexedBudget01,
		SUM(uos.InitialBudget02 * stat.NewBudgetValue02) As FlexedBudget02,
		SUM(uos.InitialBudget03 * stat.NewBudgetValue03) As FlexedBudget03,
		SUM(uos.InitialBudget04 * stat.NewBudgetValue04) As FlexedBudget04,
		SUM(uos.InitialBudget05 * stat.NewBudgetValue05) As FlexedBudget05,
		SUM(uos.InitialBudget06 * stat.NewBudgetValue06) As FlexedBudget06,
		SUM(uos.InitialBudget07 * stat.NewBudgetValue07) As FlexedBudget07,
		SUM(uos.InitialBudget08 * stat.NewBudgetValue08) As FlexedBudget08,
		SUM(uos.InitialBudget09 * stat.NewBudgetValue09) As FlexedBudget09,
		SUM(uos.InitialBudget10 * stat.NewBudgetValue10) As FlexedBudget10,
		SUM(uos.InitialBudget11 * stat.NewBudgetValue11) As FlexedBudget11,
		SUM(uos.InitialBudget12 * stat.NewBudgetValue12) As FlexedBudget12,
		SUM(uos.InitialProjection01 * stat.NewProjectionValue01) As FlexedProjection01,
		SUM(uos.InitialProjection02 * stat.NewProjectionValue02) As FlexedProjection02,
		SUM(uos.InitialProjection03 * stat.NewProjectionValue03) As FlexedProjection03,
		SUM(uos.InitialProjection04 * stat.NewProjectionValue04) As FlexedProjection04,
		SUM(uos.InitialProjection05 * stat.NewProjectionValue05) As FlexedProjection05,
		SUM(uos.InitialProjection06 * stat.NewProjectionValue06) As FlexedProjection06,
		SUM(uos.InitialProjection07 * stat.NewProjectionValue07) As FlexedProjection07,
		SUM(uos.InitialProjection08 * stat.NewProjectionValue08) As FlexedProjection08,
		SUM(uos.InitialProjection09 * stat.NewProjectionValue09) As FlexedProjection09,
		SUM(uos.InitialProjection10 * stat.NewProjectionValue10) As FlexedProjection10,
		SUM(uos.InitialProjection11 * stat.NewProjectionValue11) As FlexedProjection11,
		SUM(uos.InitialProjection12 * stat.NewProjectionValue12) As FlexedProjection12
	INTO #flexedValues
    FROM (SELECT DISTINCT f.DepartmentID, f.GLAccountID, f.StatAccountID FROM #itemsToFlex f) fm
        INNER JOIN #dollarPerUosRates uos ON uos.DepartmentID = fm.DepartmentID AND uos.AccountID = fm.GLAccountID
        INNER JOIN #statsBySourceDept stat ON fm.StatAccountID = stat.StatAccountID 
			AND fm.DepartmentID = stat.DepartmentID
			AND uos.AccountID = stat.GLAccountID
	GROUP BY uos.DepartmentID, 
		uos.AccountID

	IF @IsDebug = 1
	BEGIN
		SELECT '#FilterByDepartment', * FROM #FilterByDepartment
		SELECT '#itemsToFlex', * FROM #itemsToFlex
		SELECT '#dollarPerUosRates', * FROM #dollarPerUosRates
		SELECT '#stats', * FROM #stats
		SELECT '#statsBySourceDept', * FROM #statsBySourceDept
		SELECT '#flexedValues', * FROM #flexedValues
	END ELSE 
	BEGIN

		-- flex projection data and reset the adjusted value as well
		UPDATE basis
		SET 
			basis.InitialBudget01 = flexed.FlexedBudget01,
			basis.InitialBudget02 = flexed.FlexedBudget02,
			basis.InitialBudget03 = flexed.FlexedBudget03,
			basis.InitialBudget04 = flexed.FlexedBudget04,
			basis.InitialBudget05 = flexed.FlexedBudget05,
			basis.InitialBudget06 = flexed.FlexedBudget06,
			basis.InitialBudget07 = flexed.FlexedBudget07,
			basis.InitialBudget08 = flexed.FlexedBudget08,
			basis.InitialBudget09 = flexed.FlexedBudget09,
			basis.InitialBudget10 = flexed.FlexedBudget10,
			basis.InitialBudget11 = flexed.FlexedBudget11,
			basis.InitialBudget12 = flexed.FlexedBudget12,
			basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN basis.InitialProjection01 ELSE flexed.FlexedProjection01 END,
			basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN basis.InitialProjection02 ELSE flexed.FlexedProjection02 END,
			basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN basis.InitialProjection03 ELSE flexed.FlexedProjection03 END,
			basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN basis.InitialProjection04 ELSE flexed.FlexedProjection04 END,
			basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN basis.InitialProjection05 ELSE flexed.FlexedProjection05 END,
			basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN basis.InitialProjection06 ELSE flexed.FlexedProjection06 END,
			basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN basis.InitialProjection07 ELSE flexed.FlexedProjection07 END,
			basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN basis.InitialProjection08 ELSE flexed.FlexedProjection08 END,
			basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN basis.InitialProjection09 ELSE flexed.FlexedProjection09 END,
			basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE flexed.FlexedProjection10 END,
			basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE flexed.FlexedProjection11 END,
			basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE flexed.FlexedProjection12 END   	
		FROM [fp].[GeneralLedger] basis
    		 INNER JOIN #flexedValues flexed ON basis.DepartmentID = flexed.DepartmentID AND basis.AccountID = flexed.AccountID
		WHERE basis.VariabilityID = 2
			AND basis.EntityGroupConfigID = @EntityGroupConfigID
			AND (
				   basis.InitialBudget01 != flexed.FlexedBudget01 
				OR basis.InitialBudget02 != flexed.FlexedBudget02 
				OR basis.InitialBudget03 != flexed.FlexedBudget03 
				OR basis.InitialBudget04 != flexed.FlexedBudget04 
				OR basis.InitialBudget05 != flexed.FlexedBudget05 
				OR basis.InitialBudget06 != flexed.FlexedBudget06 
				OR basis.InitialBudget07 != flexed.FlexedBudget07 
				OR basis.InitialBudget08 != flexed.FlexedBudget08 
				OR basis.InitialBudget09 != flexed.FlexedBudget09 
				OR basis.InitialBudget10 != flexed.FlexedBudget10 
				OR basis.InitialBudget11 != flexed.FlexedBudget11 
				OR basis.InitialBudget12 != flexed.FlexedBudget12 
				OR basis.InitialProjection01 != flexed.FlexedProjection01 
				OR basis.InitialProjection02 != flexed.FlexedProjection02 
				OR basis.InitialProjection03 != flexed.FlexedProjection03 
				OR basis.InitialProjection04 != flexed.FlexedProjection04 
				OR basis.InitialProjection05 != flexed.FlexedProjection05 
				OR basis.InitialProjection06 != flexed.FlexedProjection06 
				OR basis.InitialProjection07 != flexed.FlexedProjection07 
				OR basis.InitialProjection08 != flexed.FlexedProjection08 
				OR basis.InitialProjection09 != flexed.FlexedProjection09 
				OR basis.InitialProjection10 != flexed.FlexedProjection10 
				OR basis.InitialProjection11 != flexed.FlexedProjection11 
				OR basis.InitialProjection12 != flexed.FlexedProjection12
			)	

	END
END
GO


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

-- fp.procGLCopyNewItems
CREATE   PROCEDURE [fp].[procGLCopyNewItems]
	@SourceBudgetConfigID INT,
	@SourceEntityGroupConfigID INT,
	@BudgetConfigID INT,
	@EntityGroupConfigID INT
AS 
BEGIN

/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	8-15-2023  NT      JAZZ-58783		Data restructure changes
*************************************************************/

	
INSERT INTO [fp].[GeneralLedger] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, AddDate,
SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
IsNew)
SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, AddDate,
SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
IsNew
FROM [fp].[GeneralLedger] 
WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1

END
GO


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

-- fp.procGeneralLedgerApplySpread
CREATE   PROCEDURE [fp].[procGeneralLedgerApplySpread]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN	
	
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1    2018-12-04  BK      B-21418		Initial
	** 2	2018-12-11	MY		B-21444		Adding ability to unlock spread if inactive and fixing case where row in GL but not in benefits is not spread.
	** 3	2010-02-18	NL		B-22129		changing proc to use spread view instead of table directly (to incorporate global spreads)
	** 4	2019-07-31	NL		D-08581		updating the way spread remainder is allocated (w/feature flag)
	** 5	2019-11-01	MY		B-24221		removing CID 4's FF and making it always on
	** 6 	2022-08-09	JB		JAZZ-23177	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	** 7 	2023-07-14	BW		JAZZ-55784	Data model restructure
	** 8 	2024-01-22	MY		JAZZ-64799	History Viewer does not handle Spread Impact for Monthly Values
	*************************************************************/ 
	
	IF OBJECT_ID('tempdb..#tmpGL') IS NOT NULL DROP TABLE #tmpGL;
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#spreadsChangeHistory') IS NOT NULL DROP TABLE #spreadsChangeHistory;

	CREATE TABLE #tmpGL (GeneralLedgerID INT, DepartmentID INT, AccountID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
 
	CREATE TABLE #spreadsChangeHistory (
		GeneralLedgerID INT,
		OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
	);

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID)
		SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID	
		FROM [fp].[GeneralLedger] basis
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID	
		WHERE BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7
	END ELSE BEGIN
		INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID)
		SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID	
		FROM [fp].[GeneralLedger] basis
		WHERE BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7
	END
	
	UPDATE fgl 
	SET BudgetLockType = 6, BudgetLockFlag = 1
		, BudgetAdjusted01 = CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8))
		, BudgetAdjusted02 = 
			CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
		, BudgetAdjusted03 = 
			CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
		, BudgetAdjusted04 = 
			CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
		, BudgetAdjusted05 = 
			CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
		, BudgetAdjusted06 = 
			CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
		, BudgetAdjusted07 = 
			CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
		, BudgetAdjusted08 = 
			CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
		, BudgetAdjusted09 = 
			CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
		, BudgetAdjusted10 = 
			CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
		, BudgetAdjusted11 = 
			CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
		, BudgetAdjusted12 = 
			CASE WHEN SpreadPercentage12 != 0
			THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
			ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
	OUTPUT 
	    inserted.GeneralLedgerID, 
		deleted.BudgetAdjusted01, deleted.BudgetAdjusted02, deleted.BudgetAdjusted03, deleted.BudgetAdjusted04, deleted.BudgetAdjusted05, deleted.BudgetAdjusted06,
		deleted.BudgetAdjusted07, deleted.BudgetAdjusted08, deleted.BudgetAdjusted09, deleted.BudgetAdjusted10, deleted.BudgetAdjusted11, deleted.BudgetAdjusted12,
		inserted.BudgetAdjusted01, inserted.BudgetAdjusted02, inserted.BudgetAdjusted03, inserted.BudgetAdjusted04, inserted.BudgetAdjusted05, inserted.BudgetAdjusted06,
		inserted.BudgetAdjusted07, inserted.BudgetAdjusted08, inserted.BudgetAdjusted09, inserted.BudgetAdjusted10, inserted.BudgetAdjusted11, inserted.BudgetAdjusted12
	INTO
	    #spreadsChangeHistory (GeneralLedgerID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) 
	FROM [fp].[viewGeneralLedgerSpreads] gls 
		INNER JOIN [fp].[GeneralLedger] fgl ON gls.BudgetConfigID = fgl.BudgetConfigID AND gls.DepartmentID = fgl.DepartmentID AND gls.AccountID = fgl.AccountID
		INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID
	WHERE gls.IsInactive = 0	
		

	-- Unlock Spreads that are no longer active
	UPDATE fgl 
	SET BudgetLockType = 0, BudgetLockFlag = 0
	FROM [fp].[GeneralLedgerSpreads] gls -- We don't want to use the view here because the view filters out not specified records
		INNER JOIN [fp].[GeneralLedger] fgl ON gls.BudgetConfigID = fgl.BudgetConfigID AND gls.DepartmentID = fgl.DepartmentID AND gls.AccountID = fgl.AccountID
		INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID
	WHERE gls.IsInactive = 1 
		AND fgl.BudgetLockFlag = 1 
		AND fgl.BudgetLockType = 6

	-- Populate Change History
	IF EXISTS(SELECT 1 
			  FROM fp.BudgetConfigSetting setting
				INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
			  WHERE def.Name = 'Spreads Change History Logic Is Enabled'
			  	AND setting.Value = 1)
	BEGIN
		
		INSERT INTO fp.GeneralLedgerSpreadsChangeHistory (GeneralLedgerID, BudgetConfigID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
						OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,	NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
						NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
		SELECT GeneralLedgerID, @BudgetConfigID,
			ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0),
			ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0),
			ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0),
			ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0)
		FROM #spreadsChangeHistory
		WHERE 1 = 1
			AND (
				   OldValue01 != NewValue01
				OR OldValue02 != NewValue02
				OR OldValue03 != NewValue03
				OR OldValue04 != NewValue04
				OR OldValue05 != NewValue05
				OR OldValue06 != NewValue06
				OR OldValue07 != NewValue07
				OR OldValue08 != NewValue08
				OR OldValue09 != NewValue09
				OR OldValue10 != NewValue10
				OR OldValue11 != NewValue11
				OR OldValue12 != NewValue12
			)
	END
END
GO


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

-- fp.procGeneralLedgerApplySpreadItemized
CREATE   PROCEDURE [fp].[procGeneralLedgerApplySpreadItemized]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN	
	
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1    2021-03-16  MD      JAZZ-16700		Initial
	** 2 	2022-08-09  JB		JAZZ-23177		Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	** 3 	2023-07-17	BW		JAZZ-55784		Data model restructure
	** 4 	2024-03-15	AO		JAZZ-65797		GeneralLedgerItemizationDetail table rename
	*************************************************************/ 

	IF OBJECT_ID('tempdb..#tmpGL') IS NOT NULL DROP TABLE #tmpGL;
	IF OBJECT_ID('tempdb..#deletedItemizedAdjustments') IS NOT NULL DROP TABLE #deletedItemizedAdjustments;
	IF OBJECT_ID('tempdb..#removeSpreadLockAdjustments') IS NOT NULL DROP TABLE #removeSpreadLockAdjustments;
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	
	CREATE TABLE #tmpGL (GeneralLedgerID INT, DepartmentID INT, AccountID INT);
	CREATE TABLE #deletedItemizedAdjustments (OriginalCommentGUID uniqueidentifier, InverseCommentGUID uniqueidentifier);
	CREATE TABLE #removeSpreadLockAdjustments (DepartmentID INT, AccountID INT, CountExistingAdjustmentsWithSpreads INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
 
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID)
		SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID	
		FROM [fp].[GeneralLedger] basis
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID	
			LEFT JOIN fp.GeneralLedgerSpreads gls ON gls.BudgetConfigID = basis.BudgetConfigID AND basis.DepartmentID = gls.DepartmentID AND basis.AccountID = gls.AccountID
		WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 
			AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7
			AND gls.GlobalSpreadID = 0 OR gls.GlobalSpreadID is null

		INSERT INTO #deletedItemizedAdjustments (OriginalCommentGUID, InverseCommentGUID)
		select id.CommentGUID, idl.InverseAdjustmentCommentGUID
		FROM fp.GeneralLedgerFixedDetail id
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = id.DepartmentID	
			INNER JOIN fp.GeneralLedgerItemizationDetailLink idl ON id.CommentGUID = idl.OriginalAdjustmentCommentGUID
	END ELSE BEGIN
		INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID)
		SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID	
		FROM [fp].[GeneralLedger] basis
			LEFT JOIN fp.GeneralLedgerSpreads gls ON gls.BudgetConfigID = basis.BudgetConfigID AND basis.DepartmentID = gls.DepartmentID AND basis.AccountID = gls.AccountID
		WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 
			AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7
			AND gls.GlobalSpreadID = 0  OR gls.GlobalSpreadID is null

		INSERT INTO #deletedItemizedAdjustments (OriginalCommentGUID, InverseCommentGUID)
		select id.CommentGUID, idl.InverseAdjustmentCommentGUID
		FROM fp.GeneralLedgerFixedDetail id
			INNER JOIN fp.GeneralLedgerItemizationDetailLink idl ON id.CommentGUID = idl.OriginalAdjustmentCommentGUID
	END
	
	--Lock cells that have itemized adjustments with spreads
	UPDATE fgl 
	SET BudgetLockType = 6, BudgetLockFlag = 1
	FROM
	[fp].[GeneralLedgerFixedDetail] glid 
		INNER JOIN [fp].[GeneralLedger] fgl ON glid.BudgetConfigID = fgl.BudgetConfigID AND glid.DepartmentID = fgl.DepartmentID AND glid.AccountID = fgl.AccountID
		INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID
		LEFT JOIN #deletedItemizedAdjustments da on glid.CommentGUID = da.OriginalCommentGUID
		LEFT JOIN #deletedItemizedAdjustments da1 on glid.CommentGUID = da1.InverseCommentGUID	
	WHERE da.OriginalCommentGUID IS NULL AND glid.SpreadID > 0 AND glid.TimeClassID = 2 and fgl.VariabilityID = 1 AND da1.InverseCommentGUID IS NULL

	INSERT INTO #removeSpreadLockAdjustments (DepartmentID, AccountID, CountExistingAdjustmentsWithSpreads)	
	SELECT tmp.DepartmentID, tmp.AccountID, count(*)
	FROM	[fp].[GeneralLedgerFixedDetail] glid
			INNER JOIN [fp].[GeneralLedger] fgl ON glid.BudgetConfigID = fgl.BudgetConfigID AND glid.DepartmentID = fgl.DepartmentID AND glid.AccountID = fgl.AccountID
			INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID
			LEFT JOIN #deletedItemizedAdjustments da ON glid.CommentGUID = da.OriginalCommentGUID
			LEFT JOIN #deletedItemizedAdjustments da1 on glid.CommentGUID = da1.InverseCommentGUID		
		WHERE glid.SpreadID > 0 AND BudgetLockFlag = 1 AND BudgetLockType = 6 
			AND da.OriginalCommentGUID IS NULL 
			AND da1.InverseCommentGUID IS NULL
		GROUP BY tmp.DepartmentID, tmp.AccountID
		

	-- Unlock Spreads that are no longer active
	UPDATE fgl 
	SET BudgetLockType = 0, BudgetLockFlag = 0
	FROM
		[fp].[GeneralLedger] fgl
		INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID
		LEFT JOIN #removeSpreadLockAdjustments rsla on tmp.DepartmentID = rsla.DepartmentID AND tmp.AccountID = rsla.AccountID
	WHERE BudgetLockFlag = 1 AND BudgetLockType = 6 AND rsla.DepartmentID IS NULL

END
GO


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

-- fp.procGeneralLedgerBudgetStampOff
CREATE   PROCEDURE [fp].[procGeneralLedgerBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	01-31-2023  MY      JAZZ-48962		Initial Creation
	** 2	08-15-2023  MY      JAZZ-58778		Update budget stamp off process - GL
	** 3	01-03-2024  MZ      JAZZ-65385		Added Target TimeClass
	** 4	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	*************************************************************/

	-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Budgeted Time Class
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) FROM [int].[FactGL] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
   
	INSERT INTO [int].[FactGL] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID],
		[TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID])
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		acc.AccountID,
		acc.AccountCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		acc.inversion * Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value AS Value
		FROM (
			SELECT gl.GeneralLedgerID, gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, gl.DepartmentID, gl.AccountID, gl.FinancialReportingID, gl.APEModelSectionID, gl.VariabilityID, 
				gl.BudgetAdjusted01, gl.BudgetAdjusted02, gl.BudgetAdjusted03, gl.BudgetAdjusted04, gl.BudgetAdjusted05, gl.BudgetAdjusted06, gl.BudgetAdjusted07, 
				gl.BudgetAdjusted08, gl.BudgetAdjusted09, gl.BudgetAdjusted10, gl.BudgetAdjusted11, gl.BudgetAdjusted12
			FROM fp.GeneralLedger gl
			WHERE gl.BudgetConfigID = @BudgetConfigID
		) gl
			UNPIVOT (Value FOR FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
END
GO


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

-- fp.procGeneralLedgerProjectionStampOff
CREATE     PROCEDURE [fp].[procGeneralLedgerProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	11-10-2023  AO      JAZZ-62128		Initial Creation
	** 2	01-04-2024  MZ      JAZZ-65385		Added Target TimeClass and IsMonthsLoadedIncluded
	** 3	01-24-2024  MZ      JAZZ-64527		Fix Months Loaded
	** 4	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 5	04-03-2024	MZ		JAZZ-70053		Fix Month Loaded excluding logic
	*************************************************************/

	-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Projected Time Class
	-- and all months if months loaded included otherwise only months NOT loaded will be cleared
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) gl FROM [int].[FactGL] gl
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
		WHERE gl.FiscalYearID = @FiscalYear
			AND gl.TimeClassID = @TargetTimeClassID
			AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded)
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
   
	INSERT INTO [int].[FactGL] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID],
		[TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID])
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		acc.AccountID,
		acc.AccountCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		acc.inversion * Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value AS Value
		FROM (
			SELECT gl.GeneralLedgerID, gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, gl.DepartmentID, gl.AccountID, gl.FinancialReportingID, gl.APEModelSectionID, gl.VariabilityID, 
				gl.ProjectionAdjusted01, gl.ProjectionAdjusted02, gl.ProjectionAdjusted03, gl.ProjectionAdjusted04, gl.ProjectionAdjusted05, gl.ProjectionAdjusted06, gl.ProjectionAdjusted07, 
				gl.ProjectionAdjusted08, gl.ProjectionAdjusted09, gl.ProjectionAdjusted10, gl.ProjectionAdjusted11, gl.ProjectionAdjusted12
			FROM fp.GeneralLedger gl
			WHERE gl.BudgetConfigID = @BudgetConfigID
		) gl
			UNPIVOT (Value FOR FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
		AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded)
END
GO


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

-- fp.procGetAPDetailsDebug
CREATE   PROCEDURE [fp].[procGetAPDetailsDebug]
	 @BudgetConfigID INT = 0
 AS
 BEGIN
	
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	2-13-2023  MY      JAZZ-XXXXX		Initial
	** 2	2-15-2023  MY      JAZZ-XXXXX		Added Chunking Config and Sorting
	*************************************************************/

	-- Note about this proc, it's used in the SSMS Extension, but can also be called to get a high level view of all settings in the system
		
	EXEC [dbo].[procSysDropTempTable] '#settings'
	EXEC [dbo].[procSysDropTempTable] '#budgetConfig'

	IF (@BudgetConfigID = 0)
		SET @BudgetConfigID = (SELECT BudgetConfigID FROM fp.BudgetConfig WHERE IsActive = 1)
	
	CREATE TABLE #settings (
		Name NVARCHAR(MAX) NOT NULL DEFAULT(''),
		SourceTable NVARCHAR(MAX) NOT NULL DEFAULT(''),
		Category NVARCHAR(50) NOT NULL DEFAULT(''),
		Value NVARCHAR(MAX) NOT NULL DEFAULT(''), -- Using this because the value could be anything
		Description NVARCHAR(MAX) NOT NULL DEFAULT(''),
		EntityGroupConfigName NVARCHAR(MAX) NOT NULL DEFAULT(''),
		SortOrder INT NOT NULL DEFAULT(1) -- Defaulting to 1 so that anything with 0 can show up first
	);

	----------------------------------------------------------------
	-- Budget Config
	----------------------------------------------------------------

	---- I know what you are thinking and yes, this is easier than having a huge wall of unions and this is dynamic at least...
	DECLARE @Sql NVARCHAR(MAX) = 'SELECT ';
	DECLARE @ColumnName VARCHAR(MAX);

	DECLARE cursor_config CURSOR
	FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'BudgetConfig' AND TABLE_SCHEMA = 'fp'
	OPEN cursor_config;

	FETCH NEXT FROM cursor_config INTO @ColumnName;

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @Sql = @Sql + 'CAST([' + @ColumnName + '] AS NVARCHAR(MAX)) AS [' + @ColumnName + '],' + CHAR(10);

		FETCH NEXT FROM cursor_config INTO @ColumnName;
	END;

	CLOSE cursor_config;
	DEALLOCATE cursor_config;

	SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return
	SET @Sql = LEFT(@Sql, LEN(@Sql) - 1);		  -- Remove last comma

	SET @Sql = @Sql + CHAR(10) + 'INTO #budgetConfig' + CHAR(10);
	SET @Sql = @Sql + 'FROM fp.BudgetConfig' + CHAR(10);
	SET @Sql = @Sql + 'WHERE BudgetConfigID = ' + CAST(@BudgetConfigID AS NVARCHAR(MAX)) + CHAR(10) + CHAR(10);
	
	SET @Sql = @Sql + 'INSERT INTO #settings (Name, SourceTable, Category, Value, Description, SortOrder)' + CHAR(10);
	SET @Sql = @Sql + 'SELECT ColumnName, ''fp.BudgetConfig'', ''Plan Config'', ColumnValue, '''', 0' + CHAR(10);
	SET @Sql = @Sql + 'FROM #budgetConfig' + CHAR(10);
	SET @Sql = @Sql + 'UNPIVOT(ColumnValue For ColumnName IN (' + CHAR(10);
	
	DECLARE cursor_config CURSOR
	FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'BudgetConfig' AND TABLE_SCHEMA = 'fp'
	OPEN cursor_config;

	FETCH NEXT FROM cursor_config INTO @ColumnName;

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @Sql = @Sql + @ColumnName + ',' + CHAR(10);

		FETCH NEXT FROM cursor_config INTO @ColumnName;
	END;

	CLOSE cursor_config;
	DEALLOCATE cursor_config;
	
	SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return
	SET @Sql = LEFT(@Sql, LEN(@Sql) - 1);		  -- Remove last comma

	SET @Sql = @Sql + ')) AS f' + CHAR(10);

	EXECUTE sp_executesql @Sql

	----------------------------------------------------------------
	-- Entity Group Config
	----------------------------------------------------------------

	DECLARE @EntityGroupConfigName VARCHAR(MAX);

	DECLARE cursor_egc CURSOR
	FOR SELECT Name FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE bc.BudgetConfigID = @BudgetConfigID
	OPEN cursor_egc;

	FETCH NEXT FROM cursor_egc INTO @EntityGroupConfigName;

	WHILE @@FETCH_STATUS = 0
	BEGIN
    
		SET @Sql = 'SELECT ';

		DECLARE cursor_config CURSOR
		FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'EntityGroupConfig' AND TABLE_SCHEMA = 'fp'
		OPEN cursor_config;

		FETCH NEXT FROM cursor_config INTO @ColumnName;

		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @Sql = @Sql + 'CAST([' + @ColumnName + '] AS NVARCHAR(MAX)) AS [' + @ColumnName + '],' + CHAR(10);
			FETCH NEXT FROM cursor_config INTO @ColumnName;
		END;

		CLOSE cursor_config;
		DEALLOCATE cursor_config;

		SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return
		SET @Sql = LEFT(@Sql, LEN(@Sql) - 1);		  -- Remove last comma

		SET @Sql = @Sql + CHAR(10) + 'INTO #entityGroupConfig' + CHAR(10);
		SET @Sql = @Sql + 'FROM fp.EntityGroupConfig' + CHAR(10);
		SET @Sql = @Sql + 'WHERE BudgetConfigGUID = ' + '''' + CAST((SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) AS NVARCHAR(MAX)) + '''' + CHAR(10) + CHAR(10);
	
		SET @Sql = @Sql + 'INSERT INTO #settings (Name, SourceTable, Category, Value, Description, EntityGroupConfigName, SortOrder)' + CHAR(10);
		SET @Sql = @Sql + 'SELECT ColumnName, ''fp.EntityGroupConfig'', ''Entity Group Config'', ColumnValue, '''', '+ '''' + @EntityGroupConfigName + ''', 0' + CHAR(10);
		SET @Sql = @Sql + 'FROM #entityGroupConfig' + CHAR(10);
		SET @Sql = @Sql + 'UNPIVOT(ColumnValue For ColumnName IN (' + CHAR(10);
	
		DECLARE cursor_config CURSOR
		FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'EntityGroupConfig' AND TABLE_SCHEMA = 'fp'
		OPEN cursor_config;

		FETCH NEXT FROM cursor_config INTO @ColumnName;

		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @Sql = @Sql + @ColumnName + ',' + CHAR(10);

			FETCH NEXT FROM cursor_config INTO @ColumnName;
		END;

		CLOSE cursor_config;
		DEALLOCATE cursor_config;
	
		SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return
		SET @Sql = LEFT(@Sql, LEN(@Sql) - 1);		  -- Remove last comma

		SET @Sql = @Sql + ')) AS f' + CHAR(10);

		EXECUTE sp_executesql @Sql

		FETCH NEXT FROM cursor_egc INTO @EntityGroupConfigName;
	END;

	CLOSE cursor_egc;
	DEALLOCATE cursor_egc;

	----------------------------------------------------------------
	-- Entity Group Config Mapping
	----------------------------------------------------------------  

	INSERT INTO #settings (Name, SourceTable, Category, Value, Description, EntityGroupConfigName)
	SELECT 'EntityID', 'fp.EntityGroupConfigMapping', 'Entity Group Config', egcm.EntityID, e.Name, egc.Name
	FROM fp.EntityGroupConfigMapping egcm
		INNER JOIN fw.DimEntity e ON egcm.EntityID = e.EntityID
		INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
		INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID		
	
	----------------------------------------------------------------
	-- Other Settings
	----------------------------------------------------------------  

	INSERT INTO #settings (Name, SourceTable, Category, Value, Description)
	SELECT
		Name, 
		'fp.SystemSetting',
		'Feature Flag' AS Category,
		Value,
		Description
	FROM fp.SystemSetting
	WHERE IsFeatureFlag = 1

	INSERT INTO #settings (Name, SourceTable, Category, Value, Description)
	SELECT
		Name, 
		'fp.SystemSetting',
		'System Setting' AS Category,
		Value,
		Description
	FROM fp.SystemSetting
	WHERE IsFeatureFlag = 0
	
	INSERT INTO #settings (Name, SourceTable, Category, Value, Description)
	SELECT 
		Name, 
		'fp.viewBudgetConfigSetting',
		'Plan-Level Feature Flag' AS Category,
		Value,
		Description
	FROM fp.viewBudgetConfigSetting
	WHERE BudgetConfigID = @BudgetConfigID

	INSERT INTO #settings (Name, SourceTable, Category, Value, Description, SortOrder)
	SELECT 'IsChunkingEnabled - ' + Description, 'fp.AdjustmentChunkingConfiguration',	'Chunking Configuration', IsChunkingEnabled, '', 2 FROM fp.AdjustmentChunkingConfiguration
	UNION ALL	
	SELECT 'MaxAdjustmentsPerChunk - ' + Description, 'fp.AdjustmentChunkingConfiguration', 'Chunking Configuration', MaxAdjustmentsPerChunk, '', 2 FROM fp.AdjustmentChunkingConfiguration
	UNION ALL	
	SELECT 'MaxImportAdjustmentsPerChunk - ' + Description, 'fp.AdjustmentChunkingConfiguration', 'Chunking Configuration', MaxImportAdjustmentsPerChunk, '', 2 FROM fp.AdjustmentChunkingConfiguration
	UNION ALL	
	SELECT 'MaxAdjustmentRecordCountForChunking - ' + Description, 'fp.AdjustmentChunkingConfiguration', 'Chunking Configuration', MaxAdjustmentRecordCountForChunking, '', 2 FROM fp.AdjustmentChunkingConfiguration

	SELECT Name, SourceTable, Category, Value, Description, EntityGroupConfigName FROM #settings ORDER BY SortOrder, SourceTable, Category, EntityGroupConfigName

 END;
GO


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

-- fp.procGetChargeVolumeUosData
CREATE PROCEDURE [fp].[procGetChargeVolumeUosData]
 @BudgetConfigID INT, 
 @DepartmentID INT, 
 @UnitTypeID TINYINT, 
 @TimeClassID TINYINT, 
 @IsLoadingRvuByEntity BIT, 
 @IsLoadingRvuByPatientClass BIT
 AS
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2021-11-10  NT          JAZZ-26946     Initial. This is a replacement for func fp.viewChargeVolumeUosDataQuery, which is not the most efficient.
** 2    2021-11-17  MD          JAZZ-27519     Update data pull to honor IsDollarsRemovedFromCharges flag on budget config
** 3 	2023-04-03	BW			JAZZ-52557	   Updated for new data model, use [fp].[ChargeVolume]
*********************************************************************/
BEGIN
	SELECT
		h.BudgetConfigID,
		h.DepartmentID,
		COALESCE(xwalk.AccountID, 0) AS AccountID,
		CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END as AccountName,
		h.EntityID,
		h.PatientClassID,
		pc.Name As PatientClassName,
		h.ChargeCodeID,
		cc.Name As ChargeCodeName,
		h.TimeClassID,
		h.UnitTypeID,
		SUM(h.Value) AS Value,
		SUM(h.OriginalValue) AS OriginalValue,
		SUM(h.ManagerValue) AS ManagerValue,
		COALESCE(fcm.ChargeRate1, 0) AS ChargeRate, -- Note: this is a bug, we cannot assume they are using charge rate 1.
		COALESCE(xwalk.RVUWeight, 0) AS RVUWeight
	FROM 
	(
		SELECT
			h.BudgetConfigID,
			h.DepartmentID,
			h.EntityGroupConfigID,
			h.EntityID,
			h.PatientClassID,
			h.ChargeCodeID,
			@TimeClassID AS TimeClassID,
			@UnitTypeID AS UnitTypeID,
			0 AS Value,
			SUM(CASE 
				WHEN @TimeClassID = 2 AND @UnitTypeID = 145 THEN InitialBudgetTotal
				WHEN @TimeClassID = 12 AND @UnitTypeID = 145 THEN InitialProjectionTotal
				WHEN @TimeClassID = 2 AND @UnitTypeID = 34 THEN InitialBudgetDollarsTotal
				WHEN @TimeClassID = 12 AND @UnitTypeID = 34 THEN InitialProjectionDollarsTotal
				END) AS OriginalValue,
			0 AS ManagerValue
		FROM
			[fp].[ChargeVolume] h
		WHERE
			h.DepartmentID = @DepartmentID
			and h.BudgetConfigID = @BudgetConfigID
		GROUP BY 
			h.BudgetConfigID,
			h.DepartmentID,
			h.EntityGroupConfigID,
			h.EntityID,
			h.PatientClassID,
			h.ChargeCodeID,
			h.UnitTypeID
		UNION ALL
		SELECT
			h.BudgetConfigID,
			h.DepartmentID,
			h.EntityGroupConfigID,
			h.EntityID,
			h.PatientClassID,
			h.ChargeCodeID,
			@TimeClassID AS TimeClassID,
			@UnitTypeID AS UnitTypeID,
			SUM(CASE 
			WHEN @UnitTypeID = 145 THEN TargetAdjustedTotal 
			WHEN @UnitTypeID = 34 THEN TargetDollarsAdjustedTotal
			END) AS Value,
			0 AS OriginalValue,
			SUM(CASE 
			WHEN @UnitTypeID = 145 THEN BudgetAdjustedTotal
			WHEN @UnitTypeID = 34 THEN BudgetDollarsAdjustedTotal
			END) AS ManagerValue
		FROM
			[fp].[ChargeVolume] h
		WHERE
			h.DepartmentID = @DepartmentID
			AND h.BudgetConfigID = @BudgetConfigID
			AND @TimeClassID = 2
		GROUP BY 
			h.BudgetConfigID,
			h.DepartmentID,
			h.EntityGroupConfigID,
			h.EntityID,
			h.PatientClassID,
			h.ChargeCodeID,
			h.UnitTypeID
		UNION ALL
		SELECT
			h.BudgetConfigID,
			h.DepartmentID,
			h.EntityGroupConfigID,
			h.EntityID,
			h.PatientClassID,
			h.ChargeCodeID,
			@TimeClassID AS TimeClassID,
			@UnitTypeID AS UnitTypeID,
			SUM(CASE 
			WHEN @UnitTypeID = 145 THEN ProjectionAdjustedTotal
			WHEN @UnitTypeID = 34 THEN ProjectionDollarsAdjustedTotal
			END) AS Value,
			0 AS OriginalValue,
			SUM(CASE 
			WHEN @UnitTypeID = 145 THEN ProjectionAdjustedTotal
			WHEN @UnitTypeID = 34 THEN ProjectionDollarsAdjustedTotal END) AS ManagerValue
		FROM
			[fp].[ChargeVolume] h
		WHERE
			h.DepartmentID = @DepartmentID
			AND h.BudgetConfigID = @BudgetConfigID
			AND @TimeClassID = 12
		GROUP BY 
			h.BudgetConfigID,
			h.DepartmentID,
			h.EntityGroupConfigID,
			h.EntityID,
			h.PatientClassID,
			h.ChargeCodeID,
			h.UnitTypeID
	) h
	LEFT JOIN [fp].[FactChargeMaster] fcm 
	ON fcm.BudgetConfigID = h.BudgetConfigID
	AND fcm.ChargeCodeID = h.ChargeCodeID
	AND fcm.TimeClassID = h.TimeClassID
	AND (@IsLoadingRvuByEntity = 0 OR fcm.EntityID = h.EntityID)
	AND (@IsLoadingRvuByPatientClass = 0 OR fcm.PatientClassID = h.PatientClassID)
	INNER JOIN [fw].[DimChargeCode] cc 
	ON h.ChargeCodeID = cc.ChargeCodeID
	INNER JOIN [fw].[DimPatientClass] pc 
	ON h.PatientClassID = pc.PatientClassID
	LEFT JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] xwalk 
	ON h.ChargeCodeID = xwalk.ChargeCodeID 
	AND h.EntityGroupConfigID = xwalk.EntityGroupConfigID
	AND h.DepartmentID = xwalk.DepartmentID 
	AND h.PatientClassID = xwalk.PatientClassID
	LEFT JOIN [fw].[DimAccount] acct 
	ON xwalk.AccountID = acct.AccountID
	GROUP BY h.BudgetConfigID,
		h.DepartmentID,
		h.EntityID,
		h.PatientClassID,
		pc.Name,
		h.ChargeCodeID,
		cc.Name,
		h.TimeClassID,
		h.UnitTypeID,
		fcm.ChargeRate1,
		xwalk.RVUWeight, 
		xwalk.AccountID,
		acct.Name
	ORDER BY h.DepartmentID, pc.Name, cc.Name, CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END
	OPTION (RECOMPILE)
 
 END
GO


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

-- fp.procGetDepartmentChargeVolumeHistoricalData
CREATE PROCEDURE [fp].[procGetDepartmentChargeVolumeHistoricalData]  
  @BudgetConfigID INT, 
  @DepartmentID INT, 
  @UnitTypeID INT
 AS
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2021-11-10  NT          JAZZ-26946     Initial. This is a replacement for func fp.viewDepartmentChargeVolumeHistoricalDataQuery, which is not the most efficient.
** 2    2021-11-17  MD          JAZZ-27519     Updating proc to honor IsDollarsRemovedFromCharges flag on budget config
** 3    2023-04-03  BW          JAZZ-52557     Updated for new data model, use [fp].[ChargeVolume]
*********************************************************************/
 BEGIN

	SELECT 
			fcv.DepartmentID,
			COALESCE(xwalk.AccountID, 0) AS AccountID,
			CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END as AccountName,
			fcv.EntityID,
			fcv.PatientClassID,
			pc.Name as PatientClassName,
			fcv.ChargeCodeID,
			cc.Name AS ChargeCodeName,
			@UnitTypeID AS UnitTypeID,
			SUM(CASE WHEN @UnitTypeID = 145 THEN PriorYearActualValueTotal ELSE PriorYearActualDollarValueTotal END) AS Actual,
			SUM(CASE WHEN @UnitTypeID = 145 THEN ActualYTDValueTotal ELSE ActualYTDDollarValueTotal END) AS ActualYTD
		FROM [fp].[ChargeVolumeHistory] h
		INNER JOIN [fp].[ChargeVolume] fcv 
			ON h.ChargeVolumeID = fcv.ChargeVolumeID
		LEFT JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] xwalk 
			ON fcv.ChargeCodeID = xwalk.ChargeCodeID 
			AND fcv.EntityGroupConfigID = xwalk.EntityGroupConfigID
			AND fcv.DepartmentID = xwalk.DepartmentID 
			AND fcv.PatientClassID = xwalk.PatientClassID
		LEFT JOIN [fw].[DimAccount] acct on xwalk.AccountID = acct.AccountID
		INNER JOIN [fw].[DimChargeCode] cc on fcv.ChargeCodeID = cc.ChargeCodeID
		INNER JOIN [fw].[DimPatientClass] pc on fcv.PatientClassID = pc.PatientClassID	
		WHERE 
			fcv.DepartmentID = @DepartmentID
			AND fcv.BudgetConfigID = @BudgetConfigID
		GROUP BY 
			fcv.DepartmentID,
			fcv.EntityID,
			fcv.PatientClassID,
			fcv.ChargeCodeID,
			fcv.UnitTypeID,
			xwalk.AccountID,
			acct.Name,
			pc.Name,
			cc.Name
		ORDER BY fcv.DepartmentID, pc.Name, cc.Name, CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END  
		OPTION (RECOMPILE)
 END
GO


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

-- fp.procGetFlexingExceptionReport
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	05-18-2023  MY      JAZZ-55153		Updated view to restructure
** 2	08-25-2023  MY      JAZZ-59500		Updated view to restructure
*************************************************************/
CREATE   PROCEDURE fp.procGetFlexingExceptionReport
 AS
 BEGIN
	CREATE TABLE #Results (BudgetConfigID INT, FlexingMethodID INT, FlexingTypeID INT, DepartmentID INT, DepartmentName NVARCHAR(500), AccountID INT, AccountName NVARCHAR(500), Message NVARCHAR(MAX))

	SELECT config.*, efc.EntityGroupConfigID 
	INTO #StatisticsFlexing
	FROM [fp].[StatisticsFlexingConfig] config
		INNER JOIN [fp].[EntityGroupConfig] efc ON config.EntityGroupConfigGUID = efc.EntityGroupConfigGUID
	WHERE FlexMethodID != 6
	
	INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, AccountID, Message)
	SELECT DISTINCT fs.BudgetConfigID, 10, 5, fs.DepartmentID, fs.AccountID, 'Department contains an account to be flexed by total charge code budget, but has no charge volumes.'
	FROM [fp].[FactStatistics] fs
		INNER JOIN #StatisticsFlexing config ON fs.EntityGroupConfigID = config.EntityGroupConfigID AND fs.AccountID = config.AccountID
		LEFT JOIN [fp].[ChargeVolume] cv 
			ON fs.EntityGroupConfigID = cv.EntityGroupConfigID
			AND fs.DepartmentID = cv.DepartmentID
	WHERE config.FlexMethodID = 10
		AND cv.ChargeVolumeID IS NULL
		
	INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, AccountID, Message)
	SELECT DISTINCT fs.BudgetConfigID, 9, 5, fs.DepartmentID, fs.AccountID, 'Department contains a patient class to be flexed by charge code budget, but has no charge volumes.'
	FROM [fp].[FactStatistics] fs
		INNER JOIN #StatisticsFlexing config ON fs.EntityGroupConfigID = config.EntityGroupConfigID AND fs.AccountID = config.AccountID
		LEFT JOIN [fp].[ChargeVolume] cv 
			ON fs.EntityGroupConfigID = cv.EntityGroupConfigID
			AND fs.DepartmentID = cv.DepartmentID
			AND fs.PatientClassID = cv.PatientClassID
	WHERE config.FlexMethodID = 9
		AND cv.ChargeVolumeID IS NULL
	
	INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, AccountID, Message)
	SELECT DISTINCT basis.BudgetConfigID, config.FlexMethodID, 2, basis.AccountID, 'Account is marked to flex, but has no accounts in Statistics.'
	FROM [fp].[FactStatistics] basis
		LEFT JOIN #StatisticsFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.AccountID = config.AccountID
	WHERE config.AccountID IS NULL
	
	SELECT config.*, efc.EntityGroupConfigID 
	INTO #RevenueFlexing
	FROM [fp].[RevenueExpenseFlexingConfig] config
		INNER JOIN [fp].[EntityGroupConfig] efc ON config.EntityGroupConfigGUID = efc.EntityGroupConfigGUID
	WHERE FlexMethodID NOT IN (2, 6)
	
	INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, Message)
	SELECT DISTINCT basis.BudgetConfigID, 3, 2, basis.DepartmentID, 'Department is marked to be flexed by charge code budget, but has no charge volumes.'
	FROM [fp].[FactGeneralLedger] basis
		INNER JOIN #RevenueFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.DepartmentID = config.DepartmentID
		LEFT JOIN [fp].[ChargeVolume] cv 
			ON basis.EntityGroupConfigID = cv.EntityGroupConfigID
			AND basis.DepartmentID = cv.DepartmentID
	WHERE config.FlexMethodID = 3
		AND cv.ChargeVolumeID IS NULL
		
	INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, Message)
	SELECT DISTINCT basis.BudgetConfigID, config.FlexMethodID, 2, basis.DepartmentID, 'Department is marked to flex, but has no accounts in GL.'
	FROM [fp].[GeneralLedger] basis
		LEFT JOIN #RevenueFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.DepartmentID = config.DepartmentID
	WHERE config.DepartmentID IS NULL
	
	INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, Message)
	SELECT DISTINCT basis.BudgetConfigID, config.FlexMethodID, 2, basis.DepartmentID, 'Department is marked to be flexed by statistics, but has no primary statistics.'
	FROM [fp].[GeneralLedger] basis
		INNER JOIN #RevenueFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.DepartmentID = config.DepartmentID
		INNER JOIN [fp].[PrimaryStatisticsConfig] prim ON prim.EntityGroupConfigGUID = config.EntityGroupConfigGUID
		LEFT JOIN [fp].[FactStatistics] cv 
			ON basis.EntityGroupConfigID = cv.EntityGroupConfigID
			AND basis.DepartmentID = cv.DepartmentID
			AND prim.DepartmentID = cv.DepartmentID
			AND prim.AccountID = cv.AccountID
			AND prim.IsRevenue = 1
	WHERE config.FlexMethodID IN (4, 3)
		AND cv.StatisticsID IS NULL
	
	
	UPDATE r 
	SET r.DepartmentName = dept.Name
	FROM #Results r
		INNER JOIN [fw].[DimDepartment] dept ON r.DepartmentID = dept.DepartmentID
	
	UPDATE r 
	SET r.AccountName = acc.Name
	FROM #Results r
		INNER JOIN [fw].[DimAccount] acc ON r.AccountID = acc.AccountID
		
	UPDATE #Results SET DepartmentName = '' WHERE DepartmentName IS NULL
	UPDATE #Results SET DepartmentID = -1 WHERE DepartmentID IS NULL
	UPDATE #Results SET AccountName = '' WHERE AccountName IS NULL
	UPDATE #Results SET AccountID = -1 WHERE AccountID IS NULL
	UPDATE #Results SET FlexingMethodID = -1 WHERE FlexingMethodID IS NULL
		
	SELECT * FROM #Results
 END
GO


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

-- fp.procGetGLVariableDataForServiceLineVolumeFlexing
CREATE   PROCEDURE [fp].[procGetGLVariableDataForServiceLineVolumeFlexing]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER, 
	@EntityGroupConfigID INT, 
	@FiscalYearID SMALLINT, 
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
	/*********************************************************************
	** Change History
	**********************************************************************
	** CID  Date        Author      WI				Description
	** 1    2021-09-10  NT          JAZZ-25494      Initial. This is a replacemnet for funcGetGLVariableDataForServiceLineVolumeFlexing that contained the dreaded "OR DepartmentID IS NULL" clause and unnecessary REPLACE
	** 2    2021-09-24  MD          JAZZ-25923      Update load to inner join on fp.FlexConfigMap
	** 3    2022-08-12  BW          JAZZ-40536      Update load to include projection
	** 4 	2023-08-14  BW			JAZZ-58199	    Data model restructure for GL
	** 5 	2023-08-14  MY			JAZZ-59598	    Update view to pull correct values
	*********************************************************************/
 	
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' 	
	EXEC [dbo].[procSysDropTempTable] '#FilteredData' 	
	EXEC [dbo].[procSysDropTempTable] '#glPivoted' 	
	EXEC [dbo].[procSysDropTempTable] '#GLData' 	
   
    DECLARE @IsProjectionFlexingEnabled bit
	SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) 
	FROM fp.SystemSetting
	WHERE Name = 'Is Baseline And Projection PAF Enabled' 

	CREATE TABLE #GLData (
		BasisID INT,
		BudgetPhaseID TINYINT,
		TimeClassID TINYINT,
		DepartmentID INT,
		AccountID INT,
		FiscalYearID SMALLINT,
		FiscalMonthID TINYINT,
		OriginalValue DECIMAL(19,8),
		PercentAdjustmentFactor DECIMAL(19,8)
	)

    CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	CREATE TABLE #FilteredData (GeneralLedgerID INT PRIMARY KEY CLUSTERED)
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN

		INSERT INTO #FilteredData
		SELECT fg.GeneralLedgerID
		FROM [fp].[GeneralLedger] fg
			INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fg.DepartmentID
		WHERE fg.EntityGroupConfigID = @EntityGroupConfigID
			AND fg.VariabilityID = 2 --Variable

	END ELSE BEGIN

		INSERT INTO #FilteredData
		SELECT fg.GeneralLedgerID
		FROM [fp].[GeneralLedger] fg
		WHERE fg.EntityGroupConfigID = @EntityGroupConfigID
			AND fg.VariabilityID = 2 --Variable

	END

	SELECT
		gl.GeneralLedgerID, 
		gl.BudgetConfigID, 
		gl.EntityGroupConfigID, 
		gl.EntityID, 
		gl.DepartmentID, 
		gl.AccountID, 
		gl.FinancialReportingID, 
		gl.APEModelSectionID, 
		gl.VariabilityID, 
		34 AS UnitTypeID,
		m.FiscalMonthID,
		TargetAdjusted,
		BudgetAdjusted,
		ProjectionAdjusted,
		TargetPercentAdjustmentFactor,
		BudgetPercentAdjustmentFactor, 
		ProjectionPercentAdjustmentFactor
	INTO #glPivoted
	FROM fp.GeneralLedger gl
	    INNER JOIN #FilteredData ft ON ft.GeneralLedgerID = gl.GeneralLedgerID
		INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON gl.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts
		INNER JOIN [fp].[FlexConfigMapping] map
	             ON gl.DepartmentID = map.DepartmentID
	            AND gl.AccountID = map.GLAccountID
	            AND gl.EntityGroupConfigID = map.EntityGroupConfigID
	            AND map.FlexingTypeID = 7
		CROSS APPLY (
			VALUES
				(01, TargetAdjusted01, BudgetAdjusted01, ProjectionAdjusted01, TargetPercentAdjustmentFactor01, BudgetPercentAdjustmentFactor01, ProjectionPercentAdjustmentFactor01),
				(02, TargetAdjusted02, BudgetAdjusted02, ProjectionAdjusted02, TargetPercentAdjustmentFactor02, BudgetPercentAdjustmentFactor02, ProjectionPercentAdjustmentFactor02),
				(03, TargetAdjusted03, BudgetAdjusted03, ProjectionAdjusted03, TargetPercentAdjustmentFactor03, BudgetPercentAdjustmentFactor03, ProjectionPercentAdjustmentFactor03),
				(04, TargetAdjusted04, BudgetAdjusted04, ProjectionAdjusted04, TargetPercentAdjustmentFactor04, BudgetPercentAdjustmentFactor04, ProjectionPercentAdjustmentFactor04),
				(05, TargetAdjusted05, BudgetAdjusted05, ProjectionAdjusted05, TargetPercentAdjustmentFactor05, BudgetPercentAdjustmentFactor05, ProjectionPercentAdjustmentFactor05),
				(06, TargetAdjusted06, BudgetAdjusted06, ProjectionAdjusted06, TargetPercentAdjustmentFactor06, BudgetPercentAdjustmentFactor06, ProjectionPercentAdjustmentFactor06),
				(07, TargetAdjusted07, BudgetAdjusted07, ProjectionAdjusted07, TargetPercentAdjustmentFactor07, BudgetPercentAdjustmentFactor07, ProjectionPercentAdjustmentFactor07),
				(08, TargetAdjusted08, BudgetAdjusted08, ProjectionAdjusted08, TargetPercentAdjustmentFactor08, BudgetPercentAdjustmentFactor08, ProjectionPercentAdjustmentFactor08),
				(09, TargetAdjusted09, BudgetAdjusted09, ProjectionAdjusted09, TargetPercentAdjustmentFactor09, BudgetPercentAdjustmentFactor09, ProjectionPercentAdjustmentFactor09),
				(10, TargetAdjusted10, BudgetAdjusted10, ProjectionAdjusted10, TargetPercentAdjustmentFactor10, BudgetPercentAdjustmentFactor10, ProjectionPercentAdjustmentFactor10),
				(11, TargetAdjusted11, BudgetAdjusted11, ProjectionAdjusted11, TargetPercentAdjustmentFactor11, BudgetPercentAdjustmentFactor11, ProjectionPercentAdjustmentFactor11),
				(12, TargetAdjusted12, BudgetAdjusted12, ProjectionAdjusted12, TargetPercentAdjustmentFactor12, BudgetPercentAdjustmentFactor12, ProjectionPercentAdjustmentFactor12)		
		) AS CrossApplied (MonthSortOrder, TargetAdjusted, BudgetAdjusted, ProjectionAdjusted, TargetPercentAdjustmentFactor, BudgetPercentAdjustmentFactor, ProjectionPercentAdjustmentFactor)
		LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	WHERE gl.EntityGroupConfigID = @EntityGroupConfigID

	INSERT INTO #GLData	(BasisID, BudgetPhaseID, TimeClassID, DepartmentID, AccountID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor)		
	SELECT
	       GeneralLedgerID AS BasisID,
	       CAST(2 AS TINYINT) AS BudgetPhaseID,
	       CAST(2 AS TINYINT) AS TimeClassID,
	       DepartmentID,
	       AccountID,
	       @FiscalYearID as FiscalYearID,
	       FiscalMonthID,
	       TargetAdjusted AS OriginalValue,
		   TargetPercentAdjustmentFactor AS PercentAdjustmentFactor
	FROM #glPivoted

	INSERT INTO #GLData	(BasisID, BudgetPhaseID, TimeClassID, DepartmentID, AccountID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor)		
	SELECT
	       GeneralLedgerID AS BasisID,
	       CAST(3 AS TINYINT) AS BudgetPhaseID,
	       CAST(2 AS TINYINT) AS TimeClassID,
	       DepartmentID,
	       AccountID,
	       @FiscalYearID as FiscalYearID,
	       FiscalMonthID,
	       BudgetAdjusted AS OriginalValue,
		   BudgetPercentAdjustmentFactor AS PercentAdjustmentFactor
	FROM #glPivoted

	IF(@IsProjectionFlexingEnabled = 1) -- JAZZ-40536
	BEGIN

		INSERT INTO #GLData	(BasisID, BudgetPhaseID, TimeClassID, DepartmentID, AccountID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor)	
		SELECT
			GeneralLedgerID AS BasisID,
			CAST(2 AS TINYINT) AS BudgetPhaseID,
			CAST(12 AS TINYINT) AS TimeClassID,
			DepartmentID,
			AccountID,
			@FiscalYearID as FiscalYearID, -- This is technically wrong, but leaving it for now as I don't know what this might impact.
			FiscalMonthID,
			ProjectionAdjusted AS OriginalValue,
			ProjectionPercentAdjustmentFactor AS PercentAdjustmentFactor
		FROM #glPivoted

	END

	-- Return final results
	SELECT * FROM #GLData

 END
GO


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

-- fp.procGetGLVariableDataForServiceLineVolumeFlexing_Initial
CREATE   PROCEDURE [fp].[procGetGLVariableDataForServiceLineVolumeFlexing_Initial]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER, 
	@EntityGroupConfigID INT, 
	@FiscalYearID SMALLINT, 
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
	/*********************************************************************
	** Change History
	**********************************************************************
	** CID  Date        Author      WI				Description
	** 1    2022-08-16  BW          JAZZ-40536     Initial
	** 2 	2023-08-09  BW			JAZZ-58199	   Data model restructure for GL
	*********************************************************************/
 	
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' 	
	EXEC [dbo].[procSysDropTempTable] '#FilteredData' 	
   
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	CREATE TABLE #FilteredData (GeneralLedgerID INT PRIMARY KEY CLUSTERED)
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT fg.GeneralLedgerID
		FROM [fp].[GeneralLedger] fg
		INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fg.DepartmentID
		WHERE fg.EntityGroupConfigID = @EntityGroupConfigID
		  AND fg.VariabilityID = 2 --Variable
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT fg.GeneralLedgerID
		FROM [fp].[GeneralLedger] fg
		WHERE fg.EntityGroupConfigID = @EntityGroupConfigID
		  AND fg.VariabilityID = 2 --Variable
	END
	 
	SELECT
	       GeneralLedgerID AS BasisID,
	       CAST(2 AS TINYINT) AS BudgetPhaseID,
	       CAST(2 AS TINYINT) AS TimeClassID,
	       DepartmentID,
	       AccountID,
	       @FiscalYearID as FiscalYearID,
	       FiscalMonthID,
	       OriginalValue
	FROM
	     (SELECT
	             fg.GeneralLedgerID,
	             fg.DepartmentID,
	             fg.AccountID,
	             fg.InitialBudget01 AS 'Month01',
	             fg.InitialBudget02 AS 'Month02',
	             fg.InitialBudget03 AS 'Month03',
	             fg.InitialBudget04 AS 'Month04',
	             fg.InitialBudget05 AS 'Month05',
	             fg.InitialBudget06 AS 'Month06',
	             fg.InitialBudget07 AS 'Month07',
	             fg.InitialBudget08 AS 'Month08',
	             fg.InitialBudget09 AS 'Month09',
	             fg.InitialBudget10 AS 'Month10',
	             fg.InitialBudget11 AS 'Month11',
	             fg.InitialBudget12 AS 'Month12'
	      FROM
	           [fp].[GeneralLedger] fg
	           INNER JOIN #FilteredData ft ON ft.GeneralLedgerID = fg.GeneralLedgerID
			   INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON fg.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts
	           INNER JOIN [fp].[FlexConfigMapping] map
	             ON fg.DepartmentID = map.DepartmentID
	            AND fg.AccountID = map.GLAccountID
	            AND fg.EntityGroupConfigID = map.EntityGroupConfigID
	      WHERE map.FlexingTypeID = 7) PIV
	         UNPIVOT(OriginalValue FOR FiscalMonth IN ([Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12])) AS f
	       LEFT JOIN fw.DImFiscalMonth m WITH (readuncommitted) ON m.MonthColumnName = f.FiscalMonth
	
 END
GO


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

-- fp.procGetNonStaffingFlexingExceptionItems
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2024-09-12  MZ/MY    JAZZ-75490		Created proc
** 2	2024-09-19  NH       JAZZ-77178		Updated message
** 3	2024-09-24  MY       JAZZ-76786		Pass in Budget Config for inactive configs
*************************************************************/
CREATE   PROCEDURE [fp].[procGetNonStaffingFlexingExceptionItems]
	@IsInitialPlansEnabled BIT = 0,
	@BudgetConfigID INT = 0,
	@IsDebug BIT = 0
AS
BEGIN
		
	EXEC [dbo].[procSysDropTempTable] '#accountsToValidate'
	EXEC [dbo].[procSysDropTempTable] '#missingPrimaryStats'
	EXEC [dbo].[procSysDropTempTable] '#finalValidatedTable'
	EXEC [dbo].[procSysDropTempTable] '#statisticsMapping'
	EXEC [dbo].[procSysDropTempTable] '#missingStatistics'
	EXEC [dbo].[procSysDropTempTable] '#statisticsWithZeroValues'
	EXEC [dbo].[procSysDropTempTable] '#noFlexConfigMapping'
	EXEC [dbo].[procSysDropTempTable] '#timeClassByEgc'
	EXEC [dbo].[procSysDropTempTable] '#statisticsHistoryMissing'
	EXEC [dbo].[procSysDropTempTable] '#revenueHistoryMissing'
	
	CREATE TABLE #finalValidatedTable (
		DepartmentID INT,
		AccountID INT,
		FlexMethodID INT,
		FlexMethod NVARCHAR(MAX),
		Detail NVARCHAR(MAX),
		EntityGroupConfigGUID UNIQUEIDENTIFIER,
		EntityGroupConfigName NVARCHAR(MAX),
		IsNew INT
	)
	
	SELECT EntityGroupConfigID, EntityGroupConfigGUID, AccountFiscalYearID, AccountTimeClassID
	INTO #timeClassByEgc
	FROM fp.EntityGroupConfig
	
	-- Populate NonStaffing records that we can check has Statistics or not. By default, 
	-- NonStaffing accounts are 100% Variable so we don't need to check if it's Variable or not.
	-- Populates: #accountsToValidate
	SELECT DISTINCT
	    dep.DepartmentID, 
	    acc.AccountID, 
	    flex.FlexMethodID, 
	    'Statistics Accounts' AS FlexMethod,
	    '' AS Detail, 
	    ec.EntityGroupConfigGUID,
	    ec.Name,
		gl.IsNew
	INTO #accountsToValidate
	FROM fp.GeneralLedger gl
	    INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID
	    INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID
	    INNER join fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID
	    INNER JOIN fp.EntityGroupConfig ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
	    INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID = gl.APEModelSectionID 
	    INNER JOIN fp.NonStaffingExpenseFlexingConfig flex ON flex.DepartmentID = gl.DepartmentID 
			AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
		INNER JOIN fp.NonStaffingVariabilityConfig nsvb ON ec.EntityGroupConfigGUID = nsvb.EntityGroupConfigGUID 
			AND gl.AccountID = nsvb.AccountID
		LEFT JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON ovr.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
			AND ovr.DepartmentID = gl.DepartmentID 
	        AND ovr.AccountID = gl.AccountID
	WHERE bc.BudgetConfigID = @BudgetConfigID  
	    AND map.APEModelSectionName = 'Non-Staffing' 
	    AND gl.VariabilityID = 2				-- Merely limiting the records as VariabilityID != Variability Percentage
	    AND flex.flexMethodID = 1				-- Statistic Accounts
	    AND dep.OBIsDefined = 1
		AND nsvb.Variability > 0				-- Only find accounts that are at least partial variabile
		AND (ovr.OverrideFlexConfigGUID IS NULL OR (ovr.FlexMethodID != 6 AND ovr.FlexMethodID != 2))	-- 6 = Fixed, 2 = Patient Activity
			
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#accountsToValidate' AS '#accountsToValidate', * FROM #accountsToValidate
	END
	
	-- Check to see if there are Primary Statistics configured or not
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.AccountID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name,
		atv.IsNew
	INTO #missingPrimaryStats
	FROM #accountsToValidate atv
		LEFT JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID
			AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID
			AND psc.IsNonStaffing = 1
		LEFT JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND ovr.DepartmentID = atv.DepartmentID
			AND ovr.AccountID = atv.AccountID
	WHERE psc.RowID IS NULL
		AND ovr.OverrideFlexConfigGUID IS NULL
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#missingPrimaryStats' AS '#missingPrimaryStats', * FROM #missingPrimaryStats
	END
	
	-- If there are any missing primary stats, add them to the final validation. Doing this first to weed out
	-- potential duplicates down the line
	IF EXISTS (SELECT 1 FROM #missingPrimaryStats)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
		SELECT
			DepartmentID, 
			AccountID, 
			FlexMethodID, 
			FlexMethod,
			'Department/Account is set up for flexing but has no primary statistics configured for non-staffing. To resolve, add primary statistics for this department.',
			EntityGroupConfigGUID,
			Name, 
			IsNew
		FROM #missingPrimaryStats
	
		DELETE atv 
		FROM #accountsToValidate atv
			INNER JOIN #missingPrimaryStats mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	END
	
	-- Build a mapping of Department/Account to Statististics Department/Account
	-- First build it without overrides
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.AccountID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name, 
		COALESCE(pscs.DepartmentID, psc.DepartmentID) AS StatisticsDepartmentID,
		psc.AccountID AS StatisticsAccountID, 
		atv.IsNew
	INTO #statisticsMapping
	FROM #accountsToValidate atv
		INNER JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID
			AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID
			AND psc.IsNonStaffing = 1
		INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID
		INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID 
	    LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscs ON psc.RowID = pscs.PrimaryStatisticsConfigID
		LEFT JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND ovr.DepartmentID = atv.DepartmentID
			AND ovr.AccountID = atv.AccountID
	WHERE ovr.OverrideFlexConfigGUID IS NULL
	
	-- Now build the overrides
	INSERT INTO #statisticsMapping (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, StatisticsDepartmentID, StatisticsAccountID, IsNew)
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.AccountID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name, 
	    ovr.DepartmentID AS StatisticsDepartmentID,
	    ass.AccountID AS StatisticsAccountID, 
		IsNew
	FROM #accountsToValidate atv
	    INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID
	    INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID 
		INNER JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND ovr.DepartmentID = atv.DepartmentID
			AND ovr.AccountID = atv.AccountID
		INNER JOIN fp.NSOverrideFlexConfigAssignment ass ON ovr.OverrideFlexConfigGUID = ass.OverrideFlexConfigGUID
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#statisticsMapping' AS '#statisticsMapping', * FROM #statisticsMapping
	END
	
	-- Next, we need to check to see if Primary Stats exist, but there are no Statistics for it
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name, 
		sm.IsNew
	INTO #missingStatistics
	FROM #statisticsMapping sm
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
		LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name, 
		sm.IsNew
	HAVING COUNT(fs.StatisticsID) = 0
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#missingStatistics' AS '#missingStatistics', * FROM #missingStatistics
	END
	
	IF EXISTS (SELECT 1 FROM #missingStatistics)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
		SELECT
			DepartmentID, 
			AccountID, 
			FlexMethodID, 
			FlexMethod,
			'Department/Account is set up for flexing but has no statistics data. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.',
			EntityGroupConfigGUID,
			Name, 
			IsNew
		FROM #missingStatistics
	
		DELETE atv 
		FROM #accountsToValidate atv
			INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
		DELETE atv 
		FROM #statisticsMapping atv
			INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	END
	
	-- Next, check for cases where we have statistics, but they are zero
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    12 AS TimeClassID, 
		sm.IsNew
	INTO #statisticsWithZeroValues
	FROM #statisticsMapping sm
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
		INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
		INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3
		INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name, 
		sm.IsNew
	HAVING (
		SUM(CASE WHEN bc.MonthsLoaded = 1  THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 2  THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 3  THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 4  THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 5  THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 6  THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 7  THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 8  THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 9  THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END
		) = 0							-- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    2 AS TimeClassID, 
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name, 
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    22 AS TimeClassID, 
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name, 
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#statisticsWithZeroValues' AS '#statisticsWithZeroValues', * FROM #statisticsWithZeroValues
	END
	
	IF EXISTS (SELECT 1 FROM #statisticsWithZeroValues)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Account is set up for flexing but the statistics are zero for projection. To resolve, add projection statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name, 
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 12
	
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Account is set up for flexing but the statistics are zero for budget. To resolve, add budget statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name, 
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 2
	
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Account is set up for flexing but the statistics are zero for target. To resolve, add target statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name, 
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 22
	
		DELETE atv 
		FROM #accountsToValidate atv
			INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
		DELETE atv 
		FROM #statisticsMapping atv
			INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND atv.AccountID = mps.AccountID
	END
	
	-- This only works for when Initial Plan is disabled
	IF (@IsInitialPlansEnabled = 0)
	BEGIN
	
		-- We need to check the historical data to ensure the rate is calculate correctly
		-- aka [fp].[procSampleGLDollarsPerUOS].
		SELECT DISTINCT
			sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name, 
			sm.IsNew
		INTO #statisticsHistoryMissing
		FROM #statisticsMapping sm
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
			INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
				AND sm.StatisticsDepartmentID = fs.DepartmentID 
				AND sm.StatisticsAccountID = fs.AccountID
			INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID
			INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID
		GROUP BY sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name, 
			sm.IsNew
		HAVING (
			SUM(CASE 
				WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 1 THEN hist.ActualYTDValueTotal
				WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.AccountTimeClassID = 1 THEN hist.PriorYearActualValueTotal
				WHEN tcegc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 2 THEN hist.CurrentYearBudgetTotal
				ELSE 0 END
			) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
		)
	
		SELECT DISTINCT
			sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name, 
			sm.IsNew
		INTO #revenueHistoryMissing
		FROM #statisticsMapping sm
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			INNER JOIN [fp].[GeneralLedger] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
				AND sm.DepartmentID = fs.DepartmentID 
				AND sm.AccountID = fs.AccountID
			INNER JOIN fp.GeneralLedgerHistory hist ON hist.GeneralLedgerID = fs.GeneralLedgerID
			INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID
		GROUP BY sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name, 
			sm.IsNew
		HAVING (
			SUM(CASE 
				WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 1 THEN hist.ActualYTDValueTotal
				WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.AccountTimeClassID = 1 THEN hist.PriorYearActualValueTotal
				WHEN tcegc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 2 THEN hist.CurrentYearBudgetTotal
				ELSE 0 END
			) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
		)
	
		IF (@IsDebug = 1)
		BEGIN
			SELECT '#statisticsHistoryMissing' AS '#statisticsHistoryMissing', * FROM #statisticsHistoryMissing
			SELECT '#revenueHistoryMissing' AS '#revenueHistoryMissing', * FROM #revenueHistoryMissing
		END
	
		IF EXISTS (SELECT 1 FROM #statisticsHistoryMissing) OR EXISTS(SELECT 1 FROM #revenueHistoryMissing)
		BEGIN
			INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
			SELECT
				DepartmentID, 
				AccountID, 
				FlexMethodID, 
				FlexMethod,
				-- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS]
				'Department/Account is missing historical statistics data, resulting in a calculated rate of zero.', 
				EntityGroupConfigGUID,
				Name, 
				IsNew
			FROM #statisticsHistoryMissing
	
			INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
			SELECT
				DepartmentID, 
				AccountID, 
				FlexMethodID, 
				FlexMethod,
				-- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS]
				'Department/Account is missing historical non-staffing data, resulting in a calculated rate of zero.', 
				EntityGroupConfigGUID,
				Name, 
				IsNew
			FROM #revenueHistoryMissing
	
			DELETE atv 
			FROM #accountsToValidate atv
				INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
			DELETE atv 
			FROM #statisticsMapping atv
				INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
			DELETE atv 
			FROM #accountsToValidate atv
				INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
			DELETE atv 
			FROM #statisticsMapping atv
				INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
		END
	
	END
	
	-- Lastly, we need our catch-all for other issues. This is going to be vague, but it's basically, hey we know this isn't flexing, but don't know why
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		IsNew
	INTO #noFlexConfigMapping
	FROM #statisticsMapping sm
		INNER JOIN fp.EntityGroupConfig egc ON sm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		LEFT JOIN fp.FlexConfigMapping fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID
			AND fcm.DepartmentID = sm.DepartmentID
			AND fcm.GLAccountID = sm.AccountID
			AND fcm.FlexingTypeID = 1
	WHERE fcm.StatAccountID IS NULL
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#noFlexConfigMapping' AS '#noFlexConfigMapping', * FROM #noFlexConfigMapping
	END
	
	IF EXISTS (SELECT 1 FROM #noFlexConfigMapping)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
		SELECT
			DepartmentID, 
			AccountID, 
			FlexMethodID, 
			FlexMethod,
			-- Aka, if it falls in here, we're missing something in this script.
			-- In this case, we need to debug [fp].[procNonStaffingByStatisticsFlexConfigPopulation]
			'An unknown error prevented the Department/Account from flexing. Contact support@stratadecision.com.', 
			EntityGroupConfigGUID,
			Name, 
			IsNew
		FROM #noFlexConfigMapping
	
		DELETE atv 
		FROM #accountsToValidate atv
			INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
		DELETE atv 
		FROM #statisticsMapping atv
			INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	END
	
	-- Return final results
	SELECT dep.DepartmentCode, dep.Description as DepartmentDescription, acc.AccountCode, acc.Description as AccountDescription, fv.*
	FROM #finalValidatedTable fv
		INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fv.DepartmentID
		INNER JOIN fw.DimAccount acc ON acc.AccountID = fv.AccountID
END
GO


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

-- fp.procGetOBNotificationsByEntityGroupConfiguration
CREATE   PROCEDURE fp.procGetOBNotificationsByEntityGroupConfiguration
	@EntityGroupConfigGUID UNIQUEIDENTIFIER
 AS
 BEGIN
	SET NOCOUNT ON

	SELECT dept.DepartmentID, wrole.RoleID, N'DEPT|' + CONVERT(NVARCHAR(10), DepartmentID) LootID
	INTO #TempDepartmentRole
	FROM fp.APEWorkflow wflw
	JOIN fp.EntityGroupConfig egc ON wflw.EntityGroupConfigID = egc.EntityGroupConfigID
	JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
	JOIN fp.APEWorkflowRole wrole ON wflw.WorkflowStepID = wrole.WorkflowStepID
	JOIN fp.APEDepartmentWorkflowStatus dept ON wflw.WorkflowStepID = dept.WorkflowStepID
	WHERE 
		bc.IsActive = 1
		AND wflw.IsNotificationEnabled = 1
		AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID

	SELECT up.UserGUID AS UserGuid, EmailAddress AS UserEmail, COUNT(tdr.DepartmentId) AS DepartmentsToReview
	FROM viewS3RoleAssignment ra
	JOIN UserProfile up ON up.UserGUID = ra.IdentityGUID
	JOIN #TempDepartmentRole tdr ON tdr.LootID = ra.LootGroupID AND tdr.RoleID = ra.RoleID
	WHERE 
		up.IsDisabled = 0 AND up.EmailAddress <> N'' AND up.EmailAddress IS NOT NULL
	GROUP BY up.UserGUID, EmailAddress

	DROP TABLE IF EXISTS #TempDepartmentRole;
 END
GO


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

-- fp.procGetOBNotificationsByUser
CREATE   PROCEDURE fp.procGetOBNotificationsByUser
	@UserGUID UNIQUEIDENTIFIER
 AS
 BEGIN
	SET NOCOUNT ON

	SELECT dept.DepartmentID, egc.EntityGroupConfigGUID, wrole.RoleID, N'DEPT|' + CONVERT(NVARCHAR(10), DepartmentID) LootID
	INTO #TempDepartmentRole
	FROM fp.APEWorkflow wflw
	JOIN fp.EntityGroupConfig egc ON wflw.EntityGroupConfigID = egc.EntityGroupConfigID
	JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
	JOIN fp.APEWorkflowRole wrole ON wflw.WorkflowStepID = wrole.WorkflowStepID
	JOIN fp.APEDepartmentWorkflowStatus dept ON wflw.WorkflowStepID = dept.WorkflowStepID
	WHERE 
		bc.IsActive = 1
		AND wflw.IsNotificationEnabled = 1

	SELECT EntityGroupConfigGUID AS EntityGroupConfigurationGuid, COUNT(tdr.DepartmentId) AS DepartmentsToReview
	FROM viewS3RoleAssignment ra
	JOIN UserProfile up ON up.UserGUID = ra.IdentityGUID
	JOIN #TempDepartmentRole tdr ON tdr.LootID = ra.LootGroupID AND tdr.RoleID = ra.RoleID
	WHERE 
		up.UserGUID = @UserGUID
	GROUP BY tdr.EntityGroupConfigGUID

	DROP TABLE IF EXISTS #TempDepartmentRole;
 END
GO


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

-- fp.procGetRevenueFlexingExceptionItems
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2024-09-12  MZ/MY    JAZZ-75490		Created proc
** 2	2024-09-19  NH       JAZZ-77178		Updated message
** 3	2024-09-24  MY       JAZZ-76786		Pass in Budget Config for inactive configs
*************************************************************/
CREATE   PROCEDURE [fp].[procGetRevenueFlexingExceptionItems]
	@IsInitialPlansEnabled BIT = 0,
	@BudgetConfigID INT = 0,
	@IsDebug BIT = 0
AS
BEGIN
	
	EXEC [dbo].[procSysDropTempTable] '#accountsToValidate'
	EXEC [dbo].[procSysDropTempTable] '#missingPrimaryStats'
	EXEC [dbo].[procSysDropTempTable] '#finalValidatedTable'
	EXEC [dbo].[procSysDropTempTable] '#statisticsMapping'
	EXEC [dbo].[procSysDropTempTable] '#missingStatistics'
	EXEC [dbo].[procSysDropTempTable] '#statisticsWithZeroValues'
	EXEC [dbo].[procSysDropTempTable] '#noFlexConfigMapping'
	EXEC [dbo].[procSysDropTempTable] '#timeClassByEgc'
	EXEC [dbo].[procSysDropTempTable] '#statisticsHistoryMissing'
	EXEC [dbo].[procSysDropTempTable] '#revenueHistoryMissing'
	
	
	CREATE TABLE #finalValidatedTable (
	    DepartmentID INT,
	    AccountID INT,
	    FlexMethodID INT,
	    FlexMethod NVARCHAR(MAX),
	    Detail NVARCHAR(MAX),
	    EntityGroupConfigGUID UNIQUEIDENTIFIER,
	    EntityGroupConfigName NVARCHAR(MAX),
		IsNew INT
	)
	
	SELECT EntityGroupConfigID, EntityGroupConfigGUID, RevenueAndDeductionsFiscalYearID, RevenueAndDeductionsTimeClassID
	INTO #timeClassByEgc
	FROM fp.EntityGroupConfig
	
	-- Populate Revenue records that we can check has Statistics or not. By default, 
	-- Revenue accounts are 100% Variable so we don't need to check if it's Variable or not.
	-- Populates: #accountsToValidate
	SELECT DISTINCT
	    dep.DepartmentID , 
	    acc.AccountID , 
	    COALESCE(ovr.FlexMethodID, flex.FlexMethodID) AS FlexMethodID , 
	    CASE WHEN COALESCE(ovr.FlexMethodID, flex.FlexMethodID) = 3 THEN 'Statistics Accounts By Patient Class' ELSE 'Total Statistics Accounts' END AS FlexMethod,
	    '' AS Detail, 
	    ec.EntityGroupConfigGUID,
	    ec.Name,
		gl.IsNew
	INTO #accountsToValidate
	FROM fp.GeneralLedger gl
	    INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID
	    INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID
	    INNER join fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID
	    INNER JOIN fp.EntityGroupConfig ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
	    INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID = gl.APEModelSectionID 
	    INNER JOIN fp.RevenueExpenseFlexingConfig flex ON flex.DepartmentID = gl.DepartmentID 
	        AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
		LEFT JOIN fp.RevenueFlexingOverrideConfig ovr ON ovr.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
			AND ovr.DepartmentID = gl.DepartmentID 
	        AND ovr.AccountID = gl.AccountID
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	    AND map.APEModelSectionName = 'Revenue' 
	    AND gl.VariabilityID = 2											-- Merely limiting the records as VariabilityID != Variability Percentage
	    AND flex.flexMethodID IN (3, 4)										-- Stats by patient Class (3), Total Statistics Accounts (4)
		AND (ovr.OverrideFlexConfigGUID IS NULL OR ovr.FlexMethodID != 6)	-- Override as "Fixed"
	    
	IF (@IsDebug = 1)
	BEGIN
	    SELECT '#accountsToValidate' AS '#accountsToValidate', * FROM #accountsToValidate
	END
	
	-- Check to see if there are Primary Statistics configured or not
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.AccountID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name,
		atv.IsNew
	INTO #missingPrimaryStats
	FROM #accountsToValidate atv
	    LEFT JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID
	        AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID
	        AND psc.IsRevenue = 1
		LEFT JOIN fp.RevenueFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND ovr.DepartmentID = atv.DepartmentID
			AND ovr.AccountID = atv.AccountID
	WHERE psc.RowID IS NULL
		AND ovr.OverrideFlexConfigGUID IS NULL
	
	IF (@IsDebug = 1)
	BEGIN
	    SELECT '#missingPrimaryStats' AS '#missingPrimaryStats', * FROM #missingPrimaryStats
	END
	
	-- If there are any missing primary stats, add them to the final validation. Doing this first to weed out
	-- potential duplicates down the line
	IF EXISTS (SELECT 1 FROM #missingPrimaryStats)
	BEGIN
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Account is set up for flexing but has no primary statistics configured for revenue. To resolve, add primary statistics for this department.',
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #missingPrimaryStats
	
	    DELETE atv 
	    FROM #accountsToValidate atv
	        INNER JOIN #missingPrimaryStats mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	END
	
	-- Build a mapping of Department/Account to Statististics Department/Account
	-- First build it without overrides
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.AccountID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name, 
	    COALESCE(pscs.DepartmentID, psc.DepartmentID) AS StatisticsDepartmentID,
	    psc.AccountID AS StatisticsAccountID,
		IsNew
	INTO #statisticsMapping
	FROM #accountsToValidate atv
	    INNER JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID
	        AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID
	        AND psc.IsRevenue = 1
	    INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID
	    INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID 
	    LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscs ON psc.RowID = pscs.PrimaryStatisticsConfigID
		LEFT JOIN fp.RevenueFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND ovr.DepartmentID = atv.DepartmentID
			AND ovr.AccountID = atv.AccountID
	WHERE ovr.OverrideFlexConfigGUID IS NULL
	
	-- Now build the overrides
	INSERT INTO #statisticsMapping (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, StatisticsDepartmentID, StatisticsAccountID, IsNew)
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.AccountID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name, 
	    ovr.DepartmentID AS StatisticsDepartmentID,
	    ass.AccountID AS StatisticsAccountID,
		IsNew
	FROM #accountsToValidate atv
	    INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID
	    INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID 
		INNER JOIN fp.RevenueFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND ovr.DepartmentID = atv.DepartmentID
			AND ovr.AccountID = atv.AccountID
		INNER JOIN fp.RevenueFlexingOverrideConfigAssignment ass ON ovr.OverrideFlexConfigGUID = ass.OverrideFlexConfigGUID
	
	IF (@IsDebug = 1)
	BEGIN
	    SELECT '#statisticsMapping' AS '#statisticsMapping', * FROM #statisticsMapping
	END
	
	-- Next, we need to check to see if Primary Stats exist, but there are no Statistics for it
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	INTO #missingStatistics
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID
	WHERE sm.FlexMethodID = 4
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING COUNT(fs.StatisticsID) = 0
	
	INSERT INTO #missingStatistics (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID
	WHERE sm.FlexMethodID = 3
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING COUNT(fs.StatisticsID) = 0
	
	IF (@IsDebug = 1)
	BEGIN
	    SELECT '#missingStatistics' AS '#missingStatistics', * FROM #missingStatistics
	END
	
	IF EXISTS (SELECT 1 FROM #missingStatistics)
	BEGIN
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        CASE WHEN FlexMethodID = 3 THEN 'Department/Account is set up for flexing but has no statistics data for statistics accounts by patient class. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.'
	        ELSE 'Department/Account is set up for flexing but has no statistics data. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.' END,
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #missingStatistics
	
	    DELETE atv 
	    FROM #accountsToValidate atv
	        INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
	    DELETE atv 
	    FROM #statisticsMapping atv
	        INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	END
	
	-- Next, check for cases where we have statistics, but they are zero
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    12 AS TimeClassID,
		sm.IsNew
	INTO #statisticsWithZeroValues
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID
	    INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3
	WHERE sm.FlexMethodID = 4
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(CASE WHEN bc.MonthsLoaded = 1  THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 2  THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 3  THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 4  THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 5  THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 6  THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 7  THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 8  THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 9  THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END
	    ) = 0                           -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    12 AS TimeClassID, 
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID
	    INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3
	WHERE sm.FlexMethodID = 3
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(CASE WHEN bc.MonthsLoaded = 1  THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 2  THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 3  THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 4  THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 5  THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 6  THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 7  THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 8  THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 9  THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12
	             WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END
	    ) = 0                           -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    2 AS TimeClassID,
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3
	WHERE sm.FlexMethodID = 4
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    2 AS TimeClassID,
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3
	WHERE sm.FlexMethodID = 3
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    22 AS TimeClassID,
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2
	WHERE sm.FlexMethodID = 4
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    22 AS TimeClassID,
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
	    INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
	    INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
	        AND sm.StatisticsDepartmentID = fs.DepartmentID 
	        AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2
	WHERE sm.FlexMethodID = 3
	GROUP BY sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	IF (@IsDebug = 1)
	BEGIN
	    SELECT '#statisticsWithZeroValues' AS '#statisticsWithZeroValues', * FROM #statisticsWithZeroValues
	END
	
	IF EXISTS (SELECT 1 FROM #statisticsWithZeroValues)
	BEGIN
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Account is set up for flexing but the statistics are zero for projection. To resolve, add projection statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 12
	
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Account is set up for flexing but the statistics are zero for budget. To resolve, add budget statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 2
	
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Account is set up for flexing but the statistics are zero for target. To resolve, add target statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 22
	
	    DELETE atv 
	    FROM #accountsToValidate atv
	        INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
	    DELETE atv 
	    FROM #statisticsMapping atv
	        INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND atv.AccountID = mps.AccountID
	END
	
	-- This only works for when Initial Plan is disabled
	IF (@IsInitialPlansEnabled = 0)
	BEGIN
	
		-- We need to check the historical data to ensure the rate is calculate correctly
		-- aka [fp].[procSampleGLDollarsPerUOS].
		SELECT DISTINCT
			sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		INTO #statisticsHistoryMissing
		FROM #statisticsMapping sm
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
			INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
				AND sm.StatisticsDepartmentID = fs.DepartmentID 
				AND sm.FlexMethodID = 4 AND sm.StatisticsAccountID = fs.AccountID
			INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID
			INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID
		WHERE sm.FlexMethodID = 4
		GROUP BY sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		HAVING (
			SUM(CASE 
				WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.ActualYTDValueTotal
				WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.PriorYearActualValueTotal
				WHEN tcegc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 2 THEN hist.CurrentYearBudgetTotal
				ELSE 0 END
			) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
		)
	
		INSERT INTO #statisticsHistoryMissing (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, IsNew)
		SELECT DISTINCT
			sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		FROM #statisticsMapping sm
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID
			INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
				AND sm.StatisticsDepartmentID = fs.DepartmentID 
				AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID
			INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID
			INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID
		WHERE sm.FlexMethodID = 3
		GROUP BY sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		HAVING (
			SUM(CASE 
				WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.ActualYTDValueTotal
				WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.PriorYearActualValueTotal
				WHEN tcegc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 2 THEN hist.CurrentYearBudgetTotal
				ELSE 0 END
			) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
		)
	
		SELECT DISTINCT
			sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		INTO #revenueHistoryMissing
		FROM #statisticsMapping sm
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			INNER JOIN [fp].[GeneralLedger] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
				AND sm.DepartmentID = fs.DepartmentID 
				AND sm.AccountID = fs.AccountID
			INNER JOIN fp.GeneralLedgerHistory hist ON hist.GeneralLedgerID = fs.GeneralLedgerID
			INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID
		GROUP BY sm.DepartmentID, 
			sm.AccountID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		HAVING (
			SUM(CASE 
				WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.ActualYTDValueTotal
				WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.PriorYearActualValueTotal
				WHEN tcegc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 2 THEN hist.CurrentYearBudgetTotal
				ELSE 0 END
			) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
		)
	
		IF (@IsDebug = 1)
		BEGIN
			SELECT '#statisticsHistoryMissing' AS '#statisticsHistoryMissing', * FROM #statisticsHistoryMissing
			SELECT '#revenueHistoryMissing' AS '#revenueHistoryMissing', * FROM #revenueHistoryMissing
		END
	
		IF EXISTS (SELECT 1 FROM #statisticsHistoryMissing) OR EXISTS(SELECT 1 FROM #revenueHistoryMissing)
		BEGIN
			INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
			SELECT
				DepartmentID, 
				AccountID, 
				FlexMethodID, 
				FlexMethod,
				-- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS]
				'Department/Account is missing historical statistics data, resulting in a calculated rate of zero.', 
				EntityGroupConfigGUID,
				Name,
				IsNew
			FROM #statisticsHistoryMissing
	
			INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
			SELECT
				DepartmentID, 
				AccountID, 
				FlexMethodID, 
				FlexMethod,
				-- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS]
				'Department/Account is missing historical revenue data, resulting in a calculated rate of zero.', 
				EntityGroupConfigGUID,
				Name,
				IsNew
			FROM #revenueHistoryMissing
	
			DELETE atv 
			FROM #accountsToValidate atv
				INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
			DELETE atv 
			FROM #statisticsMapping atv
				INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
			DELETE atv 
			FROM #accountsToValidate atv
				INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
			DELETE atv 
			FROM #statisticsMapping atv
				INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
		END
	
	END
	
	-- Lastly, we need our catch-all for other issues. This is going to be vague, but it's basically, hey we know this isn't flexing, but don't know why
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.AccountID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	INTO #noFlexConfigMapping
	FROM #statisticsMapping sm
	    INNER JOIN fp.EntityGroupConfig egc ON sm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
	    LEFT JOIN fp.FlexConfigMapping fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID
	        AND fcm.DepartmentID = sm.DepartmentID
	        AND fcm.GLAccountID = sm.AccountID
	        AND fcm.FlexingTypeID = 2
	WHERE fcm.StatAccountID IS NULL
	
	IF (@IsDebug = 1)
	BEGIN
	    SELECT '#noFlexConfigMapping' AS '#noFlexConfigMapping', * FROM #noFlexConfigMapping
	END
	
	IF EXISTS (SELECT 1 FROM #noFlexConfigMapping)
	BEGIN
	    INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        AccountID, 
	        FlexMethodID, 
	        FlexMethod,
	        -- Aka, if it falls in here, we're missing something in this script.
	        -- In this case, we need to debug [fp].[procRevenueByStatisticsFlexConfigPopulation]
	        'An unknown error prevented the Department/Account from flexing. Contact support@stratadecision.com.', 
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #noFlexConfigMapping
	
	    DELETE atv 
	    FROM #accountsToValidate atv
	        INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	
	    DELETE atv 
	    FROM #statisticsMapping atv
	        INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID
	END
	
	-- Return final results
	SELECT dep.DepartmentCode, dep.Description as DepartmentDescription, acc.AccountCode, acc.Description as AccountDescription, fv.*
	FROM #finalValidatedTable fv
		INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fv.DepartmentID
		INNER JOIN fw.DimAccount acc ON acc.AccountID = fv.AccountID
END
GO


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

-- fp.procGetStaffingFlexingExceptionItems
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2024-09-12  MZ/MY    JAZZ-75490		Created proc
** 2	2024-09-19  NH       JAZZ-77178		Updated message
** 3	2024-09-24  MY       JAZZ-76786		Pass in Budget Config for inactive configs
*************************************************************/
CREATE   PROCEDURE [fp].[procGetStaffingFlexingExceptionItems]
	@IsInitialPlansEnabled BIT = 0,
	@BudgetConfigID INT = 0,
	@IsDebug BIT = 0
AS
BEGIN

	EXEC [dbo].[procSysDropTempTable] '#departmentsToValidate'
	EXEC [dbo].[procSysDropTempTable] '#missingPrimaryStats'
	EXEC [dbo].[procSysDropTempTable] '#finalValidatedTable'
	EXEC [dbo].[procSysDropTempTable] '#statisticsMapping'
	EXEC [dbo].[procSysDropTempTable] '#missingStatistics'
	EXEC [dbo].[procSysDropTempTable] '#statisticsWithZeroValues'
	EXEC [dbo].[procSysDropTempTable] '#noFlexConfigMapping'
	EXEC [dbo].[procSysDropTempTable] '#timeClassByEgc'
	EXEC [dbo].[procSysDropTempTable] '#statisticsHistoryMissing'
	EXEC [dbo].[procSysDropTempTable] '#payrollHistoryMissing'
	
	CREATE TABLE #finalValidatedTable (
		DepartmentID INT,
		JobCodeID INT,
		FlexMethodID INT,
		FlexMethod NVARCHAR(MAX),
		Detail NVARCHAR(MAX),
		EntityGroupConfigGUID UNIQUEIDENTIFIER,
		EntityGroupConfigName NVARCHAR(MAX),
		IsNew INT
	)
	
	SELECT EntityGroupConfigID, EntityGroupConfigGUID, PayrollFiscalYearID, PayrollTimeClassID
	INTO #timeClassByEgc
	FROM fp.EntityGroupConfig
	
	-- Populate NonStaffing records that we can check has Statistics or not. By default, 
	-- NonStaffing accounts are 100% Variable so we don't need to check if it's Variable or not.
	-- Populates: #departmentsToValidate
	SELECT DISTINCT
	    dep.DepartmentID, 
	    st.JobCodeID, 
	    flex.FlexMethodID, 
	    'Statistics Accounts' AS FlexMethod,
	    '' AS Detail, 
	    ec.EntityGroupConfigGUID,
	    ec.Name,
		MIN(CAST(IsNew AS INT)) AS IsNew
	INTO #departmentsToValidate
	FROM fp.Staffing st
	    INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = st.DepartmentID
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = st.BudgetConfigID
	    INNER JOIN fp.EntityGroupConfig ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
	    INNER JOIN fp.StaffingExpenseFlexingConfig flex ON flex.DepartmentID = st.DepartmentID 
			AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
		INNER JOIN fp.PayrollVariabilityConfig nsvb ON ec.EntityGroupConfigGUID = nsvb.EntityGroupConfigGUID 
			AND st.JobCodeID = nsvb.JobCodeID
		LEFT JOIN fp.StaffingVariabilityOverrideConfig svoc ON ec.EntityGroupConfigGUID = svoc.EntityGroupConfigGUID
			AND st.DepartmentID = svoc.DepartmentID
			AND st.JobCodeID = svoc.JobCodeID
		LEFT JOIN fp.StaffingFlexingOverrideConfig ovr ON ec.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND st.DepartmentID = ovr.DepartmentID
			AND st.JobCodeID = ovr.JobCodeID
	WHERE bc.BudgetConfigID = @BudgetConfigID
	    AND st.VariabilityID = 2																		-- Merely limiting the records as VariabilityID != Variability Percentage
	    AND flex.flexMethodID = 1																		-- Statistic Accounts
	    AND dep.OBIsDefined = 1
		AND st.SubsectionID = 3																			-- Staffing Only, Exclude Provider for now
		AND COALESCE(svoc.Variability, nsvb.Variability) > 0											-- Only find job codes that are at least partial variable
		AND (ovr.OverrideFlexConfigGUID IS NULL OR (ovr.FlexMethodID != 6 AND ovr.FlexMethodID != 2))	-- 6 = Fixed, 2 = Patient Activity
	GROUP BY dep.DepartmentID, 
	    st.JobCodeID, 
	    flex.FlexMethodID,
	    ec.EntityGroupConfigGUID,
	    ec.Name
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#departmentsToValidate' AS '#departmentsToValidate', * FROM #departmentsToValidate
	END
	
	-- Check to see if there are Primary Statistics configured or not
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.JobCodeID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name,
		atv.IsNew
	INTO #missingPrimaryStats
	FROM #departmentsToValidate atv
		LEFT JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID
			AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID
			AND psc.IsStaffing = 1
		LEFT JOIN fp.StaffingFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND atv.DepartmentID = ovr.DepartmentID
			AND atv.JobCodeID = ovr.JobCodeID
	WHERE psc.RowID IS NULL
		AND ovr.OverrideFlexConfigGUID IS NULL
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#missingPrimaryStats' AS '#missingPrimaryStats', * FROM #missingPrimaryStats
	END
	
	-- If there are any missing primary stats, add them to the final validation. Doing this first to weed out
	-- potential duplicates down the line
	IF EXISTS (SELECT 1 FROM #missingPrimaryStats)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
		SELECT
			DepartmentID, 
			JobCodeID, 
			FlexMethodID, 
			FlexMethod,
			'Department/Job Code is set up for flexing but has no primary statistics configured for staffing. To resolve, add primary statistics for this department.',
			EntityGroupConfigGUID,
			Name,
			IsNew
		FROM #missingPrimaryStats
	
		DELETE atv 
		FROM #departmentsToValidate atv
			INNER JOIN #missingPrimaryStats mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	END
	
	-- Build a mapping of Department/Job Code to Statististics Department/Job Code
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.JobCodeID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name, 
		COALESCE(pscs.DepartmentID, psc.DepartmentID) AS StatisticsDepartmentID,
		psc.AccountID AS StatisticsAccountID,
		atv.IsNew
	INTO #statisticsMapping
	FROM #departmentsToValidate atv
		INNER JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID
			AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID
			AND psc.IsStaffing = 1
		INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID
		INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID 
	    LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscs ON psc.RowID = pscs.PrimaryStatisticsConfigID
		LEFT JOIN fp.StaffingFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND atv.DepartmentID = ovr.DepartmentID
			AND atv.JobCodeID = ovr.JobCodeID
	WHERE ovr.OverrideFlexConfigGUID IS NULL
	
	-- Now build the overrides
	INSERT INTO #statisticsMapping (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, StatisticsDepartmentID, StatisticsAccountID, IsNew)
	SELECT DISTINCT
	    atv.DepartmentID, 
	    atv.JobCodeID, 
	    atv.FlexMethodID, 
	    atv.FlexMethod,
	    atv.EntityGroupConfigGUID,
	    atv.Name, 
	    ovr.DepartmentID AS StatisticsDepartmentID,
	    ass.AccountID AS StatisticsAccountID, 
		IsNew
	FROM #departmentsToValidate atv
	    INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID
	    INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID 
		INNER JOIN fp.StaffingFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID
			AND atv.DepartmentID = ovr.DepartmentID
			AND atv.JobCodeID = ovr.JobCodeID
		INNER JOIN fp.StaffingFlexingOverrideConfigAssignment ass ON ovr.OverrideFlexConfigGUID = ass.OverrideFlexConfigGUID
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#statisticsMapping' AS '#statisticsMapping', * FROM #statisticsMapping
	END
	
	-- Next, we need to check to see if Primary Stats exist, but there are no Statistics for it
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	INTO #missingStatistics
	FROM #statisticsMapping sm
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
		LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
	GROUP BY sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING COUNT(fs.StatisticsID) = 0
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#missingStatistics' AS '#missingStatistics', * FROM #missingStatistics
	END
	
	IF EXISTS (SELECT 1 FROM #missingStatistics)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
		SELECT
			DepartmentID, 
			JobCodeID, 
			FlexMethodID, 
			FlexMethod,
			'Department/Job Code is set up for flexing but has no statistics data. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.',
			EntityGroupConfigGUID,
			Name,
			IsNew
		FROM #missingStatistics
	
		DELETE atv 
		FROM #departmentsToValidate atv
			INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	
		DELETE atv 
		FROM #statisticsMapping atv
			INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	END
	
	-- Next, check for cases where we have statistics, but they are zero
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    12 AS TimeClassID,
		sm.IsNew
	INTO #statisticsWithZeroValues
	FROM #statisticsMapping sm
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
		INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3
	GROUP BY sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
		SUM(CASE WHEN bc.MonthsLoaded = 1  THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 2  THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 3  THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 4  THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 5  THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 6  THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 7  THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 8  THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 9  THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12
				 WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END
		) = 0							-- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    2 AS TimeClassID,
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3
	GROUP BY sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	INSERT #statisticsWithZeroValues (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew)
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
	    22 AS TimeClassID,
		sm.IsNew
	FROM #statisticsMapping sm
	    INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
			AND sm.StatisticsDepartmentID = fs.DepartmentID 
			AND sm.StatisticsAccountID = fs.AccountID
	    INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2
	GROUP BY sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	HAVING (
	    SUM(fsb.AdjustedValueTotal) = 0
	)
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#statisticsWithZeroValues' AS '#statisticsWithZeroValues', * FROM #statisticsWithZeroValues
	END
	
	IF EXISTS (SELECT 1 FROM #statisticsWithZeroValues)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        JobCodeID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Job Code is set up for flexing but the statistics are zero for projection. To resolve, add projection statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 12
	
	    INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        JobCodeID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Job Code is set up for flexing but the statistics are zero for budget. To resolve, add budget statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 2
	
	    INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
	    SELECT
	        DepartmentID, 
	        JobCodeID, 
	        FlexMethodID, 
	        FlexMethod,
	        'Department/Job Code is set up for flexing but the statistics are zero for target. To resolve, add target statistic volumes in Plan Editor or change department flex method in entity group configuration.',
	        EntityGroupConfigGUID,
	        Name,
			IsNew
	    FROM #statisticsWithZeroValues 
	    WHERE TimeClassID = 22
	
		DELETE atv 
		FROM #departmentsToValidate atv
			INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	
		DELETE atv 
		FROM #statisticsMapping atv
			INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND atv.JobCodeID = mps.JobCodeID
	END
	
	-- This only works for when Initial Plan is disabled
	IF (@IsInitialPlansEnabled = 0)
	BEGIN
	
		-- We need to check the historical data to ensure the rate is calculate correctly
		-- aka [fp].[procSampleStaffingHoursPerUOS].
		SELECT DISTINCT
			sm.DepartmentID, 
			sm.JobCodeID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		INTO #statisticsHistoryMissing
		FROM #statisticsMapping sm
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID 
				AND sm.StatisticsDepartmentID = fs.DepartmentID 
				AND sm.StatisticsAccountID = fs.AccountID
			INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID
			INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID
		GROUP BY sm.DepartmentID, 
			sm.JobCodeID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		HAVING (
			SUM(CASE 
				WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 1 THEN hist.ActualYTDValueTotal
				WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.PayrollTimeClassID = 1 THEN hist.PriorYearActualValueTotal
				WHEN tcegc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 2 THEN hist.CurrentYearBudgetTotal
				ELSE 0 END
			) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider
		)
	
		SELECT DISTINCT
			sm.DepartmentID, 
			sm.JobCodeID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		INTO #payrollHistoryMissing
		FROM #statisticsMapping sm
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			INNER JOIN fp.Staffing fs ON bc.BudgetConfigID = fs.BudgetConfigID 
				AND sm.DepartmentID = fs.DepartmentID 
				AND sm.JobCodeID = fs.JobCodeID
			INNER JOIN fp.StaffingHistory hist ON hist.StaffingID = fs.StaffingID
			INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID
		GROUP BY sm.DepartmentID, 
			sm.JobCodeID, 
			sm.FlexMethodID, 
			sm.FlexMethod,
			sm.EntityGroupConfigGUID,
			sm.Name,
			sm.IsNew
		HAVING (
			SUM(CASE 
				WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 1 THEN hist.ActualYTDHoursTotal
				WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.PayrollTimeClassID = 1 THEN hist.PriorYearActualHoursTotal
				WHEN tcegc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 2 THEN hist.CurrentYearBudgetHoursTotal
				ELSE 0 END
			) = 0 -- Non Zero volume data for driver staffing - Projection, made it a sum to consider that there can be multiple records for provider
		)
	
		IF (@IsDebug = 1)
		BEGIN
			SELECT '#statisticsHistoryMissing' AS '#statisticsHistoryMissing', * FROM #statisticsHistoryMissing
			SELECT '#payrollHistoryMissing' AS '#payrollHistoryMissing', * FROM #payrollHistoryMissing
		END
	
		IF EXISTS (SELECT 1 FROM #statisticsHistoryMissing) OR EXISTS(SELECT 1 FROM #payrollHistoryMissing)
		BEGIN
			INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
			SELECT
				DepartmentID, 
				JobCodeID, 
				FlexMethodID, 
				FlexMethod,
				-- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS]
				'Department/Job Code is missing historical statistics data, resulting in a calculated rate of zero.', 
				EntityGroupConfigGUID,
				Name,
				IsNew
			FROM #statisticsHistoryMissing
	
			INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
			SELECT
				DepartmentID, 
				JobCodeID, 
				FlexMethodID, 
				FlexMethod,
				-- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS]
				'Department/Job Code is missing historical staffing data, resulting in a calculated rate of zero.', 
				EntityGroupConfigGUID,
				Name,
				IsNew
			FROM #payrollHistoryMissing
	
			DELETE atv 
			FROM #departmentsToValidate atv
				INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	
			DELETE atv 
			FROM #statisticsMapping atv
				INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	
			DELETE atv 
			FROM #departmentsToValidate atv
				INNER JOIN #payrollHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	
			DELETE atv 
			FROM #statisticsMapping atv
				INNER JOIN #payrollHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
		END
	
	END
	
	-- Lastly, we need our catch-all for other issues. This is going to be vague, but it's basically, hey we know this isn't flexing, but don't know why
	SELECT DISTINCT
	    sm.DepartmentID, 
	    sm.JobCodeID, 
	    sm.FlexMethodID, 
	    sm.FlexMethod,
	    sm.EntityGroupConfigGUID,
	    sm.Name,
		sm.IsNew
	INTO #noFlexConfigMapping
	FROM #statisticsMapping sm
		INNER JOIN fp.EntityGroupConfig egc ON sm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		LEFT JOIN fp.FlexConfigMapping fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID
			AND fcm.DepartmentID = sm.DepartmentID
			AND fcm.PRJobCodeID = sm.JobCodeID
			AND fcm.FlexingTypeID = 3 -- Staffing
	WHERE fcm.StatAccountID IS NULL
	
	IF (@IsDebug = 1)
	BEGIN
		SELECT '#noFlexConfigMapping' AS '#noFlexConfigMapping', * FROM #noFlexConfigMapping
	END
	
	IF EXISTS (SELECT 1 FROM #noFlexConfigMapping)
	BEGIN
		INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew)
		SELECT
			DepartmentID, 
			JobCodeID, 
			FlexMethodID, 
			FlexMethod,
			-- Aka, if it falls in here, we're missing something in this script.
			-- In this case, we need to debug [fp].[procNonStaffingByStatisticsFlexConfigPopulation]
			'An unknown error prevented the Department/Job Code from flexing. Contact support@stratadecision.com.', 
			EntityGroupConfigGUID,
			Name, 
			IsNew
		FROM #noFlexConfigMapping
	
		DELETE atv 
		FROM #departmentsToValidate atv
			INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	
		DELETE atv 
		FROM #statisticsMapping atv
			INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID
	END
	
	-- Return final results
	SELECT dep.DepartmentCode, dep.Description as DepartmentDescription, jc.JobCode, jc.Description as JobCodeDescription, fv.*
	FROM #finalValidatedTable fv
		INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fv.DepartmentID
		INNER JOIN fw.DimJobCode jc ON jc.JobCodeID = fv.JobCodeID
END
GO


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

-- fp.procGetStaffingVariableDataForServiceLineVolumeFlexing
CREATE    PROCEDURE [fp].[procGetStaffingVariableDataForServiceLineVolumeFlexing]  
	@EntityGroupConfigGUID UNIQUEIDENTIFIER, 
	@EntityGroupConfigID INT, 
	@FiscalYearID SMALLINT, 
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
 	/*********************************************************************
	** Change History
	**********************************************************************
	** CID  Date        Author      WI				Description
	** 1    2021-09-10  NT          JAZZ-25494      Initial. This is a replacemnet for funcGetStaffingVariableDataForServiceLineVolumeFlexing
															that contained the dreaded "OR DepartmentID IS NULL" clause and unnecessary REPLACE.
	** 2    2021-09-24  MD			JAZZ-25923		Update load to INNER JOIN on fp.FlexConfigMapping
	** 3    2022-07-21  MD			JAZZ-38981		Add projection data pull (behind flag)
	** 4	2023-10-31  MY			JAZZ-61705		Support PAF for the new data model - Staffing
	** 5	2024-06-14  SM      	JAZZ-71536  	   change JobCodeID from smallint to int
	** 6	2024-10-17   NT			JAZZ-78775      change to pull correct original values 
	*********************************************************************/
 
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' 	
	EXEC [dbo].[procSysDropTempTable] '#FilteredData' 
	EXEC [dbo].[procSysDropTempTable] '#staffingPivoted' 
	
	DECLARE @IsProjectionFlexingEnabled bit
	SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) 
	FROM fp.SystemSetting
	WHERE Name = 'Is Baseline And Projection PAF Enabled' 

	CREATE TABLE #StaffingData (
		RowID INT,
		BasisID INT,
		BudgetPhaseID TINYINT,
		TimeClassID TINYINT,
		DepartmentID INT,
		JobCodeID INT,
		PayCodeGroupID INT,
		FiscalYearID SMALLINT,
		FiscalMonthID TINYINT,
		OriginalValue DECIMAL(19,8),
		PercentAdjustmentFactor DECIMAL(19,8)
	)
   
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED)
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT fs.StaffingID
		FROM [fp].[Staffing] fs
		INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fs.DepartmentID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
		  AND fs.VariabilityID = 2 --Variable
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT fs.StaffingID
		FROM [fp].[Staffing] fs
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
		  AND fs.VariabilityID = 2 --Variable
	END
	
	SELECT
	  	fs.StaffingID,
		fs.DepartmentID,
		CAST(JobCodeID AS INT) AS JobCodeID,
		fs.PayCodeGroupID,
		fs.VariabilityID, 
		34 AS UnitTypeID,
		m.FiscalMonthID,
		TargetAdjusted,
		BudgetAdjusted,
		ProjectionAdjusted,
		TargetPercentAdjustmentFactor,
		BudgetPercentAdjustmentFactor, 
		ProjectionPercentAdjustmentFactor
	INTO #staffingPivoted
	FROM fp.Staffing fs
	INNER JOIN #FilteredData ft ON ft.StaffingID = fs.StaffingID
	INNER JOIN [fp].[FlexConfigMapping] map
	    ON fs.DepartmentID = map.DepartmentID
	AND fs.JobCodeID = map.PRJobCodeID
	AND fs.EntityGroupConfigID = map.EntityGroupConfigID
	AND map.FlexingTypeID = 7
	CROSS APPLY (
		VALUES
			(01, TargetAdjustedDollars01, BudgetAdjustedDollars01, ProjectionAdjustedDollars01, TargetDollarsPercentAdjustmentFactor01, BudgetDollarsPercentAdjustmentFactor01, ProjectionDollarsPercentAdjustmentFactor01),
			(02, TargetAdjustedDollars02, BudgetAdjustedDollars02, ProjectionAdjustedDollars02, TargetDollarsPercentAdjustmentFactor02, BudgetDollarsPercentAdjustmentFactor02, ProjectionDollarsPercentAdjustmentFactor02),
			(03, TargetAdjustedDollars03, BudgetAdjustedDollars03, ProjectionAdjustedDollars03, TargetDollarsPercentAdjustmentFactor03, BudgetDollarsPercentAdjustmentFactor03, ProjectionDollarsPercentAdjustmentFactor03),
			(04, TargetAdjustedDollars04, BudgetAdjustedDollars04, ProjectionAdjustedDollars04, TargetDollarsPercentAdjustmentFactor04, BudgetDollarsPercentAdjustmentFactor04, ProjectionDollarsPercentAdjustmentFactor04),
			(05, TargetAdjustedDollars05, BudgetAdjustedDollars05, ProjectionAdjustedDollars05, TargetDollarsPercentAdjustmentFactor05, BudgetDollarsPercentAdjustmentFactor05, ProjectionDollarsPercentAdjustmentFactor05),
			(06, TargetAdjustedDollars06, BudgetAdjustedDollars06, ProjectionAdjustedDollars06, TargetDollarsPercentAdjustmentFactor06, BudgetDollarsPercentAdjustmentFactor06, ProjectionDollarsPercentAdjustmentFactor06),
			(07, TargetAdjustedDollars07, BudgetAdjustedDollars07, ProjectionAdjustedDollars07, TargetDollarsPercentAdjustmentFactor07, BudgetDollarsPercentAdjustmentFactor07, ProjectionDollarsPercentAdjustmentFactor07),
			(08, TargetAdjustedDollars08, BudgetAdjustedDollars08, ProjectionAdjustedDollars08, TargetDollarsPercentAdjustmentFactor08, BudgetDollarsPercentAdjustmentFactor08, ProjectionDollarsPercentAdjustmentFactor08),
			(09, TargetAdjustedDollars09, BudgetAdjustedDollars09, ProjectionAdjustedDollars09, TargetDollarsPercentAdjustmentFactor09, BudgetDollarsPercentAdjustmentFactor09, ProjectionDollarsPercentAdjustmentFactor09),
			(10, TargetAdjustedDollars10, BudgetAdjustedDollars10, ProjectionAdjustedDollars10, TargetDollarsPercentAdjustmentFactor10, BudgetDollarsPercentAdjustmentFactor10, ProjectionDollarsPercentAdjustmentFactor10),
			(11, TargetAdjustedDollars11, BudgetAdjustedDollars11, ProjectionAdjustedDollars11, TargetDollarsPercentAdjustmentFactor11, BudgetDollarsPercentAdjustmentFactor11, ProjectionDollarsPercentAdjustmentFactor11),
			(12, TargetAdjustedDollars12, BudgetAdjustedDollars12, ProjectionAdjustedDollars12, TargetDollarsPercentAdjustmentFactor12, BudgetDollarsPercentAdjustmentFactor12, ProjectionDollarsPercentAdjustmentFactor12)		
	) AS CrossApplied (MonthSortOrder, TargetAdjusted, BudgetAdjusted, ProjectionAdjusted, TargetPercentAdjustmentFactor, BudgetPercentAdjustmentFactor, ProjectionPercentAdjustmentFactor)
	LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID

	INSERT INTO #StaffingData (RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor)		
	SELECT
		StaffingID AS RowID,
	    StaffingID AS BasisID,
	    CAST(2 AS TINYINT) AS BudgetPhaseID,
	    CAST(2 AS TINYINT) AS TimeClassID,
	    DepartmentID,
	    JobCodeID,
		PayCodeGroupID,
	    @FiscalYearID as FiscalYearID,
	    FiscalMonthID,
	    TargetAdjusted AS OriginalValue,
		TargetPercentAdjustmentFactor AS PercentAdjustmentFactor
	FROM #staffingPivoted

	INSERT INTO #StaffingData (RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor)		
	SELECT
		StaffingID AS RowID,
	    StaffingID AS BasisID,
	    CAST(3 AS TINYINT) AS BudgetPhaseID,
	    CAST(2 AS TINYINT) AS TimeClassID,
	    DepartmentID,
	    JobCodeID,
		PayCodeGroupID,
	    @FiscalYearID as FiscalYearID,
	    FiscalMonthID,
	    BudgetAdjusted AS OriginalValue,
		BudgetPercentAdjustmentFactor AS PercentAdjustmentFactor
	FROM #staffingPivoted

	IF(@IsProjectionFlexingEnabled = 1) -- JAZZ-40536
	BEGIN
		INSERT INTO #StaffingData (RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor)	
		SELECT
			StaffingID AS RowID,
			StaffingID AS BasisID,
			CAST(3 AS TINYINT) AS BudgetPhaseID,
			CAST(12 AS TINYINT) AS TimeClassID,
			DepartmentID,
			JobCodeID,
			PayCodeGroupID,
			@FiscalYearID as FiscalYearID, -- This is technically wrong, but leaving it for now as I don't know what this might impact.
			FiscalMonthID,
			ProjectionAdjusted AS OriginalValue,
			ProjectionPercentAdjustmentFactor AS PercentAdjustmentFactor
		FROM #staffingPivoted
	END

	-- Return final results	
	SELECT RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor
	FROM #StaffingData
	 
 END;
GO


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

-- fp.procGetStaffingVariableDataForServiceLineVolumeFlexing_Initials
CREATE   PROCEDURE [fp].[procGetStaffingVariableDataForServiceLineVolumeFlexing_Initials]  
	@EntityGroupConfigGUID UNIQUEIDENTIFIER, 
	@EntityGroupConfigID INT, 
	@FiscalYearID SMALLINT, 
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	/*********************************************************************
	** Change History
	**********************************************************************
	** CID  Date        Author      WI				Description
	** 1    2022-07-12  MD          JAZZ-38981      Initial
	** 2	2023-10-31  MY			JAZZ-61705		Support PAF for the new data model - Staffing
	** 3	2024-06-14  SM      	JAZZ-71536  	change JobCodeID from smallint to int
	*********************************************************************/
 
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' 	
	EXEC [dbo].[procSysDropTempTable] '#FilteredData' 	
   
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED)
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT fs.StaffingID
		FROM [fp].[Staffing] fs
			INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fs.DepartmentID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND fs.VariabilityID = 2 --Variable
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT fs.StaffingID
		FROM [fp].[Staffing] fs
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND fs.VariabilityID = 2 --Variable
	END
	
	SELECT
		StaffingID AS BasisID,
		TimeClassID,
		DepartmentID,
		CAST(JobCodeID AS INT) AS JobCodeID,
		PayCodeGroupID,
		@FiscalYearID,
		FiscalMonthID,
		OriginalValue
	FROM
		(
			SELECT
				fs.StaffingID,
				fs.DepartmentID,
				fs.JobCodeID,
				fs.PayCodeGroupID,
				CAST(2 AS TINYINT) AS TimeClassID,
				fs.InitialBudgetDollars01 AS 'Month01',
				fs.InitialBudgetDollars02 AS 'Month02',
				fs.InitialBudgetDollars03 AS 'Month03',
				fs.InitialBudgetDollars04 AS 'Month04',
				fs.InitialBudgetDollars05 AS 'Month05',
				fs.InitialBudgetDollars06 AS 'Month06',
				fs.InitialBudgetDollars07 AS 'Month07',
				fs.InitialBudgetDollars08 AS 'Month08',
				fs.InitialBudgetDollars09 AS 'Month09',
				fs.InitialBudgetDollars10 AS 'Month10',
				fs.InitialBudgetDollars11 AS 'Month11',
				fs.InitialBudgetDollars12 AS 'Month12'
			FROM [fp].[Staffing] fs
				INNER JOIN #FilteredData ft ON ft.StaffingID = fs.StaffingID
				INNER JOIN [fp].[FlexConfigMapping] map ON fs.DepartmentID = map.DepartmentID
					AND fs.JobCodeID = map.PRJobCodeID
					AND fs.EntityGroupConfigID = map.EntityGroupConfigID
			WHERE map.FlexingTypeID = 7		  
		) PIV
			UNPIVOT(OriginalValue FOR FiscalMonth IN ([Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12])) AS f
			LEFT JOIN fw.DimFiscalMonth m WITH (readuncommitted) ON m.MonthColumnName = f.FiscalMonth
	 
 END;
GO


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

-- fp.procGetWritableDepartmentsByEntityGroupConfigIDRoleID
CREATE PROCEDURE fp.procGetWritableDepartmentsByEntityGroupConfigIDRoleID(
	 @EntityGroupConfigID AS INT,
	 @RoleID AS INT
 )
 AS

BEGIN

	-- Disallow NULL
	IF (@EntityGroupConfigID IS NULL)
		RAISERROR('The value for @EntityGroupConfigID should not be null', 16, 1, @EntityGroupConfigID)
	IF (@RoleID IS NULL)
		RAISERROR('The value for @RoleID should not be null', 16, 1, @RoleID) 

	IF OBJECT_ID('tempdb..#dept_LootID') IS NOT NULL DROP TABLE #dept_LootID


	CREATE TABLE #dept_LootID (	
		[value] [nvarchar](128) NOT NULL PRIMARY KEY CLUSTERED  ([value] ASC) WITH (IGNORE_DUP_KEY = OFF),
		[DepartmentID] INT NOT NULL
	)

	INSERT INTO #dept_LootID
	SELECT CONCAT('Dept|', d.DepartmentID), d.DepartmentID
	FROM fp.EntityGroupConfig egc
	INNER JOIN fp.EntityGroupConfigMapping egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
	INNER JOIN fw.viewDimDepartment_Real d ON egcm.EntityID = d.EntityID
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID

	SELECT
		UserGUID, acl.RoleID, LootID, dept.DepartmentID
	FROM
		[dbo].[viewS3ACLDetail] acl
		INNER JOIN #dept_LootID dept ON dept.value = acl.LootID
	WHERE acl.RoleID = @RoleID
	AND acl.WriteAllowpts > acl.WriteDenypts  -- IsWritable
	
 END
GO


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

-- fp.procImportRosterAdjustment
/*************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		Author	WI			Description
** 1		11/13/17	MY		B-17923		Creates a Dummy Proc for Roster Changes
*************************************************************************************************************************/
CREATE PROCEDURE fp.procImportRosterAdjustment
	
AS
BEGIN
	-- Enter Any Logic that is needed for after saving a Roster Adjustment
	PRINT ''
END
GO


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

-- fp.procLockBenefitsByConfiguration
CREATE   procedure [fp].[procLockBenefitsByConfiguration]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@EntityGroupConfigID INT = null,
	@AccountID VARCHAR(MAX) = null,
	@FinancialReportingID INT = null
AS
BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1    2018-09-25  GF      E-02313		Simplify source dimensionality to only department
	** 2	2019-01-08	MY		B-20548		Lock Variable Dollar Records
	** 3	2019-02-12	IP		B-22020		Added targeted refresh by adding parameters (added to subqueries). Manager staffing adjustment performance improvements
	** 4	2019-02-14	IP		B-22020		Added AccountID as CSV
	** 5	2019-06-03	MY		TK-74658		Made some Performance Ehancements to the existing Benefits Lock proc
	** 6	2021-02-16  NN  	Jazz-466	Remove null joins on dept
	** 7	2022-07-07  MD  	JAZZ-39280	Replace dbo.ConvertCSValuesToTable with STRING_SPLIT
	*************************************************************/
 
 	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] WITH (READUNCOMMITTED)
		WHERE BudgetConfigID = @BudgetConfigID	
	END
 
 	CREATE TABLE #AccountIDs (AccountID int)
	INSERT INTO #AccountIDs (AccountID)
	SELECT DISTINCT value as AccountID FROM STRING_SPLIT(@AccountID, ',')
 
	CREATE TABLE #tmpBenefits (BenefitsID INT, UnitTypeID INT, FlexMethodID INT);
 
	INSERT INTO #tmpBenefits (BenefitsID, UnitTypeID, FlexMethodID)
		SELECT BenefitsID, basis.UnitTypeID, FlexMethodID	
		FROM [fp].[FactBenefits] basis
		INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
		WHERE BudgetConfigID = @BudgetConfigID
			  AND (basis.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null)
			  and (basis.AccountID IN ((SELECT AccountID FROM #AccountIDs)) or @AccountID is null)
			  and (basis.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null)
	
	DECLARE @PercentOfSalaries INT = 170,
			@DollarsPerFTE INT = 171,
			@Dollars INT = 34;
			
	DECLARE @Fixed INT = 0,
			@FlexAccountByFTEs INT = 1,
			@FlexAccountBySalaries INT = 2
			
	-- Lock $/FTE columns for % of salary or fixed flex methods
	UPDATE budg
	SET budg.LockFlag = 1,
		budg.LockType = 5
	FROM [fp].[FactBenefitsBudget] (READUNCOMMITTED) budg
		INNER JOIN #tmpBenefits ben ON budg.BenefitsID = ben.BenefitsID
	WHERE ben.FlexMethodID IN (@Fixed, @FlexAccountBySalaries)
		AND ben.UnitTypeID = @DollarsPerFTE
		AND budg.LockFlag = 0
 
	-- Lock % of salary columns for $/FTE or fixed flex methods
	UPDATE budg
	SET budg.LockFlag = 1,
		budg.LockType = 5
	FROM [fp].[FactBenefitsBudget](READUNCOMMITTED) budg
		INNER JOIN #tmpBenefits ben ON budg.BenefitsID = ben.BenefitsID
	WHERE ben.FlexMethodID IN (@Fixed , @FlexAccountByFTEs)
		AND ben.UnitTypeID = @PercentOfSalaries
		AND budg.LockFlag = 0
		
	-- Lock $/FTE columns for % of salary or fixed flex methods
	UPDATE proj
	SET proj.LockFlag = 1,
		proj.LockType = 5
	FROM [fp].[FactBenefitsProjection](READUNCOMMITTED) proj
		INNER JOIN #tmpBenefits ben ON proj.BenefitsID = ben.BenefitsID
	WHERE ben.FlexMethodID IN (@Fixed, @FlexAccountBySalaries)
		AND ben.UnitTypeID = @DollarsPerFTE
		AND proj.LockFlag = 0
 
	-- Lock % of salary columns for $/FTE or fixed flex methods
	UPDATE proj
	SET proj.LockFlag = 1,
		proj.LockType = 5
	FROM [fp].[FactBenefitsProjection](READUNCOMMITTED) proj
		INNER JOIN #tmpBenefits ben ON proj.BenefitsID = ben.BenefitsID
	WHERE ben.FlexMethodID IN (@Fixed , @FlexAccountByFTEs)
		AND ben.UnitTypeID = @PercentOfSalaries
		AND proj.LockFlag = 0
		
	-- Lock dollar columns for $/FTE or % of Salary flex methods
	UPDATE budg
	SET budg.LockFlag = 1,
		budg.LockType = 5
	FROM [fp].[FactBenefitsBudget](READUNCOMMITTED) budg
		INNER JOIN #tmpBenefits ben ON budg.BenefitsID = ben.BenefitsID
	WHERE ben.FlexMethodID IN (@FlexAccountBySalaries , @FlexAccountByFTEs)
		AND ben.UnitTypeID = @Dollars
		AND budg.LockFlag = 0
		
	-- Lock dollar columns for $/FTE or % of Salary flex methods
	UPDATE proj
	SET proj.LockFlag = 1,
		proj.LockType = 5
	FROM [fp].[FactBenefitsProjection](READUNCOMMITTED) proj
		INNER JOIN #tmpBenefits ben ON proj.BenefitsID = ben.BenefitsID
	WHERE ben.FlexMethodID IN (@FlexAccountBySalaries , @FlexAccountByFTEs)
		AND ben.UnitTypeID = @Dollars
		AND proj.LockFlag = 0
	
END
GO


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

-- fp.procLockStaffingByConfiguration
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2019-02-06  BK      B-21763		Lock FTE Records That Belong To Specified Productive Classes
** 2	2020-09-16	NN		JAZZ-4909	Lock Hours & Wage Rate for Dollars-only Productive Class; Remove Null check
** 3	2023-10-10  MY      JAZZ-61397	Update Staffing/Provider Comp adjustments to support data model changes
*************************************************************/
CREATE   PROCEDURE [fp].[procLockStaffingByConfiguration]
   @EntityGroupConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	CREATE TABLE #SourceDimensionality (DepartmentID INT);
	INSERT INTO #SourceDimensionality (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	--If #SourceDimensionality is empty pass in all DepartmentIds
	IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality where DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing]
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
 
	CREATE TABLE #tmpStaffing (StaffingID INT);
	
	-- Lock FTEs for PCG/PC that do not use FTEs
	UPDATE basis
	SET
		basis.TargetFTEsLockFlag = 1,
		basis.TargetFTEsLockType = 5,
		basis.BudgetFTEsLockFlag = 1,
		basis.BudgetFTEsLockType = 5,
		basis.ProjectionFTEsLockFlag = 1,
		basis.ProjectionFTEsLockType = 5
	FROM [fp].[Staffing] basis
		INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID
		INNER JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on basis.PayCodeGroupID = exc.PayCodeGroupID
	WHERE EntityGroupConfigID = @EntityGroupConfigID
		AND (
			TargetFTEsLockFlag = 0 OR
			BudgetFTEsLockFlag = 0 OR
			ProjectionFTEsLockFlag = 0
		)
	
	-- Lock hours for dollars only records
	UPDATE basis
	SET
		basis.TargetHoursLockFlag = 1,
		basis.TargetHoursLockType = 5,
		basis.BudgetHoursLockFlag = 1,
		basis.BudgetHoursLockType = 5,
		basis.ProjectionHoursLockFlag = 1,
		basis.ProjectionHoursLockType = 5
	FROM [fp].[Staffing] basis
		INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID
	WHERE EntityGroupConfigID = @EntityGroupConfigID 
		AND ProductiveClassID = 4
		AND (
			TargetHoursLockFlag = 0 OR
			BudgetHoursLockFlag = 0 OR
			ProjectionHoursLockFlag = 0
		)

	-- Lock wage rate for dollars only records
	UPDATE swr
	SET
		swr.TargetWageRateLockFlag = 1,
		swr.TargetWageRateLockType = 5,
		swr.BudgetWageRateLockFlag = 1,
		swr.BudgetWageRateLockType = 5,
		swr.ProjectionWageRateLockFlag = 1,
		swr.ProjectionWageRateLockType = 5
	FROM [fp].[StaffingWageRate] swr
		INNER JOIN [fp].[Staffing] basis ON basis.StaffingWageRateID = swr.StaffingWageRateID
		INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID
	WHERE EntityGroupConfigID = @EntityGroupConfigID 
		AND ProductiveClassID = 4
		AND basis.VariabilityID = 1	
		AND (
			TargetWageRateLockFlag = 0 OR
			BudgetWageRateLockFlag = 0 OR
			ProjectionWageRateLockFlag = 0
		)

END
GO


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

-- fp.procMRProviderBudgetStampOff
CREATE     PROCEDURE [fp].[procMRProviderBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	05-08-2023  BW      JAZZ-51541		Initial Creation
	** 2	01-03-2024  MZ      JAZZ-65385		Added Target TimeClass
	** 3 	12-04-2023  BW/MZ	JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 4	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 5	06-14-2024  MZ		JAZZ-73080		Filtering out 0 NPIs providers 
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	
	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Budgeted Time Class
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) FROM [int].[FactImportProvider] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	-- Volumes
	INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		pr.[ProviderID],
		pr.[ProviderCode] ,
		map.[OBForecastDetailID],
		obfd.Code AS AccountRollup,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, PatientClassID, PayorID, FinancialReportingID, m.FiscalMonthID, f.Value, LockType
		FROM (
			SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, PatientClassID, PayorID, FinancialReportingID,  
				bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, 
				bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.FactStatistics cv
				INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID
				Inner JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID
			WHERE bdgt.BudgetPhaseID = 3
				AND cv.BudgetConfigID = @BudgetConfigID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
		INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = BudgetedData.ProviderID
		INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI
		INNER JOIN [fp].[AccountOBForecastDetailMapping] map ON map.AccountID = BudgetedData.AccountID AND map.BudgetConfigID = @BudgetConfigID
		INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
		AND pr.NPI NOT IN ('Not Specified', '0', '')

	-- Compensation
	INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		pr.ProviderID,
		pr.ProviderCode,
		map.[OBForecastDetailID] AS [OBForecastDetailID],
		obfd.Code AS AccountRollup,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		m.FiscalMonthID,
		m.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM fp.Staffing staff (READUNCOMMITTED)
	INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID
		CROSS APPLY (
		VALUES
			( 1, 34, BudgetAdjustedDollars01), 
			( 2, 34, BudgetAdjustedDollars02),
			( 3, 34, BudgetAdjustedDollars03),
			( 4, 34, BudgetAdjustedDollars04), 
			( 5, 34, BudgetAdjustedDollars05), 
			( 6, 34, BudgetAdjustedDollars06),
			( 7, 34, BudgetAdjustedDollars07), 
			( 8, 34, BudgetAdjustedDollars08), 
			( 9, 34, BudgetAdjustedDollars09), 
			( 10, 34, BudgetAdjustedDollars10),
			( 11, 34, BudgetAdjustedDollars11), 
			( 12, 34, BudgetAdjustedDollars12)
	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID
			INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI
			INNER JOIN [fp].[ProviderLineItemOBForecastDetailMapping] map ON map.ProviderLineItemID = staff.ProviderLineItemID AND map.BudgetConfigID = @BudgetConfigID
			INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID
			WHERE Value <> 0
			AND bc.BudgetConfigID = @BudgetConfigID
			AND pr.NPI NOT IN ('Not Specified', '0', '')
END
GO


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

-- fp.procMRProviderProjectionStampOff
CREATE     PROCEDURE [fp].[procMRProviderProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	11-10-2023 AO      JAZZ-62128		Initial Creation
	** 2	01-04-2024 MZ      JAZZ-65385		Added Target TimeClass and IsMonthsLoadedIncluded
	** 3	01-24-2024 MZ      JAZZ-64527		Fix Months Loaded
	** 4 	12-04-2023 BW/MZ   JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 5	03-18-2024 MZ      JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 6	04-03-2024 MZ      JAZZ-70053		Fix Month Loaded excluding logic
	** 7	06-14-2024 MZ      JAZZ-73080		Filtering out 0 NPIs providers
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)
	
	-- Clear out existing records for the selected FiscalYear and Projected Time Class
	-- and all months if months loaded included otherwise only months NOT loaded will be cleared
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) prov FROM [int].[FactImportProvider] prov
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID
		WHERE prov.FiscalYearID = @FiscalYear
			AND prov.TimeClassID = @TargetTimeClassID
			AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded)
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	-- Volumes
	INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		pr.[ProviderID],
		pr.[ProviderCode] ,
		map.[OBForecastDetailID],
		obfd.Code AS AccountRollup,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, PatientClassID, PayorID, FinancialReportingID, m.FiscalMonthID, f.Value, LockType
		FROM (
			SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, PatientClassID, PayorID, FinancialReportingID,  
				bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, 
				bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.FactStatistics cv
				INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID
				INNER JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID
			WHERE bdgt.BudgetPhaseID = 3
				AND cv.BudgetConfigID = @BudgetConfigID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
		INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = BudgetedData.ProviderID
		INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI
		INNER JOIN [fp].[AccountOBForecastDetailMapping] map ON map.AccountID = BudgetedData.AccountID AND map.BudgetConfigID = @BudgetConfigID
		INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
		AND pr.NPI NOT IN ('Not Specified', '0', '')
		AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded)

	-- Compensation
	INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		pr.ProviderID,
		pr.ProviderCode,
		map.[OBForecastDetailID] AS [OBForecastDetailID],
		obfd.Code AS AccountRollup,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		m.FiscalMonthID,
		m.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM fp.Staffing staff (READUNCOMMITTED)
	INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID
		CROSS APPLY (
		VALUES
			( 1, 34, ProjectionAdjustedDollars01), 
			( 2, 34, ProjectionAdjustedDollars02),
			( 3, 34, ProjectionAdjustedDollars03),
			( 4, 34, ProjectionAdjustedDollars04), 
			( 5, 34, ProjectionAdjustedDollars05), 
			( 6, 34, ProjectionAdjustedDollars06),
			( 7, 34, ProjectionAdjustedDollars07), 
			( 8, 34, ProjectionAdjustedDollars08), 
			( 9, 34, ProjectionAdjustedDollars09), 
			( 10, 34, ProjectionAdjustedDollars10),
			( 11, 34, ProjectionAdjustedDollars11), 
			( 12, 34, ProjectionAdjustedDollars12)
	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID
			INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI
			INNER JOIN [fp].[ProviderLineItemOBForecastDetailMapping] map ON map.ProviderLineItemID = staff.ProviderLineItemID AND map.BudgetConfigID = @BudgetConfigID
			INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID
			WHERE Value <> 0
			AND bc.BudgetConfigID = @BudgetConfigID
			AND pr.NPI NOT IN ('Not Specified', '0', '')
			AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded)
END
GO


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

-- fp.procMigrationConflictCheck
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2018-09-26  GF      E-02313		Created to monitor for possible merge conflicts
*************************************************************/
create proc fp.procMigrationConflictCheck
	@versionService nvarchar(100),
	@versionMajor nvarchar(100)
as
	select p.name into #procs from sys.procedures p inner join sys.schemas s on s.schema_id = p.schema_id where s.name = 'fp'

	select 
		p.name as ProcName,
		l.MigrationID,
		l.Name,
		l.Branch,
		l.DateTimeStamp,
		l.ForwardScript
	into #procHistory
	from 
		migration.migrationlog l
		inner join #procs p on l.ForwardScript like '%' + p.name + '%'
	where
		l.branch in(@versionService, @versionMajor)
		and l.sourcefolder = 'OB'

	select
		hService.ProcName,
		hService.Name as ServiceMigration,
		hService.DateTimeStamp as ServiceMigrationRunDate,
		hService.ForwardScript as ServiceForwardScript,
		hMajor.Name as MajorMigration,
		hMajor.DateTimeStamp as MajorMigrationRunDate,
		hMajor.ForwardScript as MajorForwardScript
	from
		#procHistory hService
		inner join #procHistory hMajor on hService.ProcName = hMajor.ProcName and hService.MigrationID != hMajor.MigrationID
	where
		hService.Branch = @versionService
		and hMajor.Branch = @versionMajor
		and hService.DateTimeStamp > hMajor.DateTimeStamp;

	drop table #procs
	drop table #procHistory
GO


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

-- fp.procNonStaffingByStatisticsFlexConfigPopulation
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2017-06-12  IP      D-05613		APE Data Refresh - Flex Mappings, add parameter to process particular departments
** 2    2018-07-03  IP      TK-59678	fix case when @SourceDimensionality is empty
** 3    2018-08-22  IP      TK-62741	fix case validating if @SourceDimensionality is empty
** 4    2018-09-25  GF      E-02313		Simplify source dimensionality to only department
** 5	2019-03-08	IP		B-22295		Removed using table variables, small optimizations
** 6 	2021-03-26  NT	    JAZZ-14122  Simplify code to remove null joins
** 7 	2023-02-06  MY	    JAZZ-48980  Update flexing to support x-department flexing
** 8 	2023-05-01  MY	    JAZZ-54277  Flex Config Mapping is not taking handling Cross Department Flexing properly
** 9    2023-08-09	BK		JAZZ-58152	Update for new data structure
*************************************************************/
CREATE PROCEDURE [fp].[procNonStaffingByStatisticsFlexConfigPopulation]
	 @EntityGroupConfigGUID UNIQUEIDENTIFIER,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
AS
BEGIN
	EXEC [dbo].[procSysDropTempTable] '#flexMap'
	EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality'

 	DECLARE @BudgetConfigID INT,
			@EntityGroupConfigID INT;
	
	SET @BudgetConfigID = (SELECT bc.BudgetConfigID 
						   FROM [fp].[EntityGroupConfig] egc
						   	INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
						   WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
			
	CREATE TABLE #flexMap (
                    DepartmentID INT NOT NULL,
                    GLAccountID INT NOT NULL,
	                StatAccountID INT NOT NULL,
					SourceDepartmentID INT NOT NULL
                );

	CREATE TABLE #SourceDimensionality (DepartmentID int)
	INSERT INTO #SourceDimensionality (DepartmentID)
	SELECT DepartmentID FROM @SourceDimensionality

	--If department filter table is empty then get distinct from FactStatistics
	IF NOT EXISTS (SELECT 1 FROM #SourceDimensionality)
	BEGIN
		INSERT INTO #SourceDimensionality(DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[PrimaryStatisticsConfig]
		WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
			AND IsNonStaffing = 1
	END
	
	-- Process the overrides as they overidde all configurations
	INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, nso.AccountID AS StatAccountID, stat.DepartmentID
	FROM [fp].[FactStatistics] stat
	    INNER JOIN [fp].[GeneralLedger] fgl ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID
	    INNER JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] ns ON ns.DepartmentID = fgl.DepartmentID AND ns.AccountID = fgl.AccountID
	    INNER JOIN [fp].[NSOverrideFlexConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID
		INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fgl.DepartmentID
	WHERE fgl.APEModelSectionID = 2
	    AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND stat.BudgetConfigID = @BudgetConfigID
	    AND ns.FlexMethodID = 1 -- Statistics Accounts
	    AND fgl.VariabilityID = 2 -- Variable only (simply to filter the data)
				
	-- Process department level configuration changes that are not overriden. We also will exclude Department/Account combos
	-- that have multiple source departments here as that is handled in the statement below.
	-- Aka: Process the Department/Account combinations that have primary stats of "Same as Department" in the Primary Stat Config
	INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, stat.DepartmentID
	FROM [fp].[FactStatistics] stat
	    INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
	    INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID
	    INNER JOIN [fp].[GeneralLedger] fgl ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID
	    INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fgl.DepartmentID
		INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fgl.DepartmentID
		LEFT JOIN (
				SELECT DepartmentID, AccountID 
				FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] 
				WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr
			ON ovr.DepartmentID = stat.DepartmentID
			AND ovr.AccountID = fgl.AccountID
		LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID
	WHERE fgl.APEModelSectionID = 2
	    AND fsc.IsNonStaffing = 1
	    AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND stat.BudgetConfigID = @BudgetConfigID
	    AND ns.FlexMethodID = 1 -- Statistics Accounts
	    AND fgl.VariabilityID = 2 -- Variable only (simply to filter the data)
	    AND ovr.DepartmentID IS NULL -- We only want records that are not overridden
		AND pscsd.DepartmentID IS NULL; --	We want records where there is no source department specified. When no source department is specified, it's the same as the regular department

	-- Process departments with multiple source departments
	INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT fsc.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, pscsd.DepartmentID
	FROM [fp].[PrimaryStatisticsConfig] fsc
		INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID -- We only want records where there are multiple source departments
	    INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
	    INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID
	    INNER JOIN [fp].[GeneralLedger] fgl ON fgl.DepartmentID = fsc.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID
	    INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID
		INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fsc.DepartmentID
		LEFT JOIN (
				SELECT DepartmentID, AccountID 
				FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] 
				WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr
			ON ovr.DepartmentID = fsc.DepartmentID
			AND ovr.AccountID = fgl.AccountID
	WHERE fgl.APEModelSectionID = 2 -- Non-Staffing
	    AND fsc.IsNonStaffing = 1
	    AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND stat.BudgetConfigID = @BudgetConfigID
	    AND ns.FlexMethodID = 1 -- Statistics Accounts
	    AND fgl.VariabilityID = 2 -- Variable only (simply to filter the data)
	    AND ovr.DepartmentID IS NULL; -- We only want records that are not overridden
 
	IF @IsDebug = 1
	BEGIN
		SELECT '#SourceDimensionality', DepartmentID FROM #SourceDimensionality
		SELECT '#flexMap', DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID FROM #flexMap
	END ELSE 
	BEGIN

		;WITH TRG
		AS (
			SELECT fcm.EntityGroupConfigID,
				 fcm.DepartmentID,
				 fcm.GLAccountID,
				 fcm.StatAccountID,
				 fcm.FlexingTypeID,
				 fcm.SourceDepartmentID
			FROM [fp].[FlexConfigMapping] fcm
			INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = fcm.DepartmentID
			WHERE EntityGroupConfigID = @EntityGroupConfigID 
				AND FlexingTypeID = 1 -- 1 is NonStaffingTypeID
		)
		MERGE TRG
		USING (
			SELECT @EntityGroupConfigID AS EntityGroupConfigID,
				  DepartmentID,
				  GLAccountID,
				  StatAccountID,
				  1 AS FlexingTypeID, -- 1 is NonStaffing (https://confluence.sdt.local/display/DD/Common+Calculations%2C+Equations%2C+IDs%2C+and+Look+Up+Values#CommonCalculations,Equations,IDs,andLookUpValues-FlexingIDs)
				  SourceDepartmentID
			FROM #flexMap
		) AS Src ON TRG.DepartmentID = SRC.DepartmentID 
			AND TRG.GLAccountID = SRC.GLAccountID 
			AND TRG.StatAccountID = SRC.StatAccountID
			AND TRG.SourceDepartmentID = SRC.SourceDepartmentID
		WHEN NOT MATCHED BY TARGET THEN
		INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.GLAccountID, src.StatAccountID, src.FlexingTypeID, src.SourceDepartmentID) 
		WHEN NOT MATCHED BY SOURCE THEN DELETE;

	END
 
 END
GO


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

-- fp.procOptimizationRebuildIndexes
CREATE PROC [fp].[procOptimizationRebuildIndexes]
AS
	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 = 'fp') 
		and t.name not like 'Archive%'
		and t.name not like 'Temp%'
	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 (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
GO


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

-- fp.procPadBenefits
CREATE   PROCEDURE [fp].[procPadBenefits]
		@BudgetConfigID int,
		@EntityGroupConfigID INT = NULL,
		@AccountID VARCHAR(MAX) = NULL,
		@FinancialReportingID INT = NULL,
		@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
	AS
	BEGIN

		/**************************************************************
		** Change History
		** CID  Date		Author	WI			Description
		** 1	2019-02-12	IP		B-22020		Added targeted refresh by adding parameters (added to subqueries). Manager staffing adjustment performance improvements
		** 2 	2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
		** 3 	2019-04-30  BK  	D-08400	Fix duplicate key error on insert
		** 4 	2019-06-03  MY  	TK-74658	Removing Table Varibles in query
		** 5	2021-02-16  NN  	Jazz-466	Remove null joins on dept
		** 6	2022-07-07  MD  	JAZZ-39280	Replace dbo.ConvertCSValuesToTable with STRING_SPLIT
		*************************************************************/

		CREATE TABLE #FilterByDepartment (DepartmentID int)
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
		-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
		IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
		BEGIN
			INSERT INTO #FilterByDepartment (DepartmentID)
			SELECT DISTINCT DepartmentID 
			FROM [fp].[FactBenefits] WITH (READUNCOMMITTED)
			WHERE BudgetConfigID = @BudgetConfigID	
		END
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT(@AccountID, ',')
		
		CREATE TABLE #BudgetPhase (BudgetPhaseID tinyint)
	   INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3
	   
	   CREATE TABLE #FilteredData (BenefitsID int)
	   INSERT INTO #FilteredData
		SELECT [fb].[BenefitsID]
		FROM [fp].[FactBenefits] fb
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID	
		WHERE	fb.BudgetConfigID = @BudgetConfigID
			  AND (fb.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null)
			  and (fb.AccountID IN (SELECT AccountID FROM #AccountIDs) or @AccountID is null)
			  and (fb.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null)
	
		INSERT INTO [fp].[FactBenefitsBudget]([BenefitsID], [BudgetPhaseID])
		SELECT [fb].[BenefitsID], [psh].[BudgetPhaseID]
		FROM #FilteredData fb
		OUTER APPLY #BudgetPhase psh
		WHERE NOT EXISTS (SELECT 1 FROM fp.FactBenefitsBudget bud WITH (READUNCOMMITTED) WHERE fb.BenefitsID = bud.BenefitsID AND bud.BudgetPhaseID = psh.BudgetPhaseID)
	
		INSERT INTO [fp].[FactBenefitsProjection]([BenefitsID], [BudgetPhaseID])
		SELECT [fb].[BenefitsID], [psh].[BudgetPhaseID]
		FROM #FilteredData fb
		OUTER APPLY #BudgetPhase psh
		WHERE NOT EXISTS (SELECT 1 FROM fp.FactBenefitsProjection proj WITH (READUNCOMMITTED) WHERE fb.BenefitsID = proj.BenefitsID AND proj.BudgetPhaseID = psh.BudgetPhaseID)
	
		INSERT INTO [fp].[FactBenefitsHistory]([BenefitsID])
		SELECT [fb].[BenefitsID]
		FROM #FilteredData fb
		WHERE NOT EXISTS (SELECT 1 FROM fp.FactBenefitsHistory hist WITH (READUNCOMMITTED) WHERE fb.BenefitsID = hist.BenefitsID)
	END
GO


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

-- fp.procPadBenefitsFromStaffing
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2019-01-15	IP		B-21392		Added targeted refresh by adding parameters
** 2	2019-02-12	IP		B-22020		Added targeted refresh by adding parameters (added to subqueries). Manager staffing adjustment performance improvements
** 3	2019-02-14	IP		B-22020		Added AccountID as CSV
** 4 	2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 5	2019-05-10	PA		D-08438		More switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 6	2019-05-13	PA		D-08438		Move padding proc inside if block
** 7	2019-05-13	PA		D-08438		Use @@RowCount and Select Into
** 8	2020-04-02	LR		B-24089 	Removed check for null within join conditions
** 9	2022-08-31	BW		JAZZ-41678 	Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
** 10	2023-10-31	BK		JAZZ-62801 	Update for Staffing restructure
*************************************************************/
CREATE   PROCEDURE [fp].[procPadBenefitsFromStaffing]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@AccountID VARCHAR(MAX),
	@FinancialReportingID INT,
	@FlexMethodID INT,
	@PayrollFilterSQL VARCHAR(MAX),
	@PayrollFilterTempTableSQL VARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE
AS
BEGIN
	-- Temp workaround so benefits flexing does blow up overnight
	SET NOCOUNT ON;

	IF OBJECT_ID('tempdb..#AccountsList') IS NOT NULL DROP TABLE #AccountsList
	-- Used in benefits flexing to pad data from staffing that are not in benefits. Doing this in flexing, but I can move this to repo, I'm just concerned with that
	-- method getting overly bogged down. We'd also need to make this a datarefresh method cause it would need to get called before flexing runs after sampling ran initially.

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF object_id('tempdb..#paddedBenefits') IS NOT NULL 
	BEGIN
		DROP TABLE #paddedBenefits
	END	
 	CREATE TABLE #paddedBenefits (BudgetConfigID INT, EntityGroupConfigID INT, EntityID INT, DepartmentID INT, AccountID INT,
								FinancialReportingID INT, UnitTypeID INT, FlexMethodID INT)
	
	DECLARE @DynamicSql NVARCHAR(MAX)

	set @DynamicSql = '
	' + @PayrollFilterTempTableSQL + '

	CREATE TABLE #accountIdList (AccountID INT PRIMARY KEY CLUSTERED)
	INSERT INTO #accountIdList (AccountID)
	SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')

    -- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID = @BudgetConfigID	
	END	
	
	INSERT INTO #paddedBenefits
	SELECT DISTINCT
		pr.BudgetConfigID,
		pr.EntityGroupConfigID,
		pr.EntityID,
		pr.DepartmentID,
		AccLst.AccountID,
		' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
		ut.UnitTypeID,
		' + CAST(@FlexMethodID as nvarchar(50)) + ' AS FlexMethodID		
	FROM [fp].[Staffing] (READUNCOMMITTED) pr
		CROSS APPLY (VALUES (34),(170),(171),(144),(169)) ut(UnitTypeID)
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID)
		CROSS APPLY (SELECT AccountID FROM #accountIdList) AccLst
		LEFT JOIN [fp].[FactBenefits] (READUNCOMMITTED) fbb ON pr.BudgetConfigID = fbb.BudgetConfigID
			AND pr.DepartmentID = fbb.DepartmentID
			AND ut.UnitTypeID = fbb.UnitTypeID
			AND pr.EntityID = fbb.EntityID
			AND fbb.FinancialReportingID = ' + CAST(@FinancialReportingID as nvarchar(50)) + '
			AND fbb.AccountID = AccLst.AccountID
	WHERE
		pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		AND pr.VariabilityID = 1
		AND ' + @PayrollFilterSQL + '
		AND fbb.BenefitsID IS NULL 
		
		
	IF (@@ROWCOUNT > 0)
	BEGIN
		INSERT INTO [fp].[FactBenefits] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, IsNew, AddDate)
		SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, 1 AS IsNew, GETDATE() AS AddDate FROM #paddedBenefits

		EXEC [fp].[procPadBenefits] @BudgetConfigID, @EntityGroupConfigID, @AccountID, @FinancialReportingID, @SourceDimensionality
		
	END
		


	-- Pad GL with any newly added benefit accounts
	DECLARE @AccountFromList INT
	DECLARE cur CURSOR LOCAL
	FOR
	SELECT DISTINCT AccountID FROM #accountIdList AccLst
	OPEN cur
	FETCH NEXT FROM cur INTO @AccountFromList
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--execute your sproc on each row
		EXEC [fp].[procLockBenefitsByConfiguration]  @BudgetConfigID, @SourceDimensionality, @EntityGroupConfigID, @AccountFromList, @FinancialReportingID
		FETCH NEXT FROM cur INTO @AccountFromList
	END
	CLOSE cur
	DEALLOCATE cur
	';
	

	EXECUTE sp_executesql @DynamicSql, 
		N'@BudgetConfigID INT,
		@EntityGroupConfigID INT,
		@AccountID VARCHAR(MAX),
		@FinancialReportingID INT,
		@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY',  
		@SourceDimensionality = @SourceDimensionality,
		@BudgetConfigID = @BudgetConfigID,
		@EntityGroupConfigID = @EntityGroupConfigID,
		@AccountID = @AccountID,
		@FinancialReportingID = @FinancialReportingID;  
	
END
GO


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

-- fp.procPadChargeDollarsToReimbursement
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2022-01-11	MY		JAZZ-31850	Initial
** 2	2022-02-15	BW		JAZZ-33266	Pulling in configuration via Plan Config > Section Setup
** 3	2022-06-06	MD		JAZZ-37249	Making charge temp table dimensionality unique
** 4	2023-01-30  NT		JAZZ-48268	Make change to use the new fp.ChargeVolume (data restructure)
** 5	2024-01-11	AO		JAZZ-64530	Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE   PROCEDURE [fp].[procPadChargeDollarsToReimbursement]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	

	DECLARE @IsMedicalSurgicalUsed BIT = 0,
			@IsMsdrgUsed BIT = 0,
			@IsCptUsed BIT = 0,
			@IsUBRevCodeUsed BIT = 0;

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'PrimaryCPTID'

	SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'UBRevCodeID'
	  
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #factReimbursementCharges (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT,
		PatientClassID INT,
		ServiceLineID INT,
		ServiceLineRollupID INT,
		MedicalSurgicalID INT,
		PayorID INT,
		PayorGroupID INT,
		MSDRGID INT,
		PrimaryCPTID INT,
		UBRevCodeID INT
	)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE d.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END

	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID
	INTO #reimbursementTargeting
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
	WHERE cv.BudgetConfigID = @BudgetConfigID
		
	-- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well.
	-- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup
	INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
		MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID)
	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID,  
		sd.PayorID, sd.PayorGroupID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
		INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
	        AND cv.PatientClassID = sd.PatientClassID
	        AND cv.ServiceLineID = sd.ServiceLineID
			AND cv.AgeCohortID = sd.AgeCohortID
	        AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
	        AND cv.MSDRGID = sd.MSDRGID
	        AND cv.PrimaryCPTID = sd.CPTID
	        AND cv.ServiceProviderID = sd.ProviderID
	        AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
	WHERE cv.BudgetConfigID = @BudgetConfigID

	UNION

	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		0 AS PayorID, 0 AS PayorGroupID,
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
		LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
	        AND cv.PatientClassID = sd.PatientClassID
	        AND cv.ServiceLineID = sd.ServiceLineID
			AND cv.AgeCohortID = sd.AgeCohortID
	        AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
	        AND cv.MSDRGID = sd.MSDRGID
	        AND cv.PrimaryCPTID = sd.CPTID
	        AND cv.ServiceProviderID = sd.ProviderID
	        AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
		LEFT JOIN #factReimbursementCharges tmp ON 
			cv.BudgetConfigID = tmp.BudgetConfigID
			AND cv.EntityGroupConfigID = tmp.EntityGroupConfigID
			AND cv.EntityID = tmp.EntityID
			AND cv.PatientClassID = tmp.PatientClassID
			AND cv.ServiceLineID = tmp.ServiceLineID
			AND cv.MedicalSurgicalID = tmp.MedicalSurgicalID
			AND tmp.PayorID = 0
			AND tmp.PayorGroupID = 0
			AND cv.MSDRGID = tmp.MSDRGID
			AND cv.PrimaryCPTID = tmp.PrimaryCPTID
			AND cv.UBRevCodeID = tmp.UBRevCodeID
	WHERE cv.BudgetConfigID = @BudgetConfigID
		AND sd.EntityID IS NULL
		AND tmp.BudgetConfigID IS NULL -- Ensure that we didn't already add the 0 PayorID/0 PayorGroupID

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID],
				[PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID]
		FROM #factReimbursementCharges
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID],
				[PayorID], [PayorGroupID], fact.[MSDRGID], fact.[PrimaryCPTID], fact.[UBRevCodeID]
			FROM [fp].[FactReimbursementCharges] fact    
				INNER JOIN #reimbursementTargeting targeting ON
					fact.BudgetConfigID = targeting.BudgetConfigID
					AND fact.EntityGroupConfigID = targeting.EntityGroupConfigID
					AND fact.EntityID = targeting.EntityID
					AND fact.PatientClassID = targeting.PatientClassID
					AND fact.ServiceLineID = targeting.ServiceLineID
					AND fact.ServiceLineRollupID = targeting.ServiceLineRollupID
					AND fact.MedicalSurgicalID = targeting.MedicalSurgicalID
					AND fact.MSDRGID = targeting.MSDRGID
					AND fact.PrimaryCPTID = targeting.PrimaryCPTID
					AND fact.UBRevCodeID = targeting.UBRevCodeID
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  
  
		MERGE TGT AS target  
		USING #factReimbursementCharges AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.PrimaryCPTID = src.PrimaryCPTID 
			AND target.UBRevCodeID = src.UBRevCodeID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN NOT MATCHED BY TARGET THEN  
			INSERT ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID],
				[PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID])  
			VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.ServiceLineRollupID, src.MedicalSurgicalID,
				src.PayorID, src.PayorGroupID, src.MSDRGID, src.PrimaryCPTID, src.UBRevCodeID);

		-- Pad the other tables (Budget, Projection, and History)
		EXEC [fp].[procPadReimbursementCharges] @BudgetConfigID, @SourceDimensionality
	END
END
GO


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

-- fp.procPadChargeToGeneralLedgerCrosswalk
CREATE   PROCEDURE [fp].[procPadChargeToGeneralLedgerCrosswalk] 
	 @BudgetConfigID INT,
	 @EntityGroupConfigID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  BLI			Description
	 ** 1 	 2021-03-09  BK  	 JAZZ-16331	    Create proc
	 ** 2	 2021-04-05  SD		 JAZZ-18186		Fix alias
	 ** 3    2021-10-04  NT	     JAZZ-26831     FinancialReportingID should be OBDollarsFinancialReportingID instead of OBUnitsFinancialReportingID.
	 ** 4 	 2023-08-04  BW  	 JAZZ-58151	    Update for new GL data structure
	 ** 5 	 2023-11-07  MY  	 JAZZ-63252	    Add ChangeHistoryGroupingGUID to new Record
	 *************************************************************/	 
	 
 	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
 	IF OBJECT_ID('tempdb..#RecordsToPad') IS NOT NULL DROP TABLE #recordsToPad

	CREATE TABLE #RecordsToPad (DepartmentID int, EntityID int, AccountID int)
	

	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 
	BEGIN	

		INSERT INTO #RecordsToPad (DepartmentID, EntityID, AccountID)
		SELECT DISTINCT config.DepartmentID, dept.EntityID, config.AccountID 
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted)
			INNER JOIN fw.DimDepartment dept ON config.DepartmentID = dept.DepartmentID 
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND config.AccountID > 0
	END
	ELSE
	BEGIN
		CREATE TABLE #FilterByDepartment (DepartmentID int)
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

		INSERT INTO #RecordsToPad (DepartmentID, EntityID, AccountID)
		SELECT DISTINCT config.DepartmentID, dept.EntityID, config.AccountID 
		FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted)
			INNER JOIN #FilterByDepartment ft ON config.DepartmentID = ft.DepartmentID 
			INNER JOIN fw.DimDepartment dept ON ft.DepartmentID = dept.DepartmentID 
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND config.AccountID > 0
	END
  
 	-- Pad records from the crosswalk configuration to stats
	INSERT INTO [fp].[GeneralLedger] (BudgetConfigID, EntityGroupConfigID, DepartmentID, EntityID, AccountID, FinancialReportingID, VariabilityID, APEModelSectionID, IsNew, AddDate, ChangeHistoryGroupingGUID)
	SELECT
		@BudgetConfigID AS BudgetConfigID,
		@EntityGroupConfigID AS EntityGroupConfigID, 
		pad.DepartmentID, 
		pad.EntityID,
		pad.AccountID, 
		acc.OBDollarsFinancialReportingID,
		variability.VariablitiyID,
		1 as APEModelSectionID,
		1 AS IsNew,
		GETDATE() AS AddDate,
		NEWID() AS ChangeHistoryGroupingGUID
	FROM #recordsToPad pad		
		INNER JOIN [fw].[DimAccount] acc ON pad.AccountID = acc.AccountID
		CROSS JOIN (SELECT 1 AS VariablitiyID UNION SELECT 2 AS VariablitiyID) variability
		LEFT JOIN [fp].[GeneralLedger] gl ON
				gl.DepartmentID = pad.DepartmentID
			AND gl.AccountID = pad.AccountID
			AND gl.EntityGroupConfigID = @EntityGroupConfigID
	WHERE gl.GeneralLedgerID IS NULL
	
 	-- Pad any GL depdendent data
 	EXEC [fp].[procPadGeneralLedger] @BudgetConfigID, @SourceDimensionality, @EntityGroupConfigID
 	
 	-- Lock the cells
 	UPDATE gl
	SET TargetLockFlag = 1, 
		 TargetLockType = 3,
		 BudgetLockFlag = 1, 
		 BudgetLockType = 3,
		 ProjectionLockFlag = 1, 
		 ProjectionLockType = 3
	FROM #recordsToPad config
		INNER JOIN [fp].[GeneralLedger] gl 
			ON gl.DepartmentID = config.DepartmentID 
				AND gl.AccountID = config.AccountID 
	WHERE gl.EntityGroupConfigID = @EntityGroupConfigID
 	
 END
GO


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

-- fp.procPadChargeUnitToStatCrosswalk
CREATE PROCEDURE [fp].[procPadChargeUnitToStatCrosswalk] 
	 @BudgetConfigID INT,
	 @EntityGroupConfigID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 *************************************************************/	 
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
 
 	SELECT DISTINCT config.DepartmentID, AccountID 
	INTO #recordsToPad
	FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] config (readuncommitted)
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = config.DepartmentID or ft.DepartmentID is null)
	WHERE EntityGroupConfigID = @EntityGroupConfigID and config.AccountID > 0
 
 	-- Pad records from the crosswalk configuration to stats
	INSERT INTO [fp].[FactStatistics] (EntityGroupConfigID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, BudgetConfigID, EntityID, IsNew, AddDate)
	SELECT
		@EntityGroupConfigID AS EntityGroupConfigID, 
		pad.DepartmentID, 
		pad.AccountID, 
		acc.PatientClassID,
		acc.OBPayorID,
		acc.OBUnitsFinancialReportingID,
		140 AS UnitTypeID, 
		@BudgetConfigID AS BudgetConfigID,
		dept.EntityID,
		1 AS IsNew,
		GETDATE() AS AddDate
	FROM #recordsToPad pad		
		INNER JOIN [fw].[DimAccount] acc ON pad.AccountID = acc.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pad.DepartmentID = dept.DepartmentID
		LEFT JOIN [fp].[FactStatistics] stat ON
				stat.DepartmentID = pad.DepartmentID
			AND stat.AccountID = pad.AccountID
			AND stat.UnitTypeID = 140
			AND stat.EntityGroupConfigID = @EntityGroupConfigID
	WHERE stat.StatisticsID IS NULL
	
 	-- Pad any statistic depdendent data
 	EXEC [fp].[procPadStatistics] @BudgetConfigID
 	
 	-- Lock the cells
 	UPDATE budg
	SET budg.LockFlag = 1, 
		 budg.LockType = 3
	FROM #recordsToPad config
		INNER JOIN [fp].[FactStatistics] fs 
			ON fs.DepartmentID = config.DepartmentID 
				AND fs.AccountID = config.AccountID 
		INNER JOIN [fp].[FactStatisticsBudget] budg ON fs.StatisticsID = budg.StatisticsID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
 	
	UPDATE proj
	SET proj.LockFlag = 1, 
		 proj.LockType = 3
	FROM #recordsToPad config
		INNER JOIN [fp].[FactStatistics] fs 
			ON fs.DepartmentID = config.DepartmentID 
				AND fs.AccountID = config.AccountID 
		INNER JOIN [fp].[FactStatisticsProjection] proj ON fs.StatisticsID = proj.StatisticsID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
 
 
 END
GO


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

-- fp.procPadChargeVolume
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2021-03-08  LR  	 JAZZ-16329		Added padding for the new ChargeVolumeDollar tables
 ** 2 	 2021-08-12  MD  	 JAZZ-24639		Added padding for the new ChargeVolumeDollarHistory table
 ** 3 	 2022-08-31  VZ  	 JAZZ-41715		Removed check for null from join clause
 ** 4 	 2023-03-06  MY  	 JAZZ-48307		Update charges adjustment to support data model changes
*************************************************************/	 
CREATE   PROCEDURE [fp].[procPadChargeVolume]
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

   	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT)
	INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3
	
	CREATE TABLE #FilteredData (ChargeVolumeID INT PRIMARY KEY CLUSTERED)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT [fcv].[ChargeVolumeID]
		FROM [fp].[ChargeVolume] fcv
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID	
		WHERE fcv.BudgetConfigID = @BudgetConfigID
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT [fcv].[ChargeVolumeID]
		FROM [fp].[ChargeVolume] fcv	
		WHERE fcv.BudgetConfigID = @BudgetConfigID
	END
    
	INSERT INTO [fp].[ChargeVolumeHistory]([ChargeVolumeID])
	SELECT [fcv].[ChargeVolumeID]
	FROM [fp].[ChargeVolume] fcv
		INNER JOIN #FilteredData filter ON fcv.ChargeVolumeID = filter.ChargeVolumeID
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.ChargeVolumeHistory hist WITH (READUNCOMMITTED) WHERE fcv.ChargeVolumeID = hist.ChargeVolumeID)	
	
END
GO


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

-- fp.procPadEncountersToReimbursement
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			 Description
** 1    2022-02-04  MY      JAZZ-31904   Initial
** 2    2023-01-17  BK      JAZZ-48267   New data structure
** 3    2023-11-15  BK      JAZZ-62974   Fix when Entity and ServiceLine not in Charges
** 4    2024-01-11  AO      JAZZ-64530   Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE   PROCEDURE [fp].[procPadEncountersToReimbursement]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	DECLARE @IsMedicalSurgicalUsed BIT,
			@IsMsdrgUsed BIT,
			@IsCptUsed BIT

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'PrimaryCPTID'

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters;
	IF OBJECT_ID('tempdb..#encounterTargeting') IS NOT NULL DROP TABLE #encounterTargeting;

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT);

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED)
			INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
		UNION
		SELECT DISTINCT sle.EntityID, sle.ServiceLineID 
		FROM fp.ServiceLineEncounter sle 
			LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID 
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0)
		
	END ELSE 
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
		
	SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		sle.PayorID, sle.PayorGroupID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID
	INTO #factReimbursementEncounters
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
	WHERE sle.BudgetConfigID = @BudgetConfigID

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#encounterTargeting', EntityID, ServiceLineID FROM #encounterTargeting
		SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID
		FROM #factReimbursementEncounters sle
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID],
				[PayorID], [PayorGroupID], fact.[MSDRGID], fact.[CPTID]
			FROM [fp].[FactReimbursementEncounter] fact    
				INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #factReimbursementEncounters AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN NOT MATCHED BY TARGET THEN  
			INSERT ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID],
				[PayorID], [PayorGroupID], [MSDRGID], [CPTID])  
			VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.ServiceLineRollupID, src.MedicalSurgicalID,
				src.PayorID, src.PayorGroupID, src.MSDRGID, src.CPTID);

		-- Pad the other tables (Budget, Projection, and History)
		EXEC [fp].[procPadReimbursementEncounters] @BudgetConfigID, @SourceDimensionality
	END
END
GO


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

-- fp.procPadGLForBenefitsToGLCrosswalk
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2019-01-15	IP		B-21392		Added targeted refresh by adding parameters
** 2 	2019-03-26  IP  	B-22466		Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 3	2019-06-19	MY		TK-75217	Add Date and IsNew Flag now gets populated during padding
** 4 	2020-08-04	NN      JAZZ-133    Remove NULL checks to JOINS and drop temp table
** 5 	2021-09-03	NT      JAZZ-25623  Pad records for both variability 1 & 2
** 6 	2023-08-10	MY      JAZZ-58216  Upgrade GL Structure
*************************************************************/
CREATE   PROC [fp].[procPadGLForBenefitsToGLCrosswalk]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@EntityGroupConfigID INT = NULL,
	@AccountID INT = NULL,
	@FinancialReportingID INT = NULL
 AS
BEGIN
	
	EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment'

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		-- Pad records from Benefits to GL
		INSERT INTO [fp].[GeneralLedger] (EntityGroupConfigID, DepartmentID, AccountID, BudgetConfigID, FinancialReportingID, 
			VariabilityID, EntityID, APEModelSectionID, IsNew, AddDate)
		SELECT
			be.EntityGroupConfigID, 
			be.DepartmentID, 
			be.AccountID, 
			be.BudgetConfigID, 
			be.FinancialReportingID, 
			va.VariabilityID,
			be.EntityID,
			5 AS APEModelSectionID, -- Benefits
			1 AS IsNew,
			GETDATE() AS AddDate
		FROM [fp].[FactBenefits] be
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = be.DepartmentID
		INNER JOIN fw.DimVariability va on 1=1
		LEFT JOIN [fp].[GeneralLedger] gl
			ON gl.BudgetConfigID = be.BudgetConfigID
			AND gl.DepartmentID = be.DepartmentID
			AND gl.AccountID = be.AccountID
			AND be.UnitTypeID = 34
			AND gl.FinancialReportingID = be.FinancialReportingID
			AND gl.EntityID = be.EntityID
			AND gl.VariabilityID = va.VariabilityID
		WHERE
			be.BudgetConfigID = @BudgetConfigID
			AND be.UnitTypeID = 34
			and (be.AccountID = @AccountID or @AccountID is null) 
			and (be.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) 
			and (be.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null)
			AND va.VariabilityID IN (1, 2)
			AND gl.GeneralLedgerID IS NULL

	END ELSE 
	BEGIN

		-- Pad records from Benefits to GL
		INSERT INTO [fp].[GeneralLedger] (EntityGroupConfigID, DepartmentID, AccountID, BudgetConfigID, FinancialReportingID, 
			VariabilityID, EntityID, APEModelSectionID, IsNew, AddDate)
		SELECT
			be.EntityGroupConfigID, 
			be.DepartmentID, 
			be.AccountID, 
			be.BudgetConfigID, 
			be.FinancialReportingID, 
			va.VariabilityID,
			be.EntityID,
			5 AS APEModelSectionID, -- Benefits
			1 AS IsNew,
			GETDATE() AS AddDate
		FROM [fp].[FactBenefits] be
		INNER JOIN fw.DimVariability va on 1=1
		LEFT JOIN [fp].[GeneralLedger] gl
			ON gl.BudgetConfigID = be.BudgetConfigID
			AND gl.DepartmentID = be.DepartmentID
			AND gl.AccountID = be.AccountID
			AND be.UnitTypeID = 34
			AND gl.FinancialReportingID = be.FinancialReportingID
			AND gl.EntityID = be.EntityID
			AND gl.VariabilityID = va.VariabilityID
		WHERE
			be.BudgetConfigID = @BudgetConfigID
			AND be.UnitTypeID = 34
			and (be.AccountID = @AccountID or @AccountID is null) 
			and (be.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) 
			and (be.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null)
			AND va.VariabilityID IN (1, 2)
			AND gl.GeneralLedgerID IS NULL
			
	END
		
	-- Pad the remaining tables missing data
	EXEC [fp].[procPadGeneralLedger] @BudgetConfigID, @SourceDimensionality, @EntityGroupConfigID, @AccountID, @FinancialReportingID

END
GO


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

-- fp.procPadGeneralLedger
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2019-01-15	IP		B-21392	    Added targeted refresh by adding parameters
** 2 	2019-03-26  IP  	B-22466		Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 3 	2019-04-30  BK  	D-08400		Fix duplicate key error on insert and eliminated duplicate query with temp table
** 4 	2020-08-04	NN      JAZZ-133    Remove NULL checks to JOINS and drop temp tables
** 5	5-15-2023   NT      JAZZ-54290	Data restructure changes to use new fp.GeneralLedger table
*************************************************************/
CREATE   PROCEDURE [fp].[procPadGeneralLedger]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@EntityGroupConfigID INT = NULL,
	@AccountID INT  = NULL,
	@FinancialReportingID INT  = NULL
AS
BEGIN

	exec [dbo].[procSysDropTempTable] '#FilterByDepartment'
	exec [dbo].[procSysDropTempTable] '#FilteredData'
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #FilteredData (GeneralLedgerID int)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN	
		INSERT INTO #FilteredData
		SELECT [fgl].[GeneralLedgerID]
		FROM [fp].[GeneralLedger] fgl
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
		WHERE	fgl.BudgetConfigID = @BudgetConfigID
				and (fgl.AccountID = @AccountID or @AccountID is null) 
				and (fgl.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) 
				and (fgl.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null)
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT [fgl].[GeneralLedgerID]
		FROM [fp].[GeneralLedger] fgl	
		WHERE	fgl.BudgetConfigID = @BudgetConfigID
				and (fgl.AccountID = @AccountID or @AccountID is null) 
				and (fgl.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) 
				and (fgl.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null)
	END
	
	INSERT INTO [fp].[GeneralLedgerHistory]([GeneralLedgerID])
	SELECT [fgl].[GeneralLedgerID]
	FROM #FilteredData fgl
	WHERE NOT EXISTS (SELECT 1 FROM fp.GeneralLedgerHistory hist WITH (READUNCOMMITTED) WHERE fgl.GeneralLedgerID = hist.GeneralLedgerID)
END
GO


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

-- fp.procPadGeneralLedgerReimbursement
CREATE   PROCEDURE [fp].[procPadGeneralLedgerReimbursement] 
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    05-23-2023   MZ        JAZZ-54503  Initial Creation
	*************************************************************/


	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#entities') IS NOT NULL DROP TABLE #entities;

	CREATE TABLE #FilterByDepartment (DepartmentID INT);
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	CREATE TABLE #entities (EntityID INT)
		
	-- We need to convert the departments into the Entities because we don't have that coming in. 
	-- If this ends up being slow, we can target this further by using the mapping table or similarly to
	-- [fp].[procPadReimbursementCharges]
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #entities (EntityID)
		SELECT DISTINCT dept.EntityID
		FROM fw.DimDepartment dept
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = dept.DepartmentID
	END ELSE BEGIN
		INSERT INTO #entities (EntityID)
		SELECT DISTINCT EntityID
		FROM fw.DimEntity
	END

	
	INSERT INTO [fp].[ReimbursementGeneralLedgerHistory] ([ReimbursementGeneralLedgerID])
	SELECT [ReimbursementGeneralLedgerID]
	FROM [fp].[ReimbursementGeneralLedger] rgl
		INNER JOIN #entities tgt ON tgt.EntityID = rgl.EntityID
	WHERE rgl.BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM [fp].[ReimbursementGeneralLedgerHistory] hist WITH (READUNCOMMITTED) WHERE rgl.[ReimbursementGeneralLedgerID] = hist.[ReimbursementGeneralLedgerID])

	
END
GO


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

-- fp.procPadGeneralLedgerToReimbursement
CREATE   PROCEDURE [fp].[procPadGeneralLedgerToReimbursement] 
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    05-23-2023   MZ        JAZZ-54503  Initial Creation
	** 2    07-12-2023   AO        JAZZ-57493  Added check when not matched
	** 3    01-03-2024	 AO        JAZZ-65384  Data transfer for GL is based on selected Model in Plan Config 
	*************************************************************/

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData;

	CREATE TABLE #FilterByDepartment (DepartmentID INT);
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	DECLARE @Revenue INT = 1;

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE gl.BudgetConfigID = @BudgetConfigID 
			AND ((bc.DefaultReimbursementNetRevenueModelID = 2 
				AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) 
				OR rnrm.NetRevenueModelID = 2) -- GL Model
	END ELSE
	BEGIN
		DELETE d FROM #FilterByDepartment d
			INNER JOIN [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) ON d.DepartmentID = gl.DepartmentID
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE gl.BudgetConfigID <> @BudgetConfigID 
			AND ((bc.DefaultReimbursementNetRevenueModelID <> 2 
				AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 2)) 
				OR rnrm.NetRevenueModelID <> 2) -- GL Model
	END
		

	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID
	INTO #RevenueData
	FROM [fp].[GeneralLedger] gl
		JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
	WHERE gl.BudgetConfigID = @BudgetConfigID 
		AND gl.APEModelSectionID = @Revenue

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment
		SELECT '#RevenueData', * FROM #RevenueData
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [PayorGroupID]
			FROM [fp].[ReimbursementGeneralLedger]    
			WHERE BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #RevenueData AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.PayorGroupID = src.OBPayorGroupID 
		)  
		WHEN NOT MATCHED BY TARGET THEN  
			INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID)
			VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.OBPayorGroupID, src.PatientClassID);

		-- Pad History table
		EXEC [fp].[procPadGeneralLedgerReimbursement] @BudgetConfigID, @SourceDimensionality
	END
	
END
GO


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

-- fp.procPadReimbursementCharges
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			  Description
 ** 1 	 2021-01-12  MY  	 JAZZ-31850	  Initial
 ** 2	 2022-02-15	 BW		 JAZZ-33266	  Pulling in configuration via Plan Config > Section Setup
 ** 4   2023-01-26  NT       JAZZ-48268   Make change to use the new fp.ChargeVolume (data restructure)
*************************************************************/	 
CREATE   PROCEDURE [fp].[procPadReimbursementCharges]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	DECLARE @IsMedicalSurgicalUsed BIT = 0,
			@IsMsdrgUsed BIT = 0,
			@IsCptUsed BIT = 0,
			@IsUBRevCodeUsed BIT = 0;

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'PrimaryCPTID'

	SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'UBRevCodeID'

   	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT)
	INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3
	
	CREATE TABLE #FilteredData (ReimbursementChargesID INT PRIMARY KEY CLUSTERED)
	
	-- You will notice we don't have Payor on here, that's just because we don't have that inate with Charges
	-- and the performance benefit of getting that outweights the targeting.
	CREATE TABLE #reimbursementTargeting (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT,
		PatientClassID INT,
		ServiceLineID INT,
		ServiceLineRollupID INT,
		MedicalSurgicalID INT,
		MSDRGID INT,
		PrimaryCPTID INT,
		UBRevCodeID INT
	)

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #reimbursementTargeting (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
			MedicalSurgicalID, MSDRGID, PrimaryCPTID, UBRevCodeID)
		SELECT DISTINCT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
			CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID
		FROM fp.ChargeVolume cv 
			INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = cv.DepartmentID
		WHERE cv.BudgetConfigID = @BudgetConfigID
	END ELSE BEGIN
		INSERT INTO #reimbursementTargeting (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
			MedicalSurgicalID, MSDRGID, PrimaryCPTID, UBRevCodeID)
		SELECT DISTINCT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
			CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID
		FROM fp.ChargeVolume cv 
			INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
		WHERE cv.BudgetConfigID = @BudgetConfigID
	END

	INSERT INTO #FilteredData (ReimbursementChargesID)
	SELECT DISTINCT ReimbursementChargesID
	FROM fp.FactReimbursementCharges frc
		INNER JOIN #reimbursementTargeting tgt ON
			tgt.BudgetConfigID = frc.BudgetConfigID
			AND tgt.EntityGroupConfigID = frc.EntityGroupConfigID
			AND tgt.EntityID = frc.EntityID
			AND tgt.PatientClassID = frc.PatientClassID
			AND tgt.ServiceLineID = frc.ServiceLineID
			AND tgt.MedicalSurgicalID = frc.MedicalSurgicalID
			AND tgt.MSDRGID = frc.MSDRGID
			AND tgt.PrimaryCPTID = frc.PrimaryCPTID
			AND tgt.UBRevCodeID = frc.UBRevCodeID
    
	INSERT INTO [fp].[FactReimbursementChargesBudget]([ReimbursementChargesID], [BudgetPhaseID])
	SELECT [fcv].[ReimbursementChargesID], [psh].[BudgetPhaseID]
	FROM [fp].[FactReimbursementCharges] fcv
		INNER JOIN #FilteredData filter ON fcv.ReimbursementChargesID = filter.ReimbursementChargesID
		OUTER APPLY #BudgetPhase psh
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementChargesBudget bud WITH (READUNCOMMITTED) WHERE fcv.ReimbursementChargesID = bud.ReimbursementChargesID AND bud.BudgetPhaseID = psh.BudgetPhaseID)

	INSERT INTO [fp].[FactReimbursementChargesProjection]([ReimbursementChargesID], [BudgetPhaseID])
	SELECT [fcv].[ReimbursementChargesID], [psh].[BudgetPhaseID]
	FROM [fp].[FactReimbursementCharges] fcv
		INNER JOIN #FilteredData filter ON fcv.ReimbursementChargesID = filter.ReimbursementChargesID
		OUTER APPLY #BudgetPhase psh
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementChargesProjection proj WITH (READUNCOMMITTED) WHERE fcv.ReimbursementChargesID = proj.ReimbursementChargesID AND proj.BudgetPhaseID = psh.BudgetPhaseID)

	INSERT INTO [fp].[FactReimbursementChargesHistory]([ReimbursementChargesID])
	SELECT [fcv].[ReimbursementChargesID]
	FROM [fp].[FactReimbursementCharges] fcv
		INNER JOIN #FilteredData filter ON fcv.ReimbursementChargesID = filter.ReimbursementChargesID
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementChargesHistory hist WITH (READUNCOMMITTED) WHERE fcv.ReimbursementChargesID = hist.ReimbursementChargesID)
					
END
GO


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

-- fp.procPadReimbursementEncounters
-------------------------------------------------------------
-- re-add proc
-------------------------------------------------------------
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			  Description
 ** 1 	 2021-01-12  MY  	 JAZZ-31850	  Initial
*************************************************************/	 
CREATE   PROCEDURE [fp].[procPadReimbursementEncounters]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

   	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT)
	INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3

	CREATE TABLE #FilteredData (ReimbursementEncounterID INT PRIMARY KEY CLUSTERED)
	CREATE TABLE #entities (EntityID INT)

	-- We need to convert the departments into the Entities because we don't have that coming in. 
	-- If this ends up being slow, we can target this further by using the mapping table or similarly to
	-- [fp].[procPadReimbursementCharges]
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #entities (EntityID)
		SELECT DISTINCT dept.EntityID
		FROM fw.DimDepartment dept
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = dept.DepartmentID
	END ELSE BEGIN
		INSERT INTO #entities (EntityID)
		SELECT DISTINCT EntityID
		FROM fw.DimEntity
	END

	INSERT INTO #FilteredData (ReimbursementEncounterID)
	SELECT DISTINCT ReimbursementEncounterID
	FROM fp.FactReimbursementEncounter frc
		INNER JOIN #entities tgt ON tgt.EntityID = frc.EntityID
	WHERE frc.BudgetConfigID = @BudgetConfigID

	INSERT INTO [fp].[FactReimbursementEncounterBudget] ([ReimbursementEncounterID], [BudgetPhaseID])
	SELECT [fcv].[ReimbursementEncounterID], [psh].[BudgetPhaseID]
	FROM [fp].[FactReimbursementEncounter] fcv
		INNER JOIN #FilteredData filter ON fcv.ReimbursementEncounterID = filter.ReimbursementEncounterID
		OUTER APPLY #BudgetPhase psh
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementEncounterBudget bud WITH (READUNCOMMITTED) WHERE fcv.ReimbursementEncounterID = bud.ReimbursementEncounterID AND bud.BudgetPhaseID = psh.BudgetPhaseID)

	INSERT INTO [fp].[FactReimbursementEncounterProjection] ([ReimbursementEncounterID], [BudgetPhaseID])
	SELECT [fcv].[ReimbursementEncounterID], [psh].[BudgetPhaseID]
	FROM [fp].[FactReimbursementEncounter] fcv
		INNER JOIN #FilteredData filter ON fcv.ReimbursementEncounterID = filter.ReimbursementEncounterID
		OUTER APPLY #BudgetPhase psh
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementEncounterProjection proj WITH (READUNCOMMITTED) WHERE fcv.ReimbursementEncounterID = proj.ReimbursementEncounterID AND proj.BudgetPhaseID = psh.BudgetPhaseID)

	INSERT INTO [fp].[FactReimbursementEncounterHistory] ([ReimbursementEncounterID])
	SELECT [fcv].[ReimbursementEncounterID]
	FROM [fp].[FactReimbursementEncounter] fcv
		INNER JOIN #FilteredData filter ON fcv.ReimbursementEncounterID = filter.ReimbursementEncounterID
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementEncounterHistory hist WITH (READUNCOMMITTED) WHERE fcv.ReimbursementEncounterID = hist.ReimbursementEncounterID)

END
GO


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

-- fp.procPadReimbursementToGLCrosswalk
CREATE   PROC [fp].[procPadReimbursementToGLCrosswalk]
	@EntityGroupConfigID INT,
	@BudgetConfigID INT,
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1    2022-05-17  MD      JAZZ-37249		Initial Commit
	** 2    2022-08-16  MD      JAZZ-42139		Update to handle EntityID on ReimbursementToGeneralLedgerCrosswalkConfiguration
	** 3    2023-08-16  MD      JAZZ-58766		Update for GL restructure
	*******************************************************/
	IF OBJECT_ID('tempdb..#itemsToPad') IS NOT NULL DROP TABLE #itemsToPad
	IF OBJECT_ID('tempdb..#uniqueCADimensions') IS NOT NULL DROP TABLE #uniqueCADimensions
	IF OBJECT_ID('tempdb..#insertTemp') IS NOT NULL DROP TABLE #insertTemp
	IF OBJECT_ID('tempdb..#tmpReimbursement') IS NOT NULL DROP TABLE #tmpReimbursement

	CREATE TABLE #tmpReimbursement (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		OBDollarsFinancialReportingID INT
	)

	CREATE TABLE #itemsToPad (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		OBDollarsFinancialReportingID INT
	)

	--------------------------------------------------------------
	--Get unique contractual allowance config dimensionality for given budget config
	--------------------------------------------------------------
	SELECT DISTINCT
		data.BudgetConfigGUID,
		data.EntityID, 
		data.DepartmentID, 
		data.AccountID,
		da.OBDollarsFinancialReportingID
	INTO #uniqueCADimensions
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID

	--------------------------------------------------------------
	--Insert into temp table
	--------------------------------------------------------------
	SELECT 
			@BudgetConfigID AS BudgetConfigID,
			@EntityGroupConfigID AS EntityGroupConfigID,
			ca.EntityID,
			ca.DepartmentID,
			ca.AccountID,
			ca.OBDollarsFinancialReportingID,		
			vari.VariabilityID,
			4 AS APEModelSectionID,
			1 AS IsNew,
			GETDATE() AS AddDate
		INTO #insertTemp
		FROM #uniqueCADimensions ca
		INNER JOIN fw.DimDepartment dd on ca.DepartmentID = dd.DepartmentID
		LEFT JOIN fp.GeneralLedger gl
			ON gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityGroupConfigID
			AND ca.EntityID = gl.EntityID
			AND ca.DepartmentID = gl.DepartmentID
			AND ca.OBDollarsFinancialReportingID = gl.FinancialReportingID
			AND ca.AccountID = gl.AccountID
		INNER JOIN fp.EntityGroupConfig egc on egc.EntityGroupConfigID = @EntityGroupConfigID
		INNER JOIN fp.EntityGroupConfigMapping egcm on egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
		CROSS APPLY (VALUES (1),(2)) vari(VariabilityID) 
		WHERE 
			gl.GeneralLedgerID IS NULL
			AND dd.EntityID = egcm.EntityID

	IF(@IsDebug = 0)
	BEGIN
		--------------------------------------------------------------
		--Insert missing dimensionality into GL
		--------------------------------------------------------------
		INSERT INTO [fp].[GeneralLedger] 
		(
			BudgetConfigID, 
			EntityGroupConfigID, 
			EntityID, 
			DepartmentID, 
			AccountID, 
			FinancialReportingID, 
			VariabilityID, 
			APEModelSectionID, 
			IsNew, 
			AddDate
		)
		SELECT 
			@BudgetConfigID,
			@EntityGroupConfigID,
			EntityID,
			DepartmentID,
			AccountID,
			OBDollarsFinancialReportingID,		
			VariabilityID,
			APEModelSectionID,
			IsNew,
			AddDate
		FROM #insertTemp

		--------------------------------------------------------------
		-- Pad the budget/projection tables
		--------------------------------------------------------------
		EXEC [fp].[procPadGeneralLedger] @BudgetConfigID, @SourceDimensionality
	END ELSE
	BEGIN
		SELECT 
			@BudgetConfigID,
			@EntityGroupConfigID,
			EntityID,
			DepartmentID,
			AccountID,
			OBDollarsFinancialReportingID,		
			VariabilityID,
			APEModelSectionID,
			IsNew,
			AddDate
		FROM #insertTemp
	END
END
GO


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

-- fp.procPadServiceLineEncounter
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1	2023-02-13	BW		JAZZ-48306	Updated for new data model, use [fp].[ServiceLineEncounter]
*************************************************************/ 
CREATE   PROCEDURE [fp].[procPadServiceLineEncounter]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

    CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT)
	INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3
	
	CREATE TABLE #FilteredData (ServiceLineEncounterID INT PRIMARY KEY CLUSTERED)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT [fcv].[ServiceLineEncounterID]
		FROM [fp].[ServiceLineEncounter] fcv
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID
		WHERE fcv.BudgetConfigID = @BudgetConfigID
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT [fcv].[ServiceLineEncounterID]
		FROM [fp].[ServiceLineEncounter] fcv	
		WHERE fcv.BudgetConfigID = @BudgetConfigID
	END
    
	INSERT INTO [fp].[ServiceLineEncounterHistory]([ServiceLineEncounterID])
	SELECT [fcv].[ServiceLineEncounterID]
	FROM [fp].[ServiceLineEncounter] fcv
		INNER JOIN #FilteredData filter ON fcv.ServiceLineEncounterID = filter.ServiceLineEncounterID
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.ServiceLineEncounterHistory hist WITH (READUNCOMMITTED) WHERE fcv.ServiceLineEncounterID = hist.ServiceLineEncounterID)
END
GO


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

-- fp.procPadServiceLineToChargeVolumeDepartmentMapping
/************************************************************** 
** Change History  
************************************************************** 
** CID  Date        Author  WI   Description 
** 1    2022-09-19  BK      JAZZ-42503  Add ProviderID to targeting for Service Line Encounters
** 2    2023-01-31  NT      JAZZ-48268  Make change to use the new fp.ChargeVolume (data restructure)
*************************************************************/
CREATE PROCEDURE fp.procPadServiceLineToChargeVolumeDepartmentMapping
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
  
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
  	CREATE TABLE #FilterByDepartment (DepartmentID int)
  	INSERT INTO #FilterByDepartment (DepartmentID)
  	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
  	
 
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID FROM fp.ChargeVolume WHERE BudgetConfigID = @BudgetConfigID
	END
	
	
	INSERT INTO fp.ServiceLineEncounterChargeVolumeMapping (BudgetConfigID, EntityID, DepartmentID, ServiceLineID, ProviderID) 
	SELECT DISTINCT cv.BudgetConfigID, cv.ServiceEntityID, cv.DepartmentID, cv.ServiceLineID, cv.ServiceProviderID 
	FROM [fp].[ChargeVolume] cv INNER JOIN [fp].[ServiceLineEncounter] sle 
			ON cv.ServiceEntityID = sle.EntityID
			AND cv.BudgetConfigID = sle.BudgetConfigID
			AND cv.ServiceLineID = sle.ServiceLineID
			AND cv.ServiceProviderID = sle.ProviderID
		 INNER JOIN #FilterByDepartment SD on SD.DepartmentID = cv.DepartmentID 
	WHERE cv.BudgetConfigID = @BudgetConfigID
	AND NOT EXISTS (SELECT 1 FROM fp.ServiceLineEncounterChargeVolumeMapping map WHERE 
	cv.ServiceEntityID = map.EntityID
	AND cv.DepartmentID = map.DepartmentID
	AND cv.ServiceLineID = map.ServiceLineID
	AND cv.ServiceProviderID = map.ProviderID
	AND cv.BudgetConfigID = map.BudgetConfigID)
		
	
 
END
GO


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

-- fp.procPadStaffing
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2023-10-09  MY      JAZZ-61365		Upgrade to new structure
** 2	2023-10-23  MY      JAZZ-61397		Fix Targeting
*************************************************************/
CREATE   PROCEDURE [fp].[procPadStaffing]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
			
	CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT [fgl].[StaffingID]
		FROM [fp].[Staffing] fgl
			INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fgl.DepartmentID 	
		WHERE fgl.BudgetConfigID = @BudgetConfigID
	END 
	ELSE 
	BEGIN
		INSERT INTO #FilteredData
		SELECT [fgl].[StaffingID]
		FROM [fp].[Staffing] fgl	
		WHERE fgl.BudgetConfigID = @BudgetConfigID
	END
		
	INSERT INTO [fp].[StaffingHistory]([StaffingID])
	SELECT [fgl].[StaffingID]
	FROM [fp].[Staffing] fgl
		INNER JOIN #FilteredData filter ON fgl.StaffingID = filter.StaffingID
	WHERE BudgetConfigID = @BudgetConfigID
	AND NOT EXISTS 	
	(
		SELECT 1 FROM fp.StaffingHistory hist WITH (READUNCOMMITTED) 
		WHERE fgl.StaffingID = hist.StaffingID
	)

	INSERT INTO [fp].[StaffingWageRate] (StaffingWageRateID)   
	SELECT st.StaffingID 
	FROM fp.Staffing st
		INNER JOIN #FilteredData filter ON st.StaffingID = filter.StaffingID
	WHERE VariabilityID = 1
		AND st.StaffingWageRateID = 0

	UPDATE staff SET StaffingWageRateID = staff.StaffingID
	FROM fp.Staffing staff
		INNER JOIN #FilteredData filter ON staff.StaffingID = filter.StaffingID
	WHERE VariabilityID = 1
		AND staff.StaffingWageRateID = 0

	UPDATE varb SET varb.StaffingWageRateID = fixed.StaffingID 
	FROM fp.Staffing varb 
		INNER JOIN fp.Staffing fixed ON 
			  varb.DepartmentID = fixed.DepartmentID
		  AND varb.JobCodeID = fixed.JobCodeID
		  AND varb.PayCodeGroupID = fixed.PayCodeGroupID
		  AND varb.BudgetConfigID = fixed.BudgetConfigID
		  AND varb.EntityGroupConfigID = fixed.EntityGroupConfigID
		  AND varb.EntityID = fixed.EntityID
		  AND varb.ProductiveClassID = fixed.ProductiveClassID
		  AND varb.ProviderID = fixed.ProviderID
		  AND varb.ProviderLineItemID = fixed.ProviderLineItemID
		  AND varb.ProviderTypeID = fixed.ProviderTypeID
		  AND varb.ProviderSpecialtyID = fixed.ProviderSpecialtyID
		  AND varb.EmployeeID = fixed.EmployeeID
		INNER JOIN #FilteredData ft ON ft.StaffingID = fixed.StaffingID
	WHERE varb.VariabilityID = 2 
		AND fixed.VariabilityID = 1
		AND varb.StaffingWageRateID = 0
END
GO


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

-- fp.procPadStaffingToGlCrosswalk
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI   Description  
 ** 1    2018-09-25  GF      E-02313  Simplify source dimensionality to only department  
 ** 2    2021-05-05  BK      JAZZ-18217  Add Provider Compensation Dollars To GL Crosswalk  
 ** 3    2023-07-31  BK      JAZZ-58155  GL Data restructure
 ** 4    2023-10-23  Matt Hayden  JAZZ-62450 Update for Staffing table restructure
 ** 5    2024-01-31  NH      JAZZ-64064  Move Provider Planning FF as a setting in Plan Config
 *******************************************************/
CREATE procedure fp.procPadStaffingToGlCrosswalk
@EntityGroupConfigID INT,
@BudgetConfigID INT,
@SqlJoin NVARCHAR(MAX),
@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
@IsDebug BIT = 0
AS BEGIN

IF OBJECT_ID('tempdb..#Accts') IS NOT NULL DROP TABLE #Accts
IF OBJECT_ID('tempdb..#itemsToPad') IS NOT NULL DROP TABLE #itemsToPad
IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing
IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment

CREATE TABLE #FilterByDepartment (DepartmentID int)

INSERT INTO
    #FilterByDepartment (DepartmentID)
SELECT
    DepartmentID
FROM
    fp.funcGetSourceDimensionalityAsTable(@SourceDimensionality)
    
CREATE TABLE #tmpStaffing (
    DepartmentID INT,
    JobCodeID INT,
    PayCodeGroupID INT,
    EntityID INT,
    VariabilityID INT,
    EntityGroupConfigID INT,
    BudgetConfigID INT
)

CREATE TABLE #itemsToPad (
    DepartmentID INT,
    AccountID INT,
    OBDollarsFinancialReportingID INT,
    EntityID INT,
    VariabilityID INT,
    EntityGroupConfigID INT,
    BudgetConfigID INT
) 

IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN
    INSERT INTO
        #tmpStaffing (DepartmentID, JobCodeID, PayCodeGroupID, EntityID, VariabilityID, EntityGroupConfigID, BudgetConfigID)
    SELECT DISTINCT 
		staff.DepartmentID,
        staff.JobCodeID,
        staff.PayCodeGroupID,
        staff.EntityID,
        staff.VariabilityID,
        staff.EntityGroupConfigID,
        @BudgetConfigID AS BudgetConfigID
    FROM [fp].[Staffing] staff (readuncommitted)
        INNER JOIN #FilterByDepartment SD on SD.DepartmentID = staff.DepartmentID
    WHERE staff.EntityGroupConfigID = @EntityGroupConfigID
        AND staff.SubsectionID = 3
END
ELSE BEGIN
    INSERT INTO
        #tmpStaffing (DepartmentID, JobCodeID, PayCodeGroupID, EntityID, VariabilityID, EntityGroupConfigID, BudgetConfigID)
    SELECT DISTINCT 
		staff.DepartmentID,
        staff.JobCodeID,
        staff.PayCodeGroupID,
        staff.EntityID,
        staff.VariabilityID,
        staff.EntityGroupConfigID,
        @BudgetConfigID AS BudgetConfigID
    FROM [fp].[Staffing] staff (readuncommitted)
    WHERE staff.EntityGroupConfigID = @EntityGroupConfigID
        AND staff.SubsectionID = 3
END 

-- Load any rows that need to be crosswalked  
EXEC(
    '
    INSERT INTO #itemsToPad
    SELECT DISTINCT
        staff.DepartmentID,
        pax.AccountID,
        acc.OBDollarsFinancialReportingID,
        staff.EntityID,
        staff.VariabilityID,
        staff.EntityGroupConfigID,
        staff.BudgetConfigID
    FROM #tmpStaffing staff
        ' + @SqlJoin + ' 
        INNER JOIN [fw].[DimAccount] acc (readuncommitted) on pax.AccountID = acc.AccountID
    WHERE
        pax.UnitTypeID = 34
        AND staff.EntityGroupConfigID = ' + @EntityGroupConfigID
)

IF EXISTS (SELECT 1 FROM #itemsToPad) BEGIN
    -- For any rows not in the GeneralLedger, insert them in now.  
    INSERT INTO [fp].[GeneralLedger]
		(DepartmentID, AccountID, FinancialReportingID, EntityID, VariabilityID, BudgetConfigID, EntityGroupConfigID, APEModelSectionID, IsNew, AddDate)
    SELECT
        pbr.DepartmentID,
        pbr.AccountID,
        pbr.OBDollarsFinancialReportingID,
        pbr.EntityID,
        pbr.VariabilityID,
        pbr.BudgetConfigID,
        pbr.EntityGroupConfigID,
        6 AS APEModelSectionID,
        1 AS IsNew,
        GETDATE() AS AddDate
    FROM #itemsToPad pbr
        LEFT JOIN [fp].[GeneralLedger] abr (readuncommitted) ON pbr.DepartmentID = abr.DepartmentID
            AND pbr.AccountID = abr.AccountID
            AND pbr.EntityGroupConfigID = abr.EntityGroupConfigID
            AND pbr.VariabilityID = abr.VariabilityID
            AND pbr.EntityID = abr.EntityID
            AND pbr.OBDollarsFinancialReportingID = abr.FinancialReportingID
    WHERE abr.GeneralLedgerID IS NULL;
END

IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing

DECLARE @IsProviderPlanningEnabled BIT;
SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

IF @IsProviderPlanningEnabled = 1 BEGIN
    TRUNCATE TABLE #itemsToPad

    CREATE TABLE #Accts (
        AccountID INT,
        ProviderTypeID INT,
        ProviderLineItemID INT,
        OBDollarsFinancialReportingID INT
    )

    INSERT INTO
        #Accts (AccountID, ProviderTypeID, ProviderLineItemID, OBDollarsFinancialReportingID)
    SELECT DISTINCT psc.AccountID, 0, ProviderLineItemID, OBDollarsFinancialReportingID
    FROM fp.ProviderStaffingConfig psc
        INNER JOIN fw.DimAccount acct on psc.AccountID = acct.AccountID
    WHERE BudgetConfigID = @BudgetConfigID
        AND IsEditByProviderType = 0
        AND psc.AccountID > 0
    UNION
    SELECT DISTINCT t.AccountID, ProviderTypeID, ProviderLineItemID, OBDollarsFinancialReportingID
    FROM fp.ProviderStaffingConfigProviderType t
        INNER JOIN fp.ProviderStaffingConfig psc on t.ProviderStaffingConfigID = psc.ProviderStaffingConfigID
        INNER JOIN fw.DimAccount acct on t.AccountID = acct.AccountID
    WHERE BudgetConfigID = @BudgetConfigID
        AND IsEditByProviderType = 1
        
    IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN
        INSERT INTO
            #itemsToPad (DepartmentID, AccountID, OBDollarsFinancialReportingID, EntityID, VariabilityID, BudgetConfigID, EntityGroupConfigID)
        SELECT
            DISTINCT staff.DepartmentID,
            acct.AccountID,
            acct.OBDollarsFinancialReportingID,
            staff.EntityID,
            staff.VariabilityID,
            staff.BudgetConfigID,
            staff.EntityGroupConfigID
        FROM #Accts acct
            INNER JOIN fp.Staffing staff ON acct.ProviderLineItemID = staff.ProviderLineItemID
                AND acct.ProviderLineItemID = staff.ProviderLineItemID
            INNER JOIN #FilterByDepartment dept on staff.DepartmentID = dept.DepartmentID
        WHERE staff.EntityGroupConfigID = @EntityGroupConfigID
            AND staff.SubsectionID = 4
    END
    ELSE BEGIN
        INSERT INTO
            #itemsToPad (DepartmentID, AccountID, OBDollarsFinancialReportingID, EntityID, VariabilityID, BudgetConfigID, EntityGroupConfigID)
        SELECT DISTINCT
			staff.DepartmentID,
            acct.AccountID,
            acct.OBDollarsFinancialReportingID,
            staff.EntityID,
            staff.VariabilityID,
            staff.BudgetConfigID,
            staff.EntityGroupConfigID
        FROM #Accts acct
            INNER JOIN fp.Staffing staff ON acct.ProviderLineItemID = staff.ProviderLineItemID
                AND acct.ProviderLineItemID = staff.ProviderLineItemID
        WHERE staff.EntityGroupConfigID = @EntityGroupConfigID
            AND staff.SubsectionID = 4
    END

    INSERT INTO [fp].[GeneralLedger] (
		DepartmentID,
        AccountID,
        FinancialReportingID,
        EntityID,
        VariabilityID,
        BudgetConfigID,
        EntityGroupConfigID,
        APEModelSectionID,
        IsNew,
        AddDate)
    SELECT
        staff.DepartmentID,
        staff.AccountID,
        staff.OBDollarsFinancialReportingID,
        staff.EntityID,
        staff.VariabilityID,
        staff.BudgetConfigID,
        staff.EntityGroupConfigID,
        6 AS APEModelSectionID,
        1 AS IsNew,
        GETDATE() AS AddDate
    FROM
        #itemsToPad staff
        LEFT JOIN [fp].[GeneralLedger] gl (readuncommitted) ON staff.DepartmentID = gl.DepartmentID
			AND staff.AccountID = gl.AccountID
			AND staff.EntityGroupConfigID = gl.EntityGroupConfigID
			AND staff.VariabilityID = gl.VariabilityID
			AND staff.EntityID = gl.EntityID
			AND staff.OBDollarsFinancialReportingID = gl.FinancialReportingID
    WHERE gl.GeneralLedgerID IS NULL;

END
END
GO


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

-- fp.procPadStatistics
CREATE PROCEDURE [fp].[procPadStatistics]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
        
    CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT)
	INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3
	
	CREATE TABLE #FilteredData (StatisticsID INT PRIMARY KEY CLUSTERED)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT [fs].[StatisticsID]
		FROM [fp].[FactStatistics] fs
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fs.DepartmentID or ft.DepartmentID is null)	
		WHERE fs.BudgetConfigID = @BudgetConfigID
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT [fs].[StatisticsID]
		FROM [fp].[FactStatistics] fs	
		WHERE fs.BudgetConfigID = @BudgetConfigID
	END

	INSERT INTO [fp].[FactStatisticsBudget]([StatisticsID], [BudgetPhaseID])
	SELECT [fgl].[StatisticsID], psh.[BudgetPhaseID]
	FROM [fp].[FactStatistics] fgl
		INNER JOIN #FilteredData filter ON fgl.StatisticsID = filter.StatisticsID
		OUTER APPLY #BudgetPhase psh
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactStatisticsBudget bud WITH (READUNCOMMITTED) WHERE fgl.StatisticsID = bud.StatisticsID AND bud.BudgetPhaseID = psh.BudgetPhaseID)

	INSERT INTO [fp].[FactStatisticsProjection]([StatisticsID], [BudgetPhaseID])
	SELECT [fgl].[StatisticsID], psh.[BudgetPhaseID]
	FROM [fp].[FactStatistics] fgl
		INNER JOIN #FilteredData filter ON fgl.StatisticsID = filter.StatisticsID
		OUTER APPLY #BudgetPhase psh
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactStatisticsProjection proj WITH (READUNCOMMITTED) WHERE fgl.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = psh.BudgetPhaseID)

	INSERT INTO [fp].[FactStatisticsHistory]([StatisticsID])
	SELECT [fgl].[StatisticsID]
	FROM [fp].[FactStatistics] fgl
		INNER JOIN #FilteredData filter ON fgl.StatisticsID = filter.StatisticsID
	WHERE BudgetConfigID = @BudgetConfigID
		AND NOT EXISTS (SELECT 1 FROM fp.FactStatisticsHistory hist WITH (READUNCOMMITTED) WHERE fgl.StatisticsID = hist.StatisticsID)
END
GO


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

-- fp.procPatientActivityFlexingConfigPopulation
CREATE   PROCEDURE fp.procPatientActivityFlexingConfigPopulation
 @EntityGroupConfigGUID UNIQUEIDENTIFIER,
 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
 @IsGL bit = 1,
 @IsStaffing bit = 1
AS 	
BEGIN
	/*********************************************************************
	** Change History
	**********************************************************************
	** CID  Date        Author      WI				Description
	** 1    2021-09-24  MD          JAZZ-25923     Add Patient Activity Flex data to fp.FlexConfigMapping table
	** 2    2021-11-22  NT          JAZZ-28343     Pass in boolean to determine whether populating patient activity mapping for staffing or GL section
	** 3 	2023-08-09  BW			JAZZ-58199	   Data model restructure for GL
	** 4 	2023-11-08  MD			JAZZ-62448	   Data model restructure for Staffing
	*********************************************************************/
	DECLARE @BudgetConfigID INT,
			@EntityGroupConfigID INT,
			@PAFlexMethod INT,
			@FlexTypeID INT
			
	SELECT @BudgetConfigID = bc.BudgetConfigID, @EntityGroupConfigID = egc.EntityGroupConfigID 
			FROM [fp].[EntityGroupConfig] egc
			INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
			WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID

	SET @PAFlexMethod = 2;
	SET @FlexTypeID = 7;		
	
	EXEC [dbo].[procSysDropTempTable] '#flexMap'
	EXEC [dbo].[procSysDropTempTable] '#filteringTable'		

	CREATE TABLE #flexMap (
                    DepartmentID int NOT NULL,
                    GLAccountID int NOT NULL,
					PRJobCodeID int NOT NULL
                );
 	
	CREATE TABLE #filteringTable (
		DepartmentID INT
		,INDEX ix_1 NONCLUSTERED (DepartmentID)
		)

	INSERT INTO #filteringTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)	

	-- If the #FilteringTable is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #filteringTable WHERE DepartmentID IS NOT NULL)
	BEGIN
		;WITH Departments AS (
			SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID
			UNION ALL
			SELECT DISTINCT DepartmentID FROM fp.GeneralLedger WHERE EntityGroupConfigID = @EntityGroupConfigID
		)
		INSERT INTO #filteringTable (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM Departments
	END	

	-----------------------------------------------------------------
	--Do staffing flex config map
	IF (@IsStaffing = 1) 
	BEGIN
		INSERT INTO #flexMap(DepartmentID, PRJobCodeID, GLAccountID)
			SELECT DISTINCT fs.DepartmentID, fs.JobCodeID, 0
			FROM fp.Staffing fs
				JOIN #filteringTable ft ON fs.DepartmentID = ft.DepartmentID
				JOIN [fp].[viewStaffingExpenseFlexingConfig] fc 
					ON fc.EntityGroupConfigGUID = @EntityGroupConfigGUID
					AND ft.DepartmentID = fc.DepartmentID
					AND fs.JobCodeID = fc.JobCodeID
			WHERE 1=1
				AND fs.BudgetConfigID = @BudgetConfigID
				AND fs.EntityGroupConfigID = @EntityGroupConfigID
				AND fs.VariabilityID = 2 
				AND fc.FlexMethodID = @PAFlexMethod
	END

	IF (@IsGL = 1)
	BEGIN
		--Do non staffing flex config map
		INSERT INTO #flexMap(DepartmentID, GLAccountID, PRJobCodeID)
			SELECT DISTINCT gl.DepartmentID, gl.AccountID, 0
			FROM fp.GeneralLedger gl
				JOIN #filteringTable ft ON gl.DepartmentID = ft.DepartmentID
				JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc 
					ON fc.EntityGroupConfigGUID = @EntityGroupConfigGUID
					AND ft.DepartmentID = fc.DepartmentID
					AND gl.AccountID = fc.AccountID
			WHERE 1=1
				AND gl.BudgetConfigID = @BudgetConfigID
				AND gl.EntityGroupConfigID = @EntityGroupConfigID
				AND gl.VariabilityID = 2 
				AND fc.FlexMethodID = @PAFlexMethod
	END

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

	;WITH TRG AS 
 	(SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.PRJobCodeID,fcm.FlexingTypeID FROM [fp].[FlexConfigMapping] fcm
		INNER JOIN #filteringTable ft on ft.DepartmentID = fcm.DepartmentID   
	WHERE EntityGroupConfigID = @EntityGroupConfigID 
	  AND FlexingTypeID = @FlexTypeID
	  AND ((@IsGL = 1 AND PRJobCodeID = 0) OR 
	       (@IsStaffing = 1 AND GLAccountID = 0))
    )
 
	MERGE TRG
	USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID,
				DepartmentID,
				GLAccountID,
				PRJobCodeID,
				@FlexTypeID AS FlexingTypeID
		FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID and TRG.GLAccountID = SRC.GLAccountID and TRG.PRJobCodeID = SRC.PRJobcodeID
	WHEN NOT MATCHED BY TARGET THEN
	INSERT VALUES (src.EntityGroupConfigID,src.DepartmentID,src.GLAccountID,src.PRJobCodeID,src.FlexingTypeID) 
	WHEN NOT MATCHED BY SOURCE THEN DELETE;
END
GO


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

-- fp.procPopulateAccountVariability
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2021-03-23  NN      JAZZ-14117	Remove null joins and joins on targting object
** 2    2021-07-01  MD      JAZZ-13102	Use original department when populating variability
** 3	   5-9-2023  NT       JAZZ-54290	Data restructure changes to use new fp.GeneralLedger table
*************************************************************/

CREATE   PROCEDURE [fp].[procPopulateAccountVariability]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@EntityGroupConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
AS
BEGIN

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.GeneralLedger gl WITH (READUNCOMMITTED)	
		where gl.EntityGroupConfigID = @EntityGroupConfigID
	END
	
	DELETE av FROM [fp].[FactAccountVariability] av
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = av.DepartmentID
	WHERE av.EntityGroupConfigGUID = @EntityGroupConfigGUID 


    -- Patient Activity
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT 
        fp.EntityGroupConfigGUID,
        fp.DepartmentID, 
        fp.AccountID, 
        CASE WHEN fp.TotalCost = 0 THEN 0 
            WHEN (fp.TotalFixedDirectCost / fp.TotalCost) > .9999 THEN 1.0 
            ELSE (fp.TotalFixedDirectCost / fp.TotalCost) END AS [FixedPercentage] 
    FROM
        (SELECT
            ec.EntityGroupConfigGUID,
            base.OriginalDepartmentID as DepartmentID, --use original department for fp tables, not reclassed department
            OriginalAccountID as AccountID,
            efc.FlexMethodID,
            SUM(base.FixedDirectUnitCost * base.Volume) as TotalFixedDirectCost,
            SUM(base.TotalCost) as TotalCost
         FROM
            [dss].[FactCostingOutDetailGL] base
            INNER JOIN [dss].[CostingResult] cr on base.CostingResultID = cr.CostingResultID
            INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID
			INNER JOIN #FilterByDepartment ff on ff.DepartmentID = base.OriginalDepartmentID   -- make sure we are filtering on the Original Department
            INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] efc 
                ON ec.EntityGroupConfigGUID = efc.EntityGroupConfigGUID 
                AND base.OriginalDepartmentID  = efc.DepartmentID
                AND base.OriginalAccountID = efc.AccountID
         WHERE
            base.CostingResultID IN (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0)
            AND base.TimeClassID = ec.CostingConfigTimeClassID
            AND ec.EntityGroupConfigGuid = @EntityGroupConfigGuid
            AND efc.FlexMethodID = 2 -- patient activity
         GROUP BY
            ec.EntityGroupConfigGUID, 
            base.OriginalAccountID, 
            base.OriginalDepartmentID, --group by same Original Department as we are using to insert data into fp tables
            base.FiscalYearID, 
            efc.FlexMethodID 
	     ) fp
    WHERE 
        fp.EntityGroupConfigGUID = @EntityGroupConfigGuid
        AND NOT(CASE WHEN fp.TotalCost = 0 THEN 0 ELSE fp.TotalFixedDirectCost / fp.TotalCost END > .9999) -- Filter out fixed records


    -- Stat Accounts
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT 
        fc.EntityGroupConfigGUID,
        fc.DepartmentID,
        vc.AccountID,
        1 - vc.Variability AS [FixedPercentage]
    FROM [fp].[NonStaffingVariabilityConfig] vc
        INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc 
            ON vc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID
            AND vc.AccountID = fc.AccountID
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID
    WHERE
        vc.EntityGroupConfigGUID = @EntityGroupConfigGuid
        AND fc.FlexMethodID in (1) -- StatisticAccounts 
        AND vc.Variability > 0 -- Filter out fixed records

    -- Revenue accounts (revenue accounts are 100% variable unless marked as fixed)
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT
        fc.EntityGroupConfigGUID,
        fc.DepartmentID,
        fc.AccountID,
        0 AS [FixedPercentage]
    FROM [fp].[viewRevenueExpenseFlexingConfig] fc
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID
    WHERE fc.EntityGroupConfigGUID = @EntityGroupConfigGuid
    	AND fc.FlexMethodID != 6 -- Filter out fixed records			  

    -- Variable deductions accounts (deductions are 100% variable unless marked as fixed)
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT
        fc.EntityGroupConfigGUID,
        fc.DepartmentID,
        fc.AccountID,
        0 AS [FixedPercentage]
    FROM [fp].[viewDeductionsFlexingConfig] fc
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID
    WHERE fc.EntityGroupConfigGUID = @EntityGroupConfigGuid
    	AND fc.FlexMethodID != 6 -- Filter out fixed records
 		
	-- Benefits accounts (benefit accounts are 100% variable)
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT DISTINCT
        @EntityGroupConfigGuid,
        gl.DepartmentID,
        gl.AccountID,
        0 AS [FixedPercentage]
    FROM [fp].[GeneralLedger] gl
		 INNER JOIN [fp].[viewBenefitsAccounts] ba ON gl.AccountID = ba.AccountID
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = gl.DepartmentID
    WHERE gl.EntityGroupConfigID = @EntityGroupConfigID
		
END
GO


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

-- fp.procPopulateAccountVariabilityByBudgetConfig
CREATE PROC fp.procPopulateAccountVariabilityByBudgetConfig
	@BudgetConfigID INT
AS
BEGIN
	DECLARE @EntityGroupConfigGuid UNIQUEIDENTIFIER
	DECLARE @EntityGroupConfigId INT

	DECLARE entityGroupConfigCrs CURSOR FOR
	SELECT 
		EntityGroupConfigGUID,
		EntityGroupConfigID
	FROM [fp].[EntityGroupConfig] egc
		INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigId;

	OPEN entityGroupConfigCrs

	FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId

	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC [fp].[procPopulateAccountVariability] @EntityGroupConfigGUID = @EntityGroupConfigGuid, @EntityGroupConfigID = @EntityGroupConfigId
		
		FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId 
	END

	CLOSE entityGroupConfigCrs;
	DEALLOCATE entityGroupConfigCrs;
END
GO


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

-- fp.procPopulateAccountVariability_InitialPlan
CREATE PROCEDURE [fp].[procPopulateAccountVariability_InitialPlan]
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@BudgetConfigID SMALLINT,
	@EntityGroupConfigIDs VARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
AS
BEGIN
/**************************************************************
    ** Change History
    **************************************************************
    ** CID  Date        Author  WI              Description
		1	2024-05-27	MV		JAZZ-71177		Create SP for Initial plan method baseed on [fp].[procPopulateAccountVariability]
    *************************************************************/
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL  DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#FilterByEntityGroupConfig') IS NOT NULL  DROP TABLE #FilterByEntityGroupConfig

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #FilterByEntityGroupConfig (EntityGroupConfigID int, EntityGroupConfigGUID uniqueidentifier)

	IF @EntityGroupConfigIDs IS NOT NULL AND @EntityGroupConfigIDs <> ''
	BEGIN		
		INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID, EntityGroupConfigGUID)
		SELECT EntityGroupConfigID, EntityGroupConfigGUID FROM [fp].[EntityGroupConfig]
		WHERE BudgetConfigGUID = @BudgetConfigGUID
		AND EntityGroupConfigID IN (SELECT TRIM([value]) AS EntityGroupConfigID FROM STRING_SPLIT(@EntityGroupConfigIDs, ',' ))
	END
	ELSE BEGIN
		INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID, EntityGroupConfigGUID)
		SELECT EntityGroupConfigID, EntityGroupConfigGUID FROM [fp].[EntityGroupConfig]
		WHERE BudgetConfigGUID = @BudgetConfigGUID
	END

	

	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.GeneralLedger gl WITH (READUNCOMMITTED)
		INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = gl.EntityGroupConfigID
		WHERE gl.BudgetConfigID = @BudgetConfigID
	END
	
	DELETE av FROM [fp].[FactAccountVariability] av
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = av.DepartmentID		
		INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = av.EntityGroupConfigGUID


    -- Patient Activity
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT 
        fp.EntityGroupConfigGUID,
        fp.DepartmentID, 
        fp.AccountID, 
        CASE WHEN fp.TotalCost = 0 THEN 0 
            WHEN (fp.TotalFixedDirectCost / fp.TotalCost) > .9999 THEN 1.0 
            ELSE (fp.TotalFixedDirectCost / fp.TotalCost) END AS [FixedPercentage] 
    FROM
        (SELECT
            ec.EntityGroupConfigGUID,
            base.OriginalDepartmentID as DepartmentID, --use original department for fp tables, not reclassed department
            OriginalAccountID as AccountID,
            efc.FlexMethodID,
            SUM(base.FixedDirectUnitCost * base.Volume) as TotalFixedDirectCost,
            SUM(base.TotalCost) as TotalCost
         FROM
            [dss].[FactCostingOutDetailGL] base
            INNER JOIN [dss].[CostingResult] cr on base.CostingResultID = cr.CostingResultID
            INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID
			INNER JOIN #FilterByDepartment ff on ff.DepartmentID = base.OriginalDepartmentID   -- make sure we are filtering on the Original Department
            INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] efc 
                ON ec.EntityGroupConfigGUID = efc.EntityGroupConfigGUID 
                AND base.OriginalDepartmentID  = efc.DepartmentID
                AND base.OriginalAccountID = efc.AccountID
			INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = ec.EntityGroupConfigGUID
         WHERE
            base.CostingResultID IN (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0)
            AND base.TimeClassID = ec.CostingConfigTimeClassID
            AND efc.FlexMethodID = 2 -- patient activity
         GROUP BY
            ec.EntityGroupConfigGUID, 
            base.OriginalAccountID, 
            base.OriginalDepartmentID, --group by same Original Department as we are using to insert data into fp tables
            base.FiscalYearID, 
            efc.FlexMethodID 
	     ) fp
    WHERE 
        NOT(CASE WHEN fp.TotalCost = 0 THEN 0 ELSE fp.TotalFixedDirectCost / fp.TotalCost END > .9999) -- Filter out fixed records


    -- Stat Accounts
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT 
        fc.EntityGroupConfigGUID,
        fc.DepartmentID,
        vc.AccountID,
        1 - vc.Variability AS [FixedPercentage]
    FROM [fp].[NonStaffingVariabilityConfig] vc
        INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc 
            ON vc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID
            AND vc.AccountID = fc.AccountID
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID
		INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = vc.EntityGroupConfigGUID
    WHERE
        fc.FlexMethodID in (1) -- StatisticAccounts 
        AND vc.Variability > 0 -- Filter out fixed records

    -- Revenue accounts (revenue accounts are 100% variable unless marked as fixed)
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT
        fc.EntityGroupConfigGUID,
        fc.DepartmentID,
        fc.AccountID,
        0 AS [FixedPercentage]
    FROM [fp].[viewRevenueExpenseFlexingConfig] fc
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID
		INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID
    WHERE
    	fc.FlexMethodID != 6 -- Filter out fixed records			  

    -- Variable deductions accounts (deductions are 100% variable unless marked as fixed)
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT
        fc.EntityGroupConfigGUID,
        fc.DepartmentID,
        fc.AccountID,
        0 AS [FixedPercentage]
    FROM [fp].[viewDeductionsFlexingConfig] fc
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID
		INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID
    WHERE
    	fc.FlexMethodID != 6 -- Filter out fixed records
 		
	-- Benefits accounts (benefit accounts are 100% variable)
    INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage)
    SELECT DISTINCT
		fegc.EntityGroupConfigGuid,
        gl.DepartmentID,
        gl.AccountID,
        0 AS [FixedPercentage]
    FROM [fp].[GeneralLedger] gl
		INNER JOIN [fp].[viewBenefitsAccounts] ba ON gl.AccountID = ba.AccountID
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = gl.DepartmentID
		INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigID = gl.EntityGroupConfigID
    WHERE gl.BudgetConfigID = @BudgetConfigID
		
END
GO


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

-- fp.procPopulateBudgetConfigSettings
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2020-05-24  MY          JAZZ-20113      Initial
*********************************************************************/
CREATE   PROCEDURE [fp].[procPopulateBudgetConfigSettings]
	@BudgetConfigID INT = 0
AS
BEGIN
	
	INSERT INTO fp.BudgetConfigSetting (BudgetConfigID, SettingID, Value)
	SELECT 
		bc.BudgetConfigID,
		s.SettingID,
		DefaultValue AS Value
	FROM [fp].[BudgetConfigDefaultSetting] s
		CROSS APPLY (SELECT DISTINCT BudgetConfigID FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID OR @BudgetConfigID = 0) bc
		LEFT JOIN [fp].[BudgetConfigSetting] bcs ON bc.BudgetConfigID = bcs.BudgetConfigID AND bcs.SettingID = s.SettingID
	WHERE bcs.BudgetConfigID IS NULL

END
GO


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

-- fp.procPopulateChargeVolumeToStatCrosswalk
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	5-18-2023  MY      JAZZ-55153		Updated view to restructure
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateChargeVolumeToStatCrosswalk]
	@EntityGroupConfigID int
AS
BEGIN
	DECLARE @IsRecordsInChargeVolume INT
	SELECT @IsRecordsInChargeVolume  = COUNT(*) FROM [fp].[ChargeVolume] WHERE EntityGroupConfigID = @EntityGroupConfigID
	IF @IsRecordsInChargeVolume = 0
		SELECT @IsRecordsInChargeVolume;
	ELSE
		INSERT INTO [fp].[ChargeToStatisticsCrosswalkConfiguration]
			(EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, RVUWeight)
		
		SELECT DISTINCT 
			fcv.EntityGroupConfigID, 
			fcv.DepartmentID, 
			fcv.ChargeCodeID, 
			fcv.PatientClassID,
			dcc.RVUWeight
		FROM [fp].[ChargeVolume] fcv
		INNER JOIN [fw].[DimChargeCode] dcc
		ON fcv.ChargeCodeID = dcc.ChargeCodeID
		WHERE fcv.EntityGroupConfigID = @EntityGroupConfigID
		EXCEPT 
		SELECT 
			fcv.EntityGroupConfigID, 
			fcv.DepartmentID, 
			fcv.ChargeCodeID, 
			fcv.PatientClassID,
			dcc.RVUWeight
		FROM [fp].[ChargeVolume] fcv
		INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] crosswalk
		ON fcv.EntityGroupConfigID = crosswalk.EntityGroupConfigID
			AND fcv.DepartmentID = crosswalk.DepartmentID
			AND fcv.ChargeCodeID = crosswalk.ChargeCodeID
			AND fcv.PatientClassID = crosswalk.PatientClassID
		INNER JOIN [fw].[DimChargeCode] dcc
		ON fcv.ChargeCodeID = dcc.ChargeCodeID
		WHERE fcv.EntityGroupConfigID = @EntityGroupConfigID;

		SELECT @IsRecordsInChargeVolume;
END
GO


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

-- fp.procPopulateDepartmentConfig
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2018-09-25  GF      E-02313		Simplify source dimensionality to only department
** 2    2020-12-11  BW      JAZZ-8104	Departments with Expenses-Zero Based accounts to get populated in Department config
** 3    2021-02-16  NN      JAZZ-467	Remove null joins and joins on targting object
** 4    2023-06-01  MY      JAZZ-54655	Update to new GL Structure
** 5	01-03-2023  MY      JAZZ-63564	Final Pass Of Fact References (SQL)
** 6	2024-05-21  MY      JAZZ-72116	Fix Duplicate Key Issue with Unnecessary Join to Mapping Table
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateDepartmentConfig]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE
AS
BEGIN

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED)	
	END	
 
	CREATE TABLE #DepartmentConfigData (
		EntityGroupConfigGUID UNIQUEIDENTIFIER,
		DepartmentID INT,
		SectionName NVARCHAR(MAX),
		SectionValue INT
	);
 
	INSERT INTO #DepartmentConfigData (EntityGroupConfigGUID, DepartmentID, SectionName, SectionValue)
		SELECT * 
		FROM (
			SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasStatistics' AS SectionName, 1 AS SectionValue
		    FROM [fp].[FactStatistics] basis
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
			    INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID
			    INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
		    WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		        AND basis.BudgetConfigID = @BudgetConfigID
 
		    UNION
 
		    SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasRevenueAndDeductions' AS SectionName, 1 AS SectionValue
		    FROM [fp].[GeneralLedger] basis
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
			    INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID
			    INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
			    INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID
			    INNER JOIN [ob].[DimAccountPH] ph ON acc.OBAccountPHID = ph.AccountPHID
		    WHERE ph.Name IN ('Deductions', 'Deductions - Charity and Bad Debt', 'Deductions - Reimbursement', 'Gross Charges - Clinic', 'Gross Charges - ED', 'Gross Charges - Inpatient', 'Gross Charges - Observation', 'Gross Charges - Other', 'Gross Charges - Outpatient')
		    AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		        AND basis.BudgetConfigID = @BudgetConfigID
 
		    UNION
 
		    SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasOtherRevenue' AS SectionName, 1 AS SectionValue
		    FROM [fp].[GeneralLedger] basis
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
			    INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID
			    INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID
			    INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
		    WHERE acc.OBModelSectionName IN ('Other Revenue', 'Other Revenue - Zero Based')
		    AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		        AND basis.BudgetConfigID = @BudgetConfigID
 
		    UNION
 
		    SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasStaffing' AS SectionName, 1 AS SectionValue
		    FROM [fp].[Staffing] basis
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
			    INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID
			    INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
		    WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		        AND basis.BudgetConfigID = @BudgetConfigID
 
		    UNION
 
		    SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasBenefits' AS SectionName, 1 AS SectionValue
		    FROM fp.FactBenefits basis
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
			    INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID
			    INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
		    WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		        AND basis.BudgetConfigID = @BudgetConfigID
 
		    UNION
 
		    SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasNonStaffingExpenses' AS SectionName, 1 AS SectionValue 
		    FROM [fp].[GeneralLedger] basis
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
			    INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID
			    INNER JOIN [ob].[DimAccountPH] ph ON acc.OBAccountPHID = ph.AccountPHID
			    INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID
			    INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
		    WHERE ph.Name IN ('Expenses - Non-Staffing') AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		        AND basis.BudgetConfigID = @BudgetConfigID 


		    UNION
 
		    SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasZeroBasedExpenses' AS SectionName, 1 AS SectionValue 
		    FROM [fp].[GeneralLedger] basis
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID
			    INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID
			    INNER JOIN [ob].[DimAccountPH] ph ON acc.OBAccountPHID = ph.AccountPHID
			    INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID
			    INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID
		    WHERE ph.Name IN ('Expenses - Zero Based') AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		        AND basis.BudgetConfigID = @BudgetConfigID 

		) data
 
	;WITH TargetData AS (
 
	    select config.*
		from [fp].[DepartmentConfig] config
		where config.EntityGroupConfigGUID = @EntityGroupConfigGUID
 
	)
 
	MERGE TargetData targetConfig
	USING (
	        SELECT pvt.DepartmentID ,
	               pvt.EntityGroupConfigGUID ,
	               CAST(ISNULL(pvt.HasStatistics , 0) AS BIT) AS HasStatistics ,
	               CAST(ISNULL(pvt.HasRevenueAndDeductions , 0) AS BIT) AS HasRevenueAndDeductions ,
	               CAST(ISNULL(pvt.HasOtherRevenue , 0) AS BIT) AS HasOtherRevenue ,
	               CAST(ISNULL(pvt.HasRoster , 0) AS BIT) AS HasRoster ,
	               CAST(ISNULL(pvt.HasStaffing , 0) AS BIT) AS HasStaffing ,
	               CAST(ISNULL(pvt.HasBenefits , 0) AS BIT)  AS HasBenefits ,
	               CAST(ISNULL(pvt.HasNonStaffingExpenses , 0) AS BIT) AS HasNonStaffingExpenses,
	               CAST(ISNULL(pvt.HasZeroBasedExpenses , 0) AS BIT) AS HasZeroBasedExpenses
 
	        FROM 
	        (
	            SELECT d.EntityGroupConfigGUID ,
	                   d.DepartmentID ,
	                   d.SectionName ,
	                   d.SectionValue
	            FROM #DepartmentConfigData d
	            WHERE d.DepartmentID <> 0
	        ) src
	        PIVOT
	        (
	            SUM(SectionValue)
	            FOR SectionName IN (HasStatistics, HasRevenueAndDeductions, HasOtherRevenue, HasRoster, HasStaffing, HasBenefits, HasNonStaffingExpenses, HasZeroBasedExpenses)
	        ) pvt
	    ) AS sourceConfig ON sourceConfig.EntityGroupConfigGUID = targetConfig.EntityGroupConfigGUID AND sourceConfig.DepartmentID = targetConfig.DepartmentID
	WHEN MATCHED THEN
	    UPDATE SET targetConfig.HasStatistics = sourceConfig.HasStatistics , 
	               targetConfig.HasRevenueAndDeductions = sourceConfig.HasRevenueAndDeductions ,
	               targetConfig.HasOtherRevenue = sourceConfig.HasOtherRevenue ,
	               targetConfig.HasRoster = sourceConfig.HasRoster ,
	               targetConfig.HasStaffing = sourceConfig.HasStaffing ,
	               targetConfig.HasBenefits = sourceConfig.HasBenefits ,
	               targetConfig.HasNonStaffingExpenses = sourceConfig.HasNonStaffingExpenses,
	               targetConfig.HasZeroBasedExpenses = sourceConfig.HasZeroBasedExpenses

	WHEN NOT MATCHED BY TARGET THEN
	    INSERT (DepartmentID, EntityGroupConfigGUID, HasStatistics, HasRevenueAndDeductions, HasOtherRevenue, HasRoster, HasStaffing, HasBenefits, HasNonStaffingExpenses, HasZeroBasedExpenses)
	    VALUES (sourceConfig.DepartmentID, sourceConfig.EntityGroupConfigGUID, sourceConfig.HasStatistics, sourceConfig.HasRevenueAndDeductions, 
	            sourceConfig.HasOtherRevenue, sourceConfig.HasRoster, sourceConfig.HasStaffing, sourceConfig.HasBenefits, sourceConfig.HasNonStaffingExpenses, HasZeroBasedExpenses)
				
	-- We only want to do the delete when the data is not being targeted, otherwise it'll wipe out everything else and that would be bad.
	WHEN NOT MATCHED BY SOURCE AND ((SELECT COUNT(*) FROM #FilterByDepartment) = 0) THEN
	    DELETE
	OUTPUT $action AS ActionType, ISNULL(Deleted.DepartmentID, Inserted.DepartmentID) AS DepartmentID;
 
END
GO


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

-- fp.procPopulateFactBenefitsChangeHistoryGrouping
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-26-07  MY      JAZZ-39273		Added Option Recomiple to SELECTs
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateFactBenefitsChangeHistoryGrouping]
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	
	SET NOCOUNT ON;	
	
	CREATE TABLE #dimensionality (
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		FinancialReportingID INT, 
		ChangeHistoryGroupingGUID UNIQUEIDENTIFIER
	);
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS (SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, ChangeHistoryGroupingGUID)
		SELECT DISTINCT EntityID, fs.DepartmentID, AccountID, FinancialReportingID, NEWID() AS ChangeHistoryGroupingGUID
		FROM [fp].[FactBenefits] fs 
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fs.DepartmentID
		WHERE BudgetConfigID = @BudgetConfigID
			AND UnitTypeID = 34
		OPTION(RECOMPILE)
	END ELSE BEGIN
		INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, ChangeHistoryGroupingGUID)
		SELECT DISTINCT EntityID, DepartmentID, AccountID, FinancialReportingID, NEWID() AS ChangeHistoryGroupingGUID
		FROM [fp].[FactBenefits] fs 
		WHERE BudgetConfigID = @BudgetConfigID
			AND UnitTypeID = 34	
		OPTION(RECOMPILE)
	END

	UPDATE fs
	SET fs.ChangeHistoryGroupingGUID = dim.ChangeHistoryGroupingGUID
	FROM [fp].[FactBenefits] fs
		INNER JOIN #dimensionality dim ON 
			fs.EntityID = dim.EntityID
			AND fs.DepartmentID = dim.DepartmentID
			AND fs.AccountID = dim.AccountID
			AND fs.FinancialReportingID = dim.FinancialReportingID
	WHERE fs.BudgetConfigID = @BudgetConfigID
	AND fs.ChangeHistoryGroupingGUID = '00000000-0000-0000-0000-000000000000'
	
END
GO


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

-- fp.procPopulateFactGeneralLedgerChangeHistoryGrouping
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-26-07  MY      JAZZ-39273		Added Option Recomiple to SELECTs
** 2	5-10-2023   NT      JAZZ-54290		Data restructure changes to use new fp.GeneralLedger table
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateFactGeneralLedgerChangeHistoryGrouping]
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	
	SET NOCOUNT ON;	
		
	CREATE TABLE #dimensionality (
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		FinancialReportingID INT, 
		VariabilityID INT, 
		ChangeHistoryGroupingGUID UNIQUEIDENTIFIER
	);
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS (SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, ChangeHistoryGroupingGUID)
		SELECT DISTINCT EntityID, fs.DepartmentID, AccountID, FinancialReportingID, VariabilityID, NEWID() AS ChangeHistoryGroupingGUID
		FROM [fp].[GeneralLedger] fs 
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fs.DepartmentID
		WHERE BudgetConfigID = @BudgetConfigID
		  AND VariabilityID = 2
		OPTION(RECOMPILE)
	END ELSE BEGIN
		INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, ChangeHistoryGroupingGUID)
		SELECT DISTINCT EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, NEWID() AS ChangeHistoryGroupingGUID
		FROM [fp].[GeneralLedger] fs 
		WHERE BudgetConfigID = @BudgetConfigID
	  	  AND VariabilityID = 2
		OPTION(RECOMPILE)
	END

	UPDATE fs
	SET fs.ChangeHistoryGroupingGUID = dim.ChangeHistoryGroupingGUID
	FROM [fp].[GeneralLedger] fs
	INNER JOIN #dimensionality dim ON 
	    fs.EntityID = dim.EntityID
	AND fs.DepartmentID = dim.DepartmentID
	AND fs.AccountID = dim.AccountID
	AND fs.FinancialReportingID = dim.FinancialReportingID
	AND fs.VariabilityID = dim.VariabilityID
	WHERE fs.BudgetConfigID = @BudgetConfigID
	  AND fs.ChangeHistoryGroupingGUID = '00000000-0000-0000-0000-000000000000'
	  AND fs.VariabilityID = 2 -- We only need to use this for variable records, fixed doesn't use it
	
END
GO


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

-- fp.procPopulateFactStaffingChangeHistoryGrouping
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-26-07   MY      JAZZ-39273		Added Option Recomiple to SELECTs
** 2	2023-09-20   BK      JAZZ-60973		Update for new data structure
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateFactStaffingChangeHistoryGrouping]
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	
	SET NOCOUNT ON;	
	
	CREATE TABLE #dimensionality (
		EntityID INT, 
		DepartmentID INT, 
		JobCodeID INT, 
		PayCodeGroupID INT, 
		ProductiveClassID INT, 
		VariabilityID INT, 
		EmployeeID INT, 
		ChangeHistoryGroupingGUID UNIQUEIDENTIFIER
	);
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS (SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #dimensionality(EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ChangeHistoryGroupingGUID)
		SELECT DISTINCT EntityID, fs.DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, NEWID() AS ChangeHistoryGroupingGUID
		FROM [fp].[Staffing] fs 
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fs.DepartmentID
		WHERE BudgetConfigID = @BudgetConfigID
		OPTION(RECOMPILE)
	END ELSE BEGIN
		INSERT INTO #dimensionality(EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ChangeHistoryGroupingGUID)
		SELECT DISTINCT EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, NEWID() AS ChangeHistoryGroupingGUID
		FROM [fp].[Staffing] fs 
		WHERE BudgetConfigID = @BudgetConfigID
		OPTION(RECOMPILE)
	END

	UPDATE fs
	SET fs.ChangeHistoryGroupingGUID = dim.ChangeHistoryGroupingGUID
	FROM [fp].[Staffing] fs
		INNER JOIN #dimensionality dim ON 
			fs.EntityID = dim.EntityID
			AND fs.DepartmentID = dim.DepartmentID
			AND fs.JobCodeID = dim.JobCodeID
			AND fs.PayCodeGroupID = dim.PayCodeGroupID
			AND fs.ProductiveClassID = dim.ProductiveClassID
			AND fs.EmployeeID = dim.EmployeeID
	WHERE fs.BudgetConfigID = @BudgetConfigID
		AND fs.ChangeHistoryGroupingGUID = '00000000-0000-0000-0000-000000000000'
		AND fs.VariabilityID = 2 -- We only need to use this for variable records, fixed doesn't use it
	
END
GO


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

-- fp.procPopulateFactStaffingVariability_PayCodeGroup
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2022-04-29  MY	     JAZZ-28395  Cache Variability Percentage on FactStaffing
** 2    2022-08-16  MY      JAZZ-40590	Exclude Dollars Only from Variability
** 3    2022-09-20  MY      JAZZ-42870	Reset Data before applying variability
** 4    2022-10-12  NST     JAZZ-35951  Always set Varaiability to 1 for new employees addded from Add Wizard
** 5    2022-11-10  MY      JAZZ-35951  Fix issue for Employeee where it's getting set by the job code
** 6    2023-09-20  BK      JAZZ-60973  Update for new data structure
** 7    2024-01-30  BK      JAZZ-63880  Update JobCodeID and PayCodeID from smallint to int
** 8    2024-01-31  NH      JAZZ-64064  Move Provider Planning FF as a setting in Plan Config
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateFactStaffingVariability_PayCodeGroup]
	 @EntityGroupConfigGUID UNIQUEIDENTIFIER,
	 @EntityGroupConfigID INT,
	 @FiscalYearID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
 AS
 BEGIN

	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#staffingDim') IS NOT NULL DROP TABLE #staffingDim
	IF OBJECT_ID('tempdb..#variability') IS NOT NULL DROP TABLE #variability
	IF OBJECT_ID('tempdb..#providerVariability') IS NOT NULL DROP TABLE #providerVariability
	IF OBJECT_ID('tempdb..#staffingVariability') IS NOT NULL DROP TABLE #staffingVariability

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	
	DECLARE @BudgetConfigID INT
	SELECT @BudgetConfigID = BudgetConfigID 
	FROM fp.EntityGroupConfig egc 
		INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID 
	WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID

	DECLARE @IsForceDollarsOnlyToFixedFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Force Dollars Only to be Fixed' AND BudgetConfigID = @BudgetConfigID), 0)
	
	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; 
	
	DECLARE @StaffingSubsectionID INT = (SELECT SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing');
	DECLARE @ProviderSubsectionID INT = (SELECT SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider');
	       	
	CREATE TABLE #staffingVariability (EntityGroupConfigGUID UNIQUEIDENTIFIER, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6))
		
	/*
		NOTE ABOUT JAZZ-35951
		-----------------------------
		We now store variability at the Employee level, this is to allow cases where a Department/Job Code combination is set to variable, however
		it has employee budgeting enabled and they add an employee to it. This would add the employee, but we want it to be 100% Fixed.

		Employees in Employee Budgeting are always 100% Fixed. This is why we are setting EmployeeID = 0, essentially all rows where EmployeeID > 0, it should
		always have a Fixed Percentage of 100%. Anything that is variable is going to have EmployeeID = 0.
	*/

	-------------------------------------------------------------------------------------------
	-- Patient Activity
	-------------------------------------------------------------------------------------------
	IF EXISTS(SELECT 1 FROM [fp].[EntityGroupConfig] WHERE IsPatientActivityFlexingForStaffing = 1 AND EntityGroupConfigGUID = @EntityGroupConfigGUID )
	BEGIN
		
		INSERT INTO #staffingVariability (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage)
		SELECT 
			a.EntityGroupConfigGUID,
			a.DepartmentID,
			a.JobCodeID,
			a.PayCodeGroupID,
			0 AS ProviderLineItemID,
			0 AS EmployeeID,
			a.FixedPercentage
		FROM (
		    SELECT 
		        fp.EntityGroupConfigGUID,
		        fp.DepartmentID, 
		        fp.JobCodeID, 
		        fp.PayCodeGroupID, 
		        CASE 
		            WHEN TotalCost = 0 THEN 0 
		            WHEN (TotalFixedDirectCost/TotalCost) > .9999 THEN 1.0 
		            ELSE (TotalFixedDirectCost/TotalCost) 
		        END AS [FixedPercentage],
		        COALESCE(conovr.FlexMethodID, fp.FlexMethodID) as [FlexMethodID]
		    FROM (
					SELECT
						ec.EntityGroupConfigGuid,
						pay.DepartmentID,
						pay.OriginalJobCodeID as JobCodeID,
						pc.PayCodeGroupID,
						fc.FlexMethodID,
						SUM(pay.FixedDirectUnitCost * pay.Volume) as TotalFixedDirectCost,
						SUM(pay.TotalCost) as TotalCost
					FROM
						[dss].[FactCostingOutDetailPayroll] pay
						INNER JOIN [fw].[DimPayCode] pc on pay.OriginalPayCodeID = pc.PayCodeID
						INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID
						INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID
						INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.EntityGroupConfigGUID = ec.EntityGroupConfigGUID AND fc.DepartmentID = pay.DepartmentID
						INNER JOIN fw.DimPayCodeGroup pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID
						INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID
					WHERE
						pay.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0)
						AND pay.TimeClassID = ec.CostingConfigTimeClassID
						AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID
									AND (@IsForceDollarsOnlyToFixedFlag = 0 OR pcg.ProductiveClassID != 4) -- 4 = Dollars Only; 
					GROUP BY
						ec.EntityGroupConfigGuid, pay.DepartmentID, pay.OriginalJobCodeID, pc.PayCodeGroupID, pay.FiscalYearID, fc.FlexMethodID
							) fp
		    LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr 
		        ON fp.EntityGroupConfigGuid = conovr.EntityGroupConfigGuid 
		        AND fp.DepartmentID = conovr.DepartmentID 
		        AND fp.JobCodeID = conovr.JobCodeID
		    ) a
		WHERE 
		    a.FlexMethodID = 2
		    AND FixedPercentage < 1; 
	END

	-- Get distinct dimensionality from staffing
	SELECT DISTINCT
		fs.DepartmentID,
		JobCodeID,
		fs.PayCodeGroupID,
		fs.ProviderLineItemID,
		fs.SubsectionID,
		fs.EmployeeID,
		fs.IsNew
	INTO #staffingDim
	FROM [fp].[Staffing] fs
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fs.DepartmentID	
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.VariabilityID = 2  -- limit to variability = 2 only to make query faster, all unit types should be there but we only need Dept/JobCode/PayCode/ProviderLineItem
		AND (@IsForceDollarsOnlyToFixedFlag = 0 OR fs.ProductiveClassID != 4) -- 4 = Dollars Only;  
	    
	-------------------------------------------------------------------------------------------
	-- Regular Staffing Variability
	-------------------------------------------------------------------------------------------
	SELECT
		a.DepartmentID,
		a.JobCodeID,
		fs.PayCodeGroupID,
		a.FixedPercentage,
		0 as ProviderLineItemID,
		0 AS EmployeeID
	INTO #variability
	FROM
	( 
		SELECT 
			pvc.EntityGroupConfigGUID,
			COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID',
			COALESCE(conovr.JobCodeID, pvc.JobCodeID) AS 'JobCodeID',
			(1 - COALESCE(varovr.Variability, pvc.Variability)) AS 'FixedPercentage',
			COALESCE(conovr.FlexMethodID, efc.FlexMethodID) AS 'FlexMethodID'
		FROM 
			[fp].[PayrollVariabilityConfig] pvc
			INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID
			LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID
			LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID
		WHERE
			pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID
			AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 1
			AND COALESCE(varovr.Variability, pvc.Variability) != 0
	) a
	INNER JOIN (
		SELECT DISTINCT
			DepartmentID,
			JobCodeID,
			PayCodeGroupID
		FROM #staffingDim
		WHERE SubSectionID = @StaffingSubsectionID
	) fs ON fs.DepartmentID = a.DepartmentID AND fs.JobCodeID = a.JobCodeID
	
	-------------------------------------------------------------------------------------------
	-- Provider Staffing Variability (overrides regular Staffing Variability)
	-------------------------------------------------------------------------------------------
	 SELECT DISTINCT
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		fs.ProviderLineItemID,
		0 AS EmployeeID,
		CASE WHEN psc.VariabilityID = 1 THEN 1 ELSE 0 END as ProviderFixedPercentage
	INTO #ProviderVariability
	FROM #staffingDim fs
		INNER JOIN [fp].[ProviderStaffingConfig] psc ON fs.ProviderLineItemID = psc.ProviderLineItemID
		LEFT JOIN ( SELECT 
					    COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID'
					FROM 
					    [fp].[PayrollVariabilityConfig] pvc
					    INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID
							INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID
					    LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID
					    LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID
					WHERE
					    pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID
					    AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 6
					) fixed ON fs.DepartmentID = fixed.DepartmentID			
	WHERE fs.SubSectionID = @ProviderSubsectionID AND @IsProviderPlanningEnabled = 1 AND fixed.DepartmentID IS NULL and psc.BudgetConfigID = @BudgetConfigID
	
	-------------------------------------------------------------------------------------------
	-- Stat Accounts
	-------------------------------------------------------------------------------------------
	INSERT INTO #staffingVariability (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, FixedPercentage, ProviderLineItemID, EmployeeID)
	SELECT 
		@EntityGroupConfigGUID,
		s.DepartmentID,
		s.JobCodeID AS JobCodeID,
		s.PayCodeGroupID AS PayCodeID,
		s.FixedPercentage,
		0 as ProviderLineItemID,
		0 AS EmployeeID
	FROM #variability s LEFT JOIN #ProviderVariability p ON s.DepartmentID = p.DepartmentID AND s.JobCodeID = p.JobCodeID
	WHERE p.DepartmentID IS NULL AND p.JobCodeID IS NULL
	   
	-------------------------------------------------------------------------------------------
	-- Provider Stat Accounts
	-------------------------------------------------------------------------------------------
	INSERT INTO #staffingVariability (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, FixedPercentage, ProviderLineItemID, EmployeeID)
	SELECT 
		@EntityGroupConfigGUID,
		p.DepartmentID,
		p.JobCodeID AS JobCodeID,
		p.PayCodeGroupID AS PayCodeID,
		p.ProviderFixedPercentage,
		p.ProviderLineItemID,
		0 AS EmployeeID
	FROM  #ProviderVariability p 

	-------------------------------------------------------------------------------------------
	-- Publish FixedVariability Percentage to Staffing
	-------------------------------------------------------------------------------------------
	IF (@IsDebug = 1)
	BEGIN
		SELECT EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, FixedPercentage FROM #staffingVariability
	END ELSE BEGIN
				
		-- Reset the values to Fixed as we exclude things below (this is similar to deleting everything)
		UPDATE pv 
		SET pv.FixedVariabilityPercentage = 1
		FROM [fp].[Staffing] pv
			INNER JOIN #FilterByDepartment ff on ff.DepartmentID = pv.DepartmentID
		WHERE pv.EntityGroupConfigID = @EntityGroupConfigID
			AND pv.FixedVariabilityPercentage != 1

		UPDATE fs
		SET fs.FixedVariabilityPercentage = varb.FixedPercentage
		FROM fp.Staffing fs
			INNER JOIN #staffingVariability varb ON
					fs.DepartmentID = varb.DepartmentID
				AND fs.JobCodeID = varb.JobCodeID
				AND fs.PayCodeGroupID = varb.PayCodeGroupID
				AND fs.ProviderLineItemID = varb.ProviderLineItemID
				AND fs.EmployeeID = varb.EmployeeID
				AND varb.EntityGroupConfigGUID = @EntityGroupConfigGUID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND fs.FixedVariabilityPercentage != varb.FixedPercentage
	END	

 END
GO


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

-- fp.procPopulateMissingWorkflowSteps
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2021-03-17  NN      JAZZ-467	Remove null joins and joins on targting object
** 2    2022-07-06  BW      JAZZ-37489	Prevent duplicate inserts for untargeted
*************************************************************/
CREATE PROCEDURE fp.procPopulateMissingWorkflowSteps
 	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
 SELECT DepartmentID 
	INTO #SourceDimensionality 
	FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
 	-- JAZZ-9178 prevent duplicate inserts
	DELETE #SourceDimensionality
	FROM   #SourceDimensionality a
		   INNER JOIN [fp].[viewAPEDepartmentWorkflowStatus] b
				   ON b.DepartmentID = a.DepartmentId
					  AND b.EntityGroupConfigID = @EntityGroupConfigID 
	--The left join to [fp].[APEDepartmentWorkflowStatus] was missing that last clause on WorkflowStepID,
	--which stopped users from adding the same department to multiple budget configs through adjustment import
	IF (SELECT COUNT(*) FROM #SourceDimensionality WHERE DepartmentID IS NULL) >= 1
	BEGIN
	 	INSERT INTO [fp].[APEDepartmentWorkflowStatus] (WorkflowStepID, DepartmentID, EnteredStepDateTimeUtc, Status)
		SELECT DISTINCT aw.WorkflowStepID, dc.DepartmentID, GetUTCDate(), 0
		FROM [fp].[DepartmentConfig] dc
			INNER JOIN [fp].[EntityGroupConfig] ec ON ec.EntityGroupConfigGUID = dc.EntityGroupConfigGUID
			INNER JOIN [fp].[APEWorkflow] aw ON aw.EntityGroupConfigID = @EntityGroupConfigID and aw.WorkflowStepOrder = 1
		    LEFT JOIN [fp].[APEDepartmentWorkflowStatus] dw ON dc.DepartmentID = dw.DepartmentID and aw.WorkflowStepID = dw.WorkflowStepID
	    WHERE dw.DepartmentID IS NULL 
			AND dc.EntityGroupConfigGUID = @EntityGroupConfigGUID
			AND NOT EXISTS (
				SELECT DepartmentID
				FROM [fp].[viewAPEDepartmentWorkflowStatus]
				WHERE EntityGroupConfigID = @EntityGroupConfigID 
			)

	END ELSE BEGIN
		INSERT INTO [fp].[APEDepartmentWorkflowStatus] (WorkflowStepID, DepartmentID, EnteredStepDateTimeUtc, Status)
		SELECT DISTINCT aw.WorkflowStepID, dc.DepartmentID, GetUTCDate(), 0
		FROM [fp].[DepartmentConfig] dc
			INNER JOIN [fp].[EntityGroupConfig] ec ON ec.EntityGroupConfigGUID = dc.EntityGroupConfigGUID
			INNER JOIN [fp].[APEWorkflow] aw ON aw.EntityGroupConfigID = @EntityGroupConfigID and aw.WorkflowStepOrder = 1
			INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = dc.DepartmentID
		    LEFT JOIN [fp].[APEDepartmentWorkflowStatus] dw ON dc.DepartmentID = dw.DepartmentID and aw.WorkflowStepID = dw.WorkflowStepID
	    WHERE dw.DepartmentID IS NULL 
			AND dc.EntityGroupConfigGUID = @EntityGroupConfigGUID
	END
 END
GO


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

-- fp.procPopulateReportChargesNotCrosswalkedData
CREATE   PROCEDURE [fp].[procPopulateReportChargesNotCrosswalkedData] 
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI           Description
	** 1    05-16-2023   MY        JAZZ-54654	Initial Creation
	** 2	07-11-2023	 MY		   JAZZ-57364	Convert to use EntityGroupConfigID
	** 3 	08-05-2024   MD  	   JAZZ-70711	Update to only load projection months NOT loaded
	** 4 	09-27-2024   MY  	   JAZZ-75442	Add Check for IsRecordDeleted
	*************************************************************/

	EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#missingDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#missingDollars'
	EXEC [dbo].[procSysDropTempTable] '#filteringTable'

	DECLARE @MonthsLoaded INT = (SELECT MonthsLoaded FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID)

	CREATE TABLE #FilteringTable (DepartmentID INT, INDEX ix_1 NONCLUSTERED (DepartmentID))

	-- Get Targeting
	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 BEGIN
		INSERT INTO #filteringTable (DepartmentID) 
		SELECT DISTINCT DepartmentID 
		FROM fp.ChargeVolume 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	
	ELSE BEGIN
		INSERT INTO #filteringTable (DepartmentID)
		SELECT DepartmentID
		FROM @SourceDimensionality
	END

	-- First we need to determine what is in Charge Volume that is missing from the crosswalk
	SELECT DISTINCT cv.DepartmentID, ChargeCodeID, PatientClassID
	INTO #chargeDimensionality
	FROM fp.ChargeVolume cv
		INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID
	WHERE EntityGroupConfigID = @EntityGroupConfigID

	SELECT DISTINCT cv.DepartmentID, ChargeCodeID, PatientClassID
	INTO #crosswalkDimensionality
	FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration cv
		INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID
	WHERE EntityGroupConfigID = @EntityGroupConfigID
		AND cv.IsRecordDeleted = 0

	SELECT DISTINCT chrg.DepartmentID, chrg.ChargeCodeID, chrg.PatientClassID
	INTO #missingDimensionality
	FROM #chargeDimensionality chrg
		LEFT JOIN #crosswalkDimensionality walk ON chrg.DepartmentID = walk.DepartmentID
			AND chrg.ChargeCodeID = walk.ChargeCodeID
			AND chrg.PatientClassID = walk.PatientClassID
	WHERE walk.DepartmentID IS NULL

	IF @IsDebug = 1
	BEGIN
		SELECT '#chargeDimensionality' AS #chargeDimensionality, * FROM #chargeDimensionality
		SELECT '#crosswalkDimensionality' AS #crosswalkDimensionality, * FROM #crosswalkDimensionality
		SELECT '#missingDimensionality' AS #missingDimensionality, * FROM #missingDimensionality
	END

	-- We no longer need these as we can just use what is missing
	EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality'

	-- Now that we have the missing dimensionality, we need to get the total values for each.
	SELECT 
		cv.DepartmentID,
		cv.PatientClassID,
		cv.ChargeCodeID,
		cv.BudgetConfigID,
		cv.EntityGroupConfigID,
		SUM(
			CASE 
				WHEN @MonthsLoaded = 1  THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 2  THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 3  THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 4  THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 5  THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 6  THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 7  THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 8  THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 9  THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12
				ELSE 0 END
		) AS ProjectionDollarsAdjustedTotal,
		SUM(cv.TargetDollarsAdjustedTotal) AS TargetDollarsAdjustedTotal,
		SUM(cv.BudgetDollarsAdjustedTotal) AS BudgetDollarsAdjustedTotal
	INTO #missingDollars
	FROM fp.ChargeVolume cv
		INNER JOIN #missingDimensionality miss ON cv.DepartmentID = miss.DepartmentID
			AND cv.PatientClassID = miss.PatientClassID
			AND cv.ChargeCodeID = miss.ChargeCodeID
	WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
		AND (
			cv.ProjectionDollarsAdjustedTotal > 0 OR
			cv.TargetDollarsAdjustedTotal > 0 OR
			cv.BudgetDollarsAdjustedTotal > 0
		)
	GROUP BY cv.DepartmentID,
		cv.PatientClassID,
		cv.ChargeCodeID,
		cv.BudgetConfigID,
		cv.EntityGroupConfigID

	EXEC [dbo].[procSysDropTempTable] '#missingDimensionality'

	IF @IsDebug = 1
	BEGIN
		SELECT '#missingDollars' AS #missingDollars, * FROM #missingDollars
	END ELSE 
	BEGIN

		;WITH TGT AS 
		(
			SELECT FRS.DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, EntityGroupConfigID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal
			FROM fp.FactReportChargesNotCrosswalkedData FRS
				INNER JOIN #filteringTable ft ON FRS.DepartmentID = ft.DepartmentID
			WHERE EntityGroupConfigID = @EntityGroupConfigID
		)
		MERGE TGT AS target
		USING #missingDollars AS SOURCE
		ON (
				target.DepartmentID			= source.DepartmentID
			AND target.PatientClassID		= source.PatientClassID
			AND target.ChargeCodeID			= source.ChargeCodeID
			AND target.BudgetConfigID		= source.BudgetConfigID
			AND target.EntityGroupConfigID  = source.EntityGroupConfigID
			)
		WHEN MATCHED AND 
			(	
				target.BudgetDollarsAdjustedTotal <> source.BudgetDollarsAdjustedTotal
				OR target.ProjectionDollarsAdjustedTotal <> source.ProjectionDollarsAdjustedTotal
				OR target.TargetDollarsAdjustedTotal <> source.TargetDollarsAdjustedTotal
				)
		THEN
			UPDATE SET
				target.BudgetDollarsAdjustedTotal = ISNULL(source.BudgetDollarsAdjustedTotal, 0),
				target.ProjectionDollarsAdjustedTotal = ISNULL(source.ProjectionDollarsAdjustedTotal, 0),
				target.TargetDollarsAdjustedTotal = ISNULL(source.TargetDollarsAdjustedTotal, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, EntityGroupConfigID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal)
				VALUES (
						source.DepartmentID,
						source.PatientClassID,
						source.ChargeCodeID,
						source.BudgetConfigID,
						source.EntityGroupConfigID,
						ISNULL(source.ProjectionDollarsAdjustedTotal, 0),
						ISNULL(source.TargetDollarsAdjustedTotal, 0),
						ISNULL(source.BudgetDollarsAdjustedTotal, 0)
				)
		WHEN NOT MATCHED BY SOURCE
			THEN DELETE;

	END

END
GO


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

-- fp.procPopulateReportChargesNotCrosswalkedData_WithPayorGroup
CREATE   PROCEDURE [fp].[procPopulateReportChargesNotCrosswalkedData_WithPayorGroup] 
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2023-07-11   MY        JAZZ-57364    Initial Creation
	** 2 	2024-04-11   MY  	   JAZZ-70660	 Update to leverage additional dimensions in mix table
	** 3 	2024-08-05   MD  	   JAZZ-70711	 Update to only load projection months NOT loaded
	** 4 	2024-09-12   MY  	   JAZZ-75442	 Filter out the Soft Deleted Records
	*************************************************************/

	EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#missingDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#missingDollars'
	EXEC [dbo].[procSysDropTempTable] '#filteringTable'
	EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality_WithPayorMix'

	CREATE TABLE #FilteringTable (DepartmentID INT, INDEX ix_1 NONCLUSTERED (DepartmentID))

	DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID)
	DECLARE @MonthsLoaded INT = (SELECT MonthsLoaded FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID)
	DECLARE @IsServiceLineInMix INT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0)

	-- JAZZ-70660: Adding Additional Dimensionality into the SLE to Charge payor mix calc 
	DECLARE @IsAdditionalDimensionalityEnabled BIT = ISNULL((SELECT Value  
												FROM fp.viewBudgetConfigSetting setting 
													INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID 
													INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID 
												WHERE egc.EntityGroupConfigID = @EntityGroupConfigID 
													AND setting.Name = 'Enable Charge to General Ledger Crosswalk to Use Detailed Mix'), 0) 

	-- Get Targeting
	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 BEGIN
		INSERT INTO #filteringTable (DepartmentID) 
		SELECT DISTINCT DepartmentID 
		FROM fp.ChargeVolume 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	
	ELSE BEGIN
		INSERT INTO #filteringTable (DepartmentID)
		SELECT DepartmentID
		FROM @SourceDimensionality
	END

	CREATE TABLE #missingDollars (
		DepartmentID INT NOT NULL,
		PatientClassID INT NOT NULL,
		ChargeCodeID INT NOT NULL,
		BudgetConfigID INT NOT NULL,
		PayorGroupID INT NOT NULL,
		EntityGroupConfigID INT NOT NULL,
		ProjectionDollarsAdjustedTotal DECIMAL(36, 8) NOT NULL,
		TargetDollarsAdjustedTotal DECIMAL(36, 8) NOT NULL,
		BudgetDollarsAdjustedTotal DECIMAL(36, 8) NOT NULL
	)

	-- Clear out report data since the merge wasn't always cleaning it up.
	DELETE rpt 
	FROM fp.FactReportChargesNotCrosswalkedData rpt
		INNER JOIN #filteringTable ft ON rpt.DepartmentID = ft.DepartmentID
	WHERE rpt.EntityGroupConfigID = @EntityGroupConfigID

	-- DBA's recommendation
	UPDATE STATISTICS #filteringTable WITH FULLSCAN

	IF (@IsAdditionalDimensionalityEnabled = 0)
	BEGIN

		-- First we need to determine what is in Charge Volume that is missing from the crosswalk
		SELECT DISTINCT 
			cv.BudgetConfigID, cv.EntityGroupConfigID, cv.DepartmentID, cv.ServiceEntityID, 
			cv.ServiceLineID, ChargeCodeID, PatientClassID, 
			--JAZZ-70711 - We only want to display months not loaded
			CASE 
				WHEN @MonthsLoaded = 1  THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 2  THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 3  THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 4  THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 5  THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 6  THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 7  THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 8  THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 9  THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12
				ELSE 0
			END AS ProjectionDollarsAdjustedTotal, 
			TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal
		INTO #chargeDimensionality
		FROM fp.ChargeVolume cv
			INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID

		-- Right now we only have 1 mix for Budget that covers Target and Budget, that will not always be the case.
		SELECT DISTINCT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.DepartmentID, cv.ChargeCodeID, cv.PatientClassID, mix.PayorGroupID, mix.BudgetMixPercentage, mix.ProjectionMixPercentage, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal
		INTO #chargeDimensionality_WithPayorMix
		FROM #chargeDimensionality cv WITH (READUNCOMMITTED)
			INNER JOIN fp.viewServiceLineEncounterPayorGroupMix_Pivoted mix WITH (READUNCOMMITTED) on 
					mix.PatientClassID = cv.PatientClassID
				AND mix.EntityID = cv.ServiceEntityID
				AND (@IsServiceLineInMix = 0 OR mix.ServiceLineID = cv.ServiceLineID)
		WHERE mix.EntityGroupConfigID = @EntityGroupConfigID

		SELECT DISTINCT cv.DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID
		INTO #crosswalkDimensionality
		FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration cv
			INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND cv.IsRecordDeleted = 0

		SELECT DISTINCT chrg.BudgetConfigID, chrg.EntityGroupConfigID, chrg.DepartmentID, chrg.ChargeCodeID, chrg.PatientClassID, chrg.PayorGroupID, chrg.BudgetMixPercentage, chrg.ProjectionMixPercentage, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal
		INTO #missingDimensionality
		FROM #chargeDimensionality_WithPayorMix chrg
			LEFT JOIN #crosswalkDimensionality walk ON chrg.DepartmentID = walk.DepartmentID
				AND chrg.ChargeCodeID = walk.ChargeCodeID
				AND chrg.PatientClassID = walk.PatientClassID
				AND chrg.PayorGroupID = walk.PayorGroupID
		WHERE walk.DepartmentID IS NULL

		IF @IsDebug = 1
		BEGIN
			SELECT '#chargeDimensionality' AS #chargeDimensionality, * FROM #chargeDimensionality
			SELECT '#chargeDimensionality_WithPayorMix' AS #chargeDimensionality_WithPayorMix, * FROM #chargeDimensionality_WithPayorMix
			SELECT '#crosswalkDimensionality' AS #crosswalkDimensionality, * FROM #crosswalkDimensionality
			SELECT '#missingDimensionality' AS #missingDimensionality, * FROM #missingDimensionality
		END

		-- We no longer need these as we can just use what is missing
		EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality'
		EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality'

		-- Now that we have the missing dimensionality, we need to get the total values for each.
		INSERT INTO #missingDollars (DepartmentID,
			PatientClassID,
			ChargeCodeID,
			BudgetConfigID,
			PayorGroupID,
			EntityGroupConfigID,
			ProjectionDollarsAdjustedTotal,
			TargetDollarsAdjustedTotal,
			BudgetDollarsAdjustedTotal)
		SELECT 
			DepartmentID,
			PatientClassID,
			ChargeCodeID,
			BudgetConfigID,
			PayorGroupID,
			EntityGroupConfigID,
			SUM(ProjectionDollarsAdjustedTotal * ProjectionMixPercentage) AS ProjectionDollarsAdjustedTotal,
			SUM(TargetDollarsAdjustedTotal * BudgetMixPercentage) AS TargetDollarsAdjustedTotal,
			SUM(BudgetDollarsAdjustedTotal * BudgetMixPercentage) AS BudgetDollarsAdjustedTotal
		FROM #missingDimensionality
		WHERE EntityGroupConfigID = @EntityGroupConfigID
			AND (
				ProjectionDollarsAdjustedTotal != 0 OR
				TargetDollarsAdjustedTotal != 0 OR
				BudgetDollarsAdjustedTotal != 0
			)
		GROUP BY DepartmentID,
			PatientClassID,
			ChargeCodeID,
			BudgetConfigID,
			PayorGroupID,
			EntityGroupConfigID

		EXEC [dbo].[procSysDropTempTable] '#missingDimensionality'

	END ELSE BEGIN

	INSERT INTO #missingDollars (
			DepartmentID,
			PatientClassID,
			ChargeCodeID,
			BudgetConfigID,
			PayorGroupID,
			EntityGroupConfigID,
			ProjectionDollarsAdjustedTotal,
			TargetDollarsAdjustedTotal,
			BudgetDollarsAdjustedTotal)
		SELECT cv.DepartmentID, cv.PatientClassID, cv.ChargeCodeID, cv.BudgetConfigID, mix.PayorGroupID, cv.EntityGroupConfigID, 
		SUM(
			CASE 
				WHEN @MonthsLoaded = 1  THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 2  THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 3  THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 4  THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 5  THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 6  THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 7  THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 8  THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 9  THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12
				ELSE 0 END * ProjectionMixPercentage
		) AS ProjectionTotal, 
		SUM(TargetDollarsAdjustedTotal * mix.BudgetMixPercentage) AS TargetTotal, SUM(cv.BudgetDollarsAdjustedTotal * mix.BudgetMixPercentage) AS BudgetTotal
		FROM fp.ChargeVolume cv 
		INNER JOIN fp.ServiceLineEncounterToChargePayorMix mix on 
				mix.BudgetConfigID = cv.BudgetConfigID
			AND mix.EntityGroupConfigID = cv.EntityGroupConfigID
			AND	mix.PatientClassID = cv.PatientClassID
			AND mix.EntityID = cv.ServiceEntityID
			AND mix.ServiceLineID = cv.ServiceLineID
			AND mix.AgeCohortID = cv.AgeCohortID
			AND mix.MedicalSurgicalID = cv.MedicalSurgicalID
			AND mix.MSDRGID = cv.MSDRGID
			AND mix.CPTID = cv.PrimaryCPTID
			AND mix.ProviderID = cv.ServiceProviderID
		INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID
		INNER JOIN fp.EntityGroupConfig egc ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
		LEFT JOIN (SELECT DISTINCT BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration WHERE IsRecordDeleted = 0) config ON 
					cv.BudgetConfigID = config.BudgetConfigID
				AND cv.EntityGroupConfigID = config.EntityGroupConfigID 
				AND cv.DepartmentID = config.DepartmentID 
				AND cv.ChargeCodeID = config.ChargeCodeID
				AND cv.PatientClassID = config.PatientClassID
				AND mix.PayorGroupID = config.PayorGroupID
		WHERE 1 = 1
			AND egc.IsPayorGroupUsedForCrosswalk = 1
			AND cv.EntityGroupConfigID = @EntityGroupConfigID
			AND config.BudgetConfigID IS NULL
		GROUP BY cv.DepartmentID, cv.PatientClassID, cv.ChargeCodeID, cv.BudgetConfigID, mix.PayorGroupID, 
			cv.EntityGroupConfigID
		HAVING (SUM(
			CASE 
				WHEN @MonthsLoaded = 1  THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 2  THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 3  THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 4  THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 5  THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 6  THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 7  THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 8  THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 9  THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12
				WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12
				ELSE 0 END * ProjectionMixPercentage
			) != 0 
		OR SUM(cv.TargetDollarsAdjustedTotal * mix.BudgetMixPercentage) != 0 
		OR SUM(cv.BudgetDollarsAdjustedTotal * mix.BudgetMixPercentage) != 0)

	END

	IF @IsDebug = 1
	BEGIN
		SELECT '#missingDollars' AS #missingDollars, * FROM #missingDollars
	END ELSE 
	BEGIN

		;WITH TGT AS 
		(
			SELECT FRS.DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, EntityGroupConfigID, PayorGroupID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal
			FROM fp.FactReportChargesNotCrosswalkedData FRS
				INNER JOIN #filteringTable ft ON FRS.DepartmentID = ft.DepartmentID
			WHERE EntityGroupConfigID = @EntityGroupConfigID
		)
		MERGE TGT AS target
		USING #missingDollars AS SOURCE
		ON (
				target.BudgetConfigID		= source.BudgetConfigID
			AND target.EntityGroupConfigID  = source.EntityGroupConfigID
			AND target.DepartmentID			= source.DepartmentID
			AND target.PatientClassID		= source.PatientClassID
			AND target.ChargeCodeID			= source.ChargeCodeID
			AND target.PayorGroupID			= source.PayorGroupID
			)
		WHEN MATCHED AND 
			(	
				target.BudgetDollarsAdjustedTotal <> source.BudgetDollarsAdjustedTotal
				OR target.ProjectionDollarsAdjustedTotal <> source.ProjectionDollarsAdjustedTotal
				OR target.TargetDollarsAdjustedTotal <> source.TargetDollarsAdjustedTotal
				)
		THEN
			UPDATE SET
				target.BudgetDollarsAdjustedTotal = ISNULL(source.BudgetDollarsAdjustedTotal, 0),
				target.ProjectionDollarsAdjustedTotal = ISNULL(source.ProjectionDollarsAdjustedTotal, 0),
				target.TargetDollarsAdjustedTotal = ISNULL(source.TargetDollarsAdjustedTotal, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, PayorGroupID, EntityGroupConfigID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal)
				VALUES (
						source.DepartmentID,
						source.PatientClassID,
						source.ChargeCodeID,
						source.BudgetConfigID,
						source.PayorGroupID,
						source.EntityGroupConfigID,
						ISNULL(source.ProjectionDollarsAdjustedTotal, 0),
						ISNULL(source.TargetDollarsAdjustedTotal, 0),
						ISNULL(source.BudgetDollarsAdjustedTotal, 0)
				)
		WHEN NOT MATCHED BY SOURCE
			THEN DELETE;

	END

END
GO


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

-- fp.procPopulateReportFactChargeVolume_Dollars_Budget
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2020-03-04  MY          JAZZ-16292      Initial
** 2    2020-02-14  MY          JAZZ-33542      Add Targeting
** 3	2023-03-21	MY		    JAZZ-49993		Update reporting to support new data model
** 4	2023-06-12	MY		    JAZZ-54952		Update to new column names
*********************************************************************/
CREATE   PROCEDURE fp.procPopulateReportFactChargeVolume_Dollars_Budget (
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN	

	EXEC [dbo].[procSysDropTempTable] '#source'
	EXEC [dbo].[procSysDropTempTable] '#recordsUpdated'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	DECLARE @BudgetYear INT;
	SET @BudgetYear = (SELECT FiscalYearID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID);

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END
	
	CREATE TABLE #source (
		ChargeVolumeID INT,
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		PatientClassID INT,
		ChargeCodeID INT,
		ServiceLineID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		ServiceEntityID INT,
		MSDRGID INT,
		UBRevCodeID INT,
		PrimaryCPTID INT,
		ServiceProviderID INT,
		ServiceProviderSpecialtyID INT,
		PerformingProviderID INT,
		PerformingProviderSpecialtyID INT,
		BillingCPTID INT,
		UnitTypeID INT,
		TimeClassID INT,
		FiscalMonthID INT,
		FiscalYearID INT,
		OriginalValue01 DECIMAL(19, 8),
		OriginalValue02 DECIMAL(19, 8),
		OriginalValue03 DECIMAL(19, 8),
		OriginalValue04 DECIMAL(19, 8),
		OriginalValue05 DECIMAL(19, 8),
		OriginalValue06 DECIMAL(19, 8),
		OriginalValue07 DECIMAL(19, 8),
		OriginalValue08 DECIMAL(19, 8),
		OriginalValue09 DECIMAL(19, 8),
		OriginalValue10 DECIMAL(19, 8),
		OriginalValue11 DECIMAL(19, 8),
		OriginalValue12 DECIMAL(19, 8),
		OriginalValueTotal DECIMAL(19, 8),
		Value01 DECIMAL(19, 8),
		Value02 DECIMAL(19, 8),
		Value03 DECIMAL(19, 8),
		Value04 DECIMAL(19, 8),
		Value05 DECIMAL(19, 8),
		Value06 DECIMAL(19, 8),
		Value07 DECIMAL(19, 8),
		Value08 DECIMAL(19, 8),
		Value09 DECIMAL(19, 8),
		Value10 DECIMAL(19, 8),
		Value11 DECIMAL(19, 8),
		Value12 DECIMAL(19, 8),
		ValueTotal DECIMAL(19, 8),
		ManagerValue01 DECIMAL(19, 8),
		ManagerValue02 DECIMAL(19, 8),
		ManagerValue03 DECIMAL(19, 8),
		ManagerValue04 DECIMAL(19, 8),
		ManagerValue05 DECIMAL(19, 8),
		ManagerValue06 DECIMAL(19, 8),
		ManagerValue07 DECIMAL(19, 8),
		ManagerValue08 DECIMAL(19, 8),
		ManagerValue09 DECIMAL(19, 8),
		ManagerValue10 DECIMAL(19, 8),
		ManagerValue11 DECIMAL(19, 8),
		ManagerValue12 DECIMAL(19, 8),
		ManagerValueTotal DECIMAL(19, 8)
	)

	-- Budget
	INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID,	ServiceEntityID,
			MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
			BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, 
			OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12, OriginalValueTotal, 
			Value01, Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12, ValueTotal, 
			ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12, ManagerValueTotal)
	SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID,	fcv.ServiceEntityID,
			fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID,
			fcv.BillingCPTID, 34 AS UnitTypeID, 2 AS TimeClassID, @BudgetYear AS FiscalYearID, 
			fcv.InitialBudgetDollars01, fcv.InitialBudgetDollars02, fcv.InitialBudgetDollars03, fcv.InitialBudgetDollars04, fcv.InitialBudgetDollars05, fcv.InitialBudgetDollars06, fcv.InitialBudgetDollars07, fcv.InitialBudgetDollars08, fcv.InitialBudgetDollars09, fcv.InitialBudgetDollars10, fcv.InitialBudgetDollars11, fcv.InitialBudgetDollars12, fcv.InitialBudgetDollarsTotal, 
			fcv.TargetDollarsAdjusted01, fcv.TargetDollarsAdjusted02, fcv.TargetDollarsAdjusted03, fcv.TargetDollarsAdjusted04, fcv.TargetDollarsAdjusted05, fcv.TargetDollarsAdjusted06, fcv.TargetDollarsAdjusted07, fcv.TargetDollarsAdjusted08, fcv.TargetDollarsAdjusted09, fcv.TargetDollarsAdjusted10, fcv.TargetDollarsAdjusted11, fcv.TargetDollarsAdjusted12, fcv.TargetDollarsAdjustedTotal, 
			fcv.BudgetDollarsAdjusted01, fcv.BudgetDollarsAdjusted02, fcv.BudgetDollarsAdjusted03, fcv.BudgetDollarsAdjusted04, fcv.BudgetDollarsAdjusted05, fcv.BudgetDollarsAdjusted06, fcv.BudgetDollarsAdjusted07, fcv.BudgetDollarsAdjusted08, fcv.BudgetDollarsAdjusted09, fcv.BudgetDollarsAdjusted10, fcv.BudgetDollarsAdjusted11, fcv.BudgetDollarsAdjusted12, fcv.BudgetDollarsAdjustedTotal
	FROM fp.ChargeVolume fcv
		INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID
	WHERE fcv.BudgetConfigID  = @BudgetConfigID		

	CREATE CLUSTERED INDEX inx_src ON #source (
		ChargeVolumeID,
		BudgetConfigID,
		EntityID,
		DepartmentID,
		PatientClassID,
		ChargeCodeID,
		ServiceLineID,
		AgeCohortID,
		MedicalSurgicalID,
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		UnitTypeID,
		TimeClassID,
		FiscalYearID
	) with (data_compression = page)			
			
	;WITH TGT AS 
	(
		SELECT 
			ChargeVolumeID,
			BudgetConfigID,
			EntityID,
			FRS.DepartmentID,
			PatientClassID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			ServiceEntityID,
			MSDRGID,
			UBRevCodeID,
			PrimaryCPTID,
			ServiceProviderID,
			ServiceProviderSpecialtyID,
			PerformingProviderID,
			PerformingProviderSpecialtyID,
			BillingCPTID,
			UnitTypeID,
			InitialBudget01, 
			InitialBudget02, 
			InitialBudget03, 
			InitialBudget04, 
			InitialBudget05, 
			InitialBudget06, 
			InitialBudget07, 
			InitialBudget08, 
			InitialBudget09, 
			InitialBudget10, 
			InitialBudget11, 
			InitialBudget12, 
			InitialBudgetTotal, 
			Target01, 
			Target02, 
			Target03, 
			Target04, 
			Target05, 
			Target06, 
			Target07, 
			Target08, 
			Target09, 
			Target10, 
			Target11, 
			Target12, 
			TargetTotal, 
			Budget01, 
			Budget02, 
			Budget03, 
			Budget04, 
			Budget05, 
			Budget06, 
			Budget07, 
			Budget08, 
			Budget09, 
			Budget10, 
			Budget11, 
			Budget12, 
			BudgetTotal
		FROM [fp].[FactReportChargeVolume] FRS
			INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)
			MERGE TGT AS target
			USING #source AS source
				ON (
							target.ChargeVolumeID				 = source.ChargeVolumeID
						AND	target.BudgetConfigID				 = source.BudgetConfigID
						AND target.EntityID						 = source.EntityID
						AND target.DepartmentID					 = source.DepartmentID
						AND target.PatientClassID				 = source.PatientClassID
						AND target.ChargeCodeID					 = source.ChargeCodeID
						AND target.ServiceLineID				 = source.ServiceLineID
						AND target.AgeCohortID					 = source.AgeCohortID
						AND target.MedicalSurgicalID			 = source.MedicalSurgicalID
						AND target.ServiceEntityID				 = source.ServiceEntityID
						AND target.MSDRGID						 = source.MSDRGID
						AND target.UBRevCodeID					 = source.UBRevCodeID
						AND target.PrimaryCPTID					 = source.PrimaryCPTID
						AND target.ServiceProviderID			 = source.ServiceProviderID
						AND target.ServiceProviderSpecialtyID    = source.ServiceProviderSpecialtyID
						AND target.PerformingProviderID          = source.PerformingProviderID
						AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID
						AND target.BillingCPTID					 = source.BillingCPTID
						AND target.UnitTypeID					 = source.UnitTypeID

						)
			WHEN MATCHED AND (
					      target.InitialBudget01 <> source.OriginalValue01
					   OR target.InitialBudget02 <> source.OriginalValue02
					   OR target.InitialBudget03 <> source.OriginalValue03
					   OR target.InitialBudget04 <> source.OriginalValue04
					   OR target.InitialBudget05 <> source.OriginalValue05
					   OR target.InitialBudget06 <> source.OriginalValue06
					   OR target.InitialBudget07 <> source.OriginalValue07
					   OR target.InitialBudget08 <> source.OriginalValue08
					   OR target.InitialBudget09 <> source.OriginalValue09
					   OR target.InitialBudget10 <> source.OriginalValue10
					   OR target.InitialBudget11 <> source.OriginalValue11
					   OR target.InitialBudget12 <> source.OriginalValue12
					   OR target.InitialBudgetTotal <> source.OriginalValueTotal
					   OR target.Target01 <> source.Value01
					   OR target.Target02 <> source.Value02
					   OR target.Target03 <> source.Value03
					   OR target.Target04 <> source.Value04
					   OR target.Target05 <> source.Value05
					   OR target.Target06 <> source.Value06
					   OR target.Target07 <> source.Value07
					   OR target.Target08 <> source.Value08
					   OR target.Target09 <> source.Value09
					   OR target.Target10 <> source.Value10
					   OR target.Target11 <> source.Value11
					   OR target.Target12 <> source.Value12
					   OR target.TargetTotal <> source.ValueTotal
					   OR target.Budget01 <> source.ManagerValue01
					   OR target.Budget02 <> source.ManagerValue02
					   OR target.Budget03 <> source.ManagerValue03
					   OR target.Budget04 <> source.ManagerValue04
					   OR target.Budget05 <> source.ManagerValue05
					   OR target.Budget06 <> source.ManagerValue06
					   OR target.Budget07 <> source.ManagerValue07
					   OR target.Budget08 <> source.ManagerValue08
					   OR target.Budget09 <> source.ManagerValue09
					   OR target.Budget10 <> source.ManagerValue10
					   OR target.Budget11 <> source.ManagerValue11
					   OR target.Budget12 <> source.ManagerValue12
					   OR target.BudgetTotal <> source.ManagerValueTotal)
				THEN
					UPDATE SET
					target.InitialBudget01 = ISNULL(source.OriginalValue01, 0),
					target.InitialBudget02 = ISNULL(source.OriginalValue02, 0),
					target.InitialBudget03 = ISNULL(source.OriginalValue03, 0),
					target.InitialBudget04 = ISNULL(source.OriginalValue04, 0),
					target.InitialBudget05 = ISNULL(source.OriginalValue05, 0),
					target.InitialBudget06 = ISNULL(source.OriginalValue06, 0),
					target.InitialBudget07 = ISNULL(source.OriginalValue07, 0),
					target.InitialBudget08 = ISNULL(source.OriginalValue08, 0),
					target.InitialBudget09 = ISNULL(source.OriginalValue09, 0),
					target.InitialBudget10 = ISNULL(source.OriginalValue10, 0),
					target.InitialBudget11 = ISNULL(source.OriginalValue11, 0),
					target.InitialBudget12 = ISNULL(source.OriginalValue12, 0),
					target.InitialBudgetTotal = ISNULL(source.OriginalValueTotal, 0),
					target.Target01 = ISNULL(source.Value01, 0),
					target.Target02 = ISNULL(source.Value02, 0),
					target.Target03 = ISNULL(source.Value03, 0),
					target.Target04 = ISNULL(source.Value04, 0),
					target.Target05 = ISNULL(source.Value05, 0),
					target.Target06 = ISNULL(source.Value06, 0),
					target.Target07 = ISNULL(source.Value07, 0),
					target.Target08 = ISNULL(source.Value08, 0),
					target.Target09 = ISNULL(source.Value09, 0),
					target.Target10 = ISNULL(source.Value10, 0),
					target.Target11 = ISNULL(source.Value11, 0),
					target.Target12 = ISNULL(source.Value12, 0),
					target.TargetTotal = ISNULL(source.ValueTotal, 0),
					target.Budget01 = ISNULL(source.ManagerValue01, 0),
					target.Budget02 = ISNULL(source.ManagerValue02, 0),
					target.Budget03 = ISNULL(source.ManagerValue03, 0),
					target.Budget04 = ISNULL(source.ManagerValue04, 0),
					target.Budget05 = ISNULL(source.ManagerValue05, 0),
					target.Budget06 = ISNULL(source.ManagerValue06, 0),
					target.Budget07 = ISNULL(source.ManagerValue07, 0),
					target.Budget08 = ISNULL(source.ManagerValue08, 0),
					target.Budget09 = ISNULL(source.ManagerValue09, 0),
					target.Budget10 = ISNULL(source.ManagerValue10, 0),
					target.Budget11 = ISNULL(source.ManagerValue11, 0),
					target.Budget12 = ISNULL(source.ManagerValue12, 0),
					target.BudgetTotal = ISNULL(source.ManagerValueTotal, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
								ChargeVolumeID,
								BudgetConfigID,
								EntityID,
								DepartmentID,
								PatientClassID,
								ChargeCodeID,
								ServiceLineID,
								AgeCohortID,
								MedicalSurgicalID,
								ServiceEntityID,
								MSDRGID,
								UBRevCodeID,
								PrimaryCPTID,
								ServiceProviderID,
								ServiceProviderSpecialtyID,
								PerformingProviderID,
								PerformingProviderSpecialtyID,
								BillingCPTID,
								UnitTypeID,
								InitialBudget01, 
								InitialBudget02, 
								InitialBudget03, 
								InitialBudget04, 
								InitialBudget05, 
								InitialBudget06, 
								InitialBudget07, 
								InitialBudget08, 
								InitialBudget09, 
								InitialBudget10, 
								InitialBudget11, 
								InitialBudget12, 
								InitialBudgetTotal, 
								Target01, 
								Target02, 
								Target03, 
								Target04, 
								Target05, 
								Target06, 
								Target07, 
								Target08, 
								Target09, 
								Target10, 
								Target11, 
								Target12, 
								TargetTotal, 
								Budget01, 
								Budget02, 
								Budget03, 
								Budget04, 
								Budget05, 
								Budget06, 
								Budget07, 
								Budget08, 
								Budget09, 
								Budget10, 
								Budget11, 
								Budget12, 
								BudgetTotal
						)
					VALUES (
							source.ChargeVolumeID,
							source.BudgetConfigID,
							source.EntityID,
							source.DepartmentID,
							source.PatientClassID,
							source.ChargeCodeID,
							source.ServiceLineID,
							source.AgeCohortID,
							source.MedicalSurgicalID,
							source.ServiceEntityID,
							source.MSDRGID,
							source.UBRevCodeID,
							source.PrimaryCPTID,
							source.ServiceProviderID,
							source.ServiceProviderSpecialtyID,
							source.PerformingProviderID,
							source.PerformingProviderSpecialtyID,
							source.BillingCPTID,
							source.UnitTypeID,
							ISNULL(OriginalValue01, 0), 
							ISNULL(OriginalValue02, 0), 
							ISNULL(OriginalValue03, 0), 
							ISNULL(OriginalValue04, 0), 
							ISNULL(OriginalValue05, 0), 
							ISNULL(OriginalValue06, 0), 
							ISNULL(OriginalValue07, 0), 
							ISNULL(OriginalValue08, 0), 
							ISNULL(OriginalValue09, 0), 
							ISNULL(OriginalValue10, 0), 
							ISNULL(OriginalValue11, 0), 
							ISNULL(OriginalValue12, 0), 
							ISNULL(OriginalValueTotal, 0), 
							ISNULL(Value01, 0), 
							ISNULL(Value02, 0), 
							ISNULL(Value03, 0), 
							ISNULL(Value04, 0), 
							ISNULL(Value05, 0), 
							ISNULL(Value06, 0), 
							ISNULL(Value07, 0), 
							ISNULL(Value08, 0), 
							ISNULL(Value09, 0), 
							ISNULL(Value10, 0), 
							ISNULL(Value11, 0), 
							ISNULL(Value12, 0), 
							ISNULL(ValueTotal, 0), 
							ISNULL(ManagerValue01, 0), 
							ISNULL(ManagerValue02, 0), 
							ISNULL(ManagerValue03, 0), 
							ISNULL(ManagerValue04, 0), 
							ISNULL(ManagerValue05, 0), 
							ISNULL(ManagerValue06, 0), 
							ISNULL(ManagerValue07, 0), 
							ISNULL(ManagerValue08, 0), 
							ISNULL(ManagerValue09, 0), 
							ISNULL(ManagerValue10, 0), 
							ISNULL(ManagerValue11, 0), 
							ISNULL(ManagerValue12, 0), 
							ISNULL(ManagerValueTotal, 0)
						);

END
GO


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

-- fp.procPopulateReportFactChargeVolume_Dollars_Projection
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2020-03-04  MY          JAZZ-16292      Initial
** 2    2020-02-14  MY          JAZZ-33542      Add Targeting
** 3	2023-03-21	MY		    JAZZ-49993		Update reporting to support new data model
** 4	2023-06-12	MY		    JAZZ-54952		Update to new columns
*********************************************************************/
CREATE   PROCEDURE fp.procPopulateReportFactChargeVolume_Dollars_Projection (
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN	

	EXEC [dbo].[procSysDropTempTable] '#source'
	EXEC [dbo].[procSysDropTempTable] '#recordsUpdated'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	DECLARE @ProjectionYear INT;
	SET @ProjectionYear = (SELECT FiscalYearID - 1 FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID);
	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END
	
	CREATE TABLE #source (
		ChargeVolumeID INT,
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		PatientClassID INT,
		ChargeCodeID INT,
		ServiceLineID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		ServiceEntityID INT,
		MSDRGID INT,
		UBRevCodeID INT,
		PrimaryCPTID INT,
		ServiceProviderID INT,
		ServiceProviderSpecialtyID INT,
		PerformingProviderID INT,
		PerformingProviderSpecialtyID INT,
		BillingCPTID INT,
		UnitTypeID INT,
		TimeClassID INT,
		FiscalMonthID INT,
		FiscalYearID INT,
		Projection01 DECIMAL(19, 8),
		Projection02 DECIMAL(19, 8),
		Projection03 DECIMAL(19, 8),
		Projection04 DECIMAL(19, 8),
		Projection05 DECIMAL(19, 8),
		Projection06 DECIMAL(19, 8),
		Projection07 DECIMAL(19, 8),
		Projection08 DECIMAL(19, 8),
		Projection09 DECIMAL(19, 8),
		Projection10 DECIMAL(19, 8),
		Projection11 DECIMAL(19, 8),
		Projection12 DECIMAL(19, 8),
		ProjectionTotal DECIMAL(19, 8)
	)
	
	-- Projection
	INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID,	ServiceEntityID,
			MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
			BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, 
			Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12, ProjectionTotal)
	SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID,	fcv.ServiceEntityID,
			fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID,
			fcv.BillingCPTID, 34 AS UnitTypeID, 12 AS TimeClassID, @ProjectionYear AS FiscalYearID, 
			fcv.ProjectionDollarsAdjusted01, fcv.ProjectionDollarsAdjusted02, fcv.ProjectionDollarsAdjusted03, fcv.ProjectionDollarsAdjusted04, fcv.ProjectionDollarsAdjusted05, fcv.ProjectionDollarsAdjusted06, fcv.ProjectionDollarsAdjusted07, fcv.ProjectionDollarsAdjusted08, fcv.ProjectionDollarsAdjusted09, fcv.ProjectionDollarsAdjusted10, fcv.ProjectionDollarsAdjusted11, fcv.ProjectionDollarsAdjusted12, fcv.ProjectionDollarsAdjustedTotal
	FROM fp.ChargeVolume fcv
		INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID
	WHERE fcv.BudgetConfigID  = @BudgetConfigID

	CREATE CLUSTERED INDEX inx_src ON #source (
		ChargeVolumeID,
		BudgetConfigID,
		EntityID,
		DepartmentID,
		PatientClassID,
		ChargeCodeID,
		ServiceLineID,
		AgeCohortID,
		MedicalSurgicalID,
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		UnitTypeID,
		TimeClassID,
		FiscalYearID
	) with (data_compression = page)			
			
	;WITH TGT AS 
	(
		SELECT 
			ChargeVolumeID,
			BudgetConfigID,
			EntityID,
			FRS.DepartmentID,
			PatientClassID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			ServiceEntityID,
			MSDRGID,
			UBRevCodeID,
			PrimaryCPTID,
			ServiceProviderID,
			ServiceProviderSpecialtyID,
			PerformingProviderID,
			PerformingProviderSpecialtyID,
			BillingCPTID,
			UnitTypeID,
			Projection01, 
			Projection02, 
			Projection03, 
			Projection04, 
			Projection05, 
			Projection06, 
			Projection07, 
			Projection08, 
			Projection09, 
			Projection10, 
			Projection11, 
			Projection12, 
			ProjectionTotal
		FROM [fp].[FactReportChargeVolume] FRS
			INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)
			MERGE TGT AS target
			USING #source AS source
				ON (
							target.ChargeVolumeID				 = source.ChargeVolumeID
						AND	target.BudgetConfigID				 = source.BudgetConfigID
						AND target.EntityID						 = source.EntityID
						AND target.DepartmentID					 = source.DepartmentID
						AND target.PatientClassID				 = source.PatientClassID
						AND target.ChargeCodeID					 = source.ChargeCodeID
						AND target.ServiceLineID				 = source.ServiceLineID
						AND target.AgeCohortID					 = source.AgeCohortID
						AND target.MedicalSurgicalID			 = source.MedicalSurgicalID
						AND target.ServiceEntityID				 = source.ServiceEntityID
						AND target.MSDRGID						 = source.MSDRGID
						AND target.UBRevCodeID					 = source.UBRevCodeID
						AND target.PrimaryCPTID					 = source.PrimaryCPTID
						AND target.ServiceProviderID			 = source.ServiceProviderID
						AND target.ServiceProviderSpecialtyID    = source.ServiceProviderSpecialtyID
						AND target.PerformingProviderID          = source.PerformingProviderID
						AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID
						AND target.BillingCPTID					 = source.BillingCPTID
						AND target.UnitTypeID					 = source.UnitTypeID

						)
			WHEN MATCHED AND (
						  target.Projection01 <> source.Projection01
					   OR target.Projection02 <> source.Projection02
					   OR target.Projection03 <> source.Projection03
					   OR target.Projection04 <> source.Projection04
					   OR target.Projection05 <> source.Projection05
					   OR target.Projection06 <> source.Projection06
					   OR target.Projection07 <> source.Projection07
					   OR target.Projection08 <> source.Projection08
					   OR target.Projection09 <> source.Projection09
					   OR target.Projection10 <> source.Projection10
					   OR target.Projection11 <> source.Projection11
					   OR target.Projection12 <> source.Projection12
					   OR target.ProjectionTotal <> source.ProjectionTotal)
				THEN
					UPDATE SET
					target.Projection01 = ISNULL(source.Projection01, 0),
					target.Projection02 = ISNULL(source.Projection02, 0),
					target.Projection03 = ISNULL(source.Projection03, 0),
					target.Projection04 = ISNULL(source.Projection04, 0),
					target.Projection05 = ISNULL(source.Projection05, 0),
					target.Projection06 = ISNULL(source.Projection06, 0),
					target.Projection07 = ISNULL(source.Projection07, 0),
					target.Projection08 = ISNULL(source.Projection08, 0),
					target.Projection09 = ISNULL(source.Projection09, 0),
					target.Projection10 = ISNULL(source.Projection10, 0),
					target.Projection11 = ISNULL(source.Projection11, 0),
					target.Projection12 = ISNULL(source.Projection12, 0),
					target.ProjectionTotal = ISNULL(source.ProjectionTotal, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
								ChargeVolumeID,
								BudgetConfigID,
								EntityID,
								DepartmentID,
								PatientClassID,
								ChargeCodeID,
								ServiceLineID,
								AgeCohortID,
								MedicalSurgicalID,
								ServiceEntityID,
								MSDRGID,
								UBRevCodeID,
								PrimaryCPTID,
								ServiceProviderID,
								ServiceProviderSpecialtyID,
								PerformingProviderID,
								PerformingProviderSpecialtyID,
								BillingCPTID,
								UnitTypeID,
								Projection01, 
								Projection02, 
								Projection03, 
								Projection04, 
								Projection05, 
								Projection06, 
								Projection07, 
								Projection08, 
								Projection09, 
								Projection10, 
								Projection11, 
								Projection12, 
								ProjectionTotal
						)
					VALUES (
							source.ChargeVolumeID,
							source.BudgetConfigID,
							source.EntityID,
							source.DepartmentID,
							source.PatientClassID,
							source.ChargeCodeID,
							source.ServiceLineID,
							source.AgeCohortID,
							source.MedicalSurgicalID,
							source.ServiceEntityID,
							source.MSDRGID,
							source.UBRevCodeID,
							source.PrimaryCPTID,
							source.ServiceProviderID,
							source.ServiceProviderSpecialtyID,
							source.PerformingProviderID,
							source.PerformingProviderSpecialtyID,
							source.BillingCPTID,
							source.UnitTypeID,
							ISNULL(Projection01, 0), 
							ISNULL(Projection02, 0), 
							ISNULL(Projection03, 0), 
							ISNULL(Projection04, 0), 
							ISNULL(Projection05, 0), 
							ISNULL(Projection06, 0), 
							ISNULL(Projection07, 0), 
							ISNULL(Projection08, 0), 
							ISNULL(Projection09, 0), 
							ISNULL(Projection10, 0), 
							ISNULL(Projection11, 0), 
							ISNULL(Projection12, 0), 
							ISNULL(ProjectionTotal, 0)
						);

END
GO


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

-- fp.procPopulateReportFactChargeVolume_Units_Budget
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2020-03-11  MY          JAZZ-16618      Initial
** 2    2020-02-14  MY          JAZZ-33542      Add Targeting
** 3	2023-03-21	MY		    JAZZ-49993		Update reporting to support new data model
** 4	2023-06-12	MY		    JAZZ-54952		Update to new column names
*********************************************************************/
CREATE   PROCEDURE fp.procPopulateReportFactChargeVolume_Units_Budget (
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN	

	EXEC [dbo].[procSysDropTempTable] '#source'
	EXEC [dbo].[procSysDropTempTable] '#recordsUpdated'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	DECLARE @BudgetYear INT;
	SET @BudgetYear = (SELECT FiscalYearID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID);
	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END

	CREATE TABLE #source (
		ChargeVolumeID INT,
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		PatientClassID INT,
		ChargeCodeID INT,
		ServiceLineID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		ServiceEntityID INT,
		MSDRGID INT,
		UBRevCodeID INT,
		PrimaryCPTID INT,
		ServiceProviderID INT,
		ServiceProviderSpecialtyID INT,
		PerformingProviderID INT,
		PerformingProviderSpecialtyID INT,
		BillingCPTID INT,
		UnitTypeID INT,
		TimeClassID INT,
		FiscalMonthID INT,
		FiscalYearID INT,
		OriginalValue01 DECIMAL(19, 8),
		OriginalValue02 DECIMAL(19, 8),
		OriginalValue03 DECIMAL(19, 8),
		OriginalValue04 DECIMAL(19, 8),
		OriginalValue05 DECIMAL(19, 8),
		OriginalValue06 DECIMAL(19, 8),
		OriginalValue07 DECIMAL(19, 8),
		OriginalValue08 DECIMAL(19, 8),
		OriginalValue09 DECIMAL(19, 8),
		OriginalValue10 DECIMAL(19, 8),
		OriginalValue11 DECIMAL(19, 8),
		OriginalValue12 DECIMAL(19, 8),
		OriginalValueTotal DECIMAL(19, 8),
		Value01 DECIMAL(19, 8),
		Value02 DECIMAL(19, 8),
		Value03 DECIMAL(19, 8),
		Value04 DECIMAL(19, 8),
		Value05 DECIMAL(19, 8),
		Value06 DECIMAL(19, 8),
		Value07 DECIMAL(19, 8),
		Value08 DECIMAL(19, 8),
		Value09 DECIMAL(19, 8),
		Value10 DECIMAL(19, 8),
		Value11 DECIMAL(19, 8),
		Value12 DECIMAL(19, 8),
		ValueTotal DECIMAL(19, 8),
		ManagerValue01 DECIMAL(19, 8),
		ManagerValue02 DECIMAL(19, 8),
		ManagerValue03 DECIMAL(19, 8),
		ManagerValue04 DECIMAL(19, 8),
		ManagerValue05 DECIMAL(19, 8),
		ManagerValue06 DECIMAL(19, 8),
		ManagerValue07 DECIMAL(19, 8),
		ManagerValue08 DECIMAL(19, 8),
		ManagerValue09 DECIMAL(19, 8),
		ManagerValue10 DECIMAL(19, 8),
		ManagerValue11 DECIMAL(19, 8),
		ManagerValue12 DECIMAL(19, 8),
		ManagerValueTotal DECIMAL(19, 8)
	)
	
	-- Budget
	INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID,	ServiceEntityID,
			MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
			BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, 
			OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12, OriginalValueTotal, 
			Value01, Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12, ValueTotal, 
			ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12, ManagerValueTotal)
	SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID,	fcv.ServiceEntityID,
			fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID,
			fcv.BillingCPTID, fcv.UnitTypeID, 2 AS TimeClassID, @BudgetYear AS FiscalYearID, 
			fcv.InitialBudget01, fcv.InitialBudget02, fcv.InitialBudget03, fcv.InitialBudget04, fcv.InitialBudget05, fcv.InitialBudget06, fcv.InitialBudget07, fcv.InitialBudget08, fcv.InitialBudget09, fcv.InitialBudget10, fcv.InitialBudget11, fcv.InitialBudget12, fcv.InitialBudgetTotal, 
			fcv.TargetAdjusted01, fcv.TargetAdjusted02, fcv.TargetAdjusted03, fcv.TargetAdjusted04, fcv.TargetAdjusted05, fcv.TargetAdjusted06, fcv.TargetAdjusted07, fcv.TargetAdjusted08, fcv.TargetAdjusted09, fcv.TargetAdjusted10, fcv.TargetAdjusted11, fcv.TargetAdjusted12, fcv.TargetAdjustedTotal, 
			fcv.BudgetAdjusted01, fcv.BudgetAdjusted02, fcv.BudgetAdjusted03, fcv.BudgetAdjusted04, fcv.BudgetAdjusted05, fcv.BudgetAdjusted06, fcv.BudgetAdjusted07, fcv.BudgetAdjusted08, fcv.BudgetAdjusted09, fcv.BudgetAdjusted10, fcv.BudgetAdjusted11, fcv.BudgetAdjusted12, fcv.BudgetAdjustedTotal
	FROM fp.ChargeVolume fcv
		INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID
	WHERE fcv.BudgetConfigID  = @BudgetConfigID
		AND fcv.UnitTypeID = 145
			
	CREATE CLUSTERED INDEX inx_src ON #source ( 
		ChargeVolumeID,
		BudgetConfigID,
		EntityID,
		DepartmentID,
		PatientClassID,
		ChargeCodeID,
		ServiceLineID,
		AgeCohortID,
		MedicalSurgicalID,
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		UnitTypeID,
		TimeClassID,
		FiscalYearID 
	)  with (data_compression = page)
			
	;WITH TGT AS 
	(
		SELECT 
			ChargeVolumeID,
			BudgetConfigID,
			EntityID,
			FRS.DepartmentID,
			PatientClassID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			ServiceEntityID,
			MSDRGID,
			UBRevCodeID,
			PrimaryCPTID,
			ServiceProviderID,
			ServiceProviderSpecialtyID,
			PerformingProviderID,
			PerformingProviderSpecialtyID,
			BillingCPTID,
			UnitTypeID,
			InitialBudget01, 
			InitialBudget02, 
			InitialBudget03, 
			InitialBudget04, 
			InitialBudget05, 
			InitialBudget06, 
			InitialBudget07, 
			InitialBudget08, 
			InitialBudget09, 
			InitialBudget10, 
			InitialBudget11, 
			InitialBudget12, 
			InitialBudgetTotal, 
			Target01, 
			Target02, 
			Target03, 
			Target04, 
			Target05, 
			Target06, 
			Target07, 
			Target08, 
			Target09, 
			Target10, 
			Target11, 
			Target12, 
			TargetTotal, 
			Budget01, 
			Budget02, 
			Budget03, 
			Budget04, 
			Budget05, 
			Budget06, 
			Budget07, 
			Budget08, 
			Budget09, 
			Budget10, 
			Budget11, 
			Budget12, 
			BudgetTotal
		FROM [fp].[FactReportChargeVolume] FRS
			INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)
			MERGE TGT AS target
			USING #source AS source
				ON (
							target.ChargeVolumeID				 = source.ChargeVolumeID
						AND	target.BudgetConfigID				 = source.BudgetConfigID
						AND target.EntityID						 = source.EntityID
						AND target.DepartmentID					 = source.DepartmentID
						AND target.PatientClassID				 = source.PatientClassID
						AND target.ChargeCodeID					 = source.ChargeCodeID
						AND target.ServiceLineID				 = source.ServiceLineID
						AND target.AgeCohortID					 = source.AgeCohortID
						AND target.MedicalSurgicalID			 = source.MedicalSurgicalID
						AND target.ServiceEntityID				 = source.ServiceEntityID
						AND target.MSDRGID						 = source.MSDRGID
						AND target.UBRevCodeID					 = source.UBRevCodeID
						AND target.PrimaryCPTID					 = source.PrimaryCPTID
						AND target.ServiceProviderID			 = source.ServiceProviderID
						AND target.ServiceProviderSpecialtyID    = source.ServiceProviderSpecialtyID
						AND target.PerformingProviderID          = source.PerformingProviderID
						AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID
						AND target.BillingCPTID					 = source.BillingCPTID
						AND target.UnitTypeID					 = source.UnitTypeID

						)
			WHEN MATCHED AND (
					      target.InitialBudget01 <> source.OriginalValue01
					   OR target.InitialBudget02 <> source.OriginalValue02
					   OR target.InitialBudget03 <> source.OriginalValue03
					   OR target.InitialBudget04 <> source.OriginalValue04
					   OR target.InitialBudget05 <> source.OriginalValue05
					   OR target.InitialBudget06 <> source.OriginalValue06
					   OR target.InitialBudget07 <> source.OriginalValue07
					   OR target.InitialBudget08 <> source.OriginalValue08
					   OR target.InitialBudget09 <> source.OriginalValue09
					   OR target.InitialBudget10 <> source.OriginalValue10
					   OR target.InitialBudget11 <> source.OriginalValue11
					   OR target.InitialBudget12 <> source.OriginalValue12
					   OR target.InitialBudgetTotal <> source.OriginalValueTotal
					   OR target.Target01 <> source.Value01
					   OR target.Target02 <> source.Value02
					   OR target.Target03 <> source.Value03
					   OR target.Target04 <> source.Value04
					   OR target.Target05 <> source.Value05
					   OR target.Target06 <> source.Value06
					   OR target.Target07 <> source.Value07
					   OR target.Target08 <> source.Value08
					   OR target.Target09 <> source.Value09
					   OR target.Target10 <> source.Value10
					   OR target.Target11 <> source.Value11
					   OR target.Target12 <> source.Value12
					   OR target.TargetTotal <> source.ValueTotal
					   OR target.Budget01 <> source.ManagerValue01
					   OR target.Budget02 <> source.ManagerValue02
					   OR target.Budget03 <> source.ManagerValue03
					   OR target.Budget04 <> source.ManagerValue04
					   OR target.Budget05 <> source.ManagerValue05
					   OR target.Budget06 <> source.ManagerValue06
					   OR target.Budget07 <> source.ManagerValue07
					   OR target.Budget08 <> source.ManagerValue08
					   OR target.Budget09 <> source.ManagerValue09
					   OR target.Budget10 <> source.ManagerValue10
					   OR target.Budget11 <> source.ManagerValue11
					   OR target.Budget12 <> source.ManagerValue12
					   OR target.BudgetTotal <> source.ManagerValueTotal)
				THEN
					UPDATE SET
					target.InitialBudget01 = ISNULL(source.OriginalValue01, 0),
					target.InitialBudget02 = ISNULL(source.OriginalValue02, 0),
					target.InitialBudget03 = ISNULL(source.OriginalValue03, 0),
					target.InitialBudget04 = ISNULL(source.OriginalValue04, 0),
					target.InitialBudget05 = ISNULL(source.OriginalValue05, 0),
					target.InitialBudget06 = ISNULL(source.OriginalValue06, 0),
					target.InitialBudget07 = ISNULL(source.OriginalValue07, 0),
					target.InitialBudget08 = ISNULL(source.OriginalValue08, 0),
					target.InitialBudget09 = ISNULL(source.OriginalValue09, 0),
					target.InitialBudget10 = ISNULL(source.OriginalValue10, 0),
					target.InitialBudget11 = ISNULL(source.OriginalValue11, 0),
					target.InitialBudget12 = ISNULL(source.OriginalValue12, 0),
					target.InitialBudgetTotal = ISNULL(source.OriginalValueTotal, 0),
					target.Target01 = ISNULL(source.Value01, 0),
					target.Target02 = ISNULL(source.Value02, 0),
					target.Target03 = ISNULL(source.Value03, 0),
					target.Target04 = ISNULL(source.Value04, 0),
					target.Target05 = ISNULL(source.Value05, 0),
					target.Target06 = ISNULL(source.Value06, 0),
					target.Target07 = ISNULL(source.Value07, 0),
					target.Target08 = ISNULL(source.Value08, 0),
					target.Target09 = ISNULL(source.Value09, 0),
					target.Target10 = ISNULL(source.Value10, 0),
					target.Target11 = ISNULL(source.Value11, 0),
					target.Target12 = ISNULL(source.Value12, 0),
					target.TargetTotal = ISNULL(source.ValueTotal, 0),
					target.Budget01 = ISNULL(source.ManagerValue01, 0),
					target.Budget02 = ISNULL(source.ManagerValue02, 0),
					target.Budget03 = ISNULL(source.ManagerValue03, 0),
					target.Budget04 = ISNULL(source.ManagerValue04, 0),
					target.Budget05 = ISNULL(source.ManagerValue05, 0),
					target.Budget06 = ISNULL(source.ManagerValue06, 0),
					target.Budget07 = ISNULL(source.ManagerValue07, 0),
					target.Budget08 = ISNULL(source.ManagerValue08, 0),
					target.Budget09 = ISNULL(source.ManagerValue09, 0),
					target.Budget10 = ISNULL(source.ManagerValue10, 0),
					target.Budget11 = ISNULL(source.ManagerValue11, 0),
					target.Budget12 = ISNULL(source.ManagerValue12, 0),
					target.BudgetTotal = ISNULL(source.ManagerValueTotal, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
								ChargeVolumeID,
								BudgetConfigID,
								EntityID,
								DepartmentID,
								PatientClassID,
								ChargeCodeID,
								ServiceLineID,
								AgeCohortID,
								MedicalSurgicalID,
								ServiceEntityID,
								MSDRGID,
								UBRevCodeID,
								PrimaryCPTID,
								ServiceProviderID,
								ServiceProviderSpecialtyID,
								PerformingProviderID,
								PerformingProviderSpecialtyID,
								BillingCPTID,
								UnitTypeID,
								InitialBudget01, 
								InitialBudget02, 
								InitialBudget03, 
								InitialBudget04, 
								InitialBudget05, 
								InitialBudget06, 
								InitialBudget07, 
								InitialBudget08, 
								InitialBudget09, 
								InitialBudget10, 
								InitialBudget11, 
								InitialBudget12, 
								InitialBudgetTotal, 
								Target01, 
								Target02, 
								Target03, 
								Target04, 
								Target05, 
								Target06, 
								Target07, 
								Target08, 
								Target09, 
								Target10, 
								Target11, 
								Target12, 
								TargetTotal, 
								Budget01, 
								Budget02, 
								Budget03, 
								Budget04, 
								Budget05, 
								Budget06, 
								Budget07, 
								Budget08, 
								Budget09, 
								Budget10, 
								Budget11, 
								Budget12, 
								BudgetTotal
						)
					VALUES (
							source.ChargeVolumeID,
							source.BudgetConfigID,
							source.EntityID,
							source.DepartmentID,
							source.PatientClassID,
							source.ChargeCodeID,
							source.ServiceLineID,
							source.AgeCohortID,
							source.MedicalSurgicalID,
							source.ServiceEntityID,
							source.MSDRGID,
							source.UBRevCodeID,
							source.PrimaryCPTID,
							source.ServiceProviderID,
							source.ServiceProviderSpecialtyID,
							source.PerformingProviderID,
							source.PerformingProviderSpecialtyID,
							source.BillingCPTID,
							source.UnitTypeID,
							ISNULL(OriginalValue01, 0), 
							ISNULL(OriginalValue02, 0), 
							ISNULL(OriginalValue03, 0), 
							ISNULL(OriginalValue04, 0), 
							ISNULL(OriginalValue05, 0), 
							ISNULL(OriginalValue06, 0), 
							ISNULL(OriginalValue07, 0), 
							ISNULL(OriginalValue08, 0), 
							ISNULL(OriginalValue09, 0), 
							ISNULL(OriginalValue10, 0), 
							ISNULL(OriginalValue11, 0), 
							ISNULL(OriginalValue12, 0), 
							ISNULL(OriginalValueTotal, 0), 
							ISNULL(Value01, 0), 
							ISNULL(Value02, 0), 
							ISNULL(Value03, 0), 
							ISNULL(Value04, 0), 
							ISNULL(Value05, 0), 
							ISNULL(Value06, 0), 
							ISNULL(Value07, 0), 
							ISNULL(Value08, 0), 
							ISNULL(Value09, 0), 
							ISNULL(Value10, 0), 
							ISNULL(Value11, 0), 
							ISNULL(Value12, 0), 
							ISNULL(ValueTotal, 0), 
							ISNULL(ManagerValue01, 0), 
							ISNULL(ManagerValue02, 0), 
							ISNULL(ManagerValue03, 0), 
							ISNULL(ManagerValue04, 0), 
							ISNULL(ManagerValue05, 0), 
							ISNULL(ManagerValue06, 0), 
							ISNULL(ManagerValue07, 0), 
							ISNULL(ManagerValue08, 0), 
							ISNULL(ManagerValue09, 0), 
							ISNULL(ManagerValue10, 0), 
							ISNULL(ManagerValue11, 0), 
							ISNULL(ManagerValue12, 0), 
							ISNULL(ManagerValueTotal, 0)
						);
		-- NOTE: We are not deleting for performance reasons, otherwise we would have to join the report information on what's being passed in
		-- If this ends up being a problem we can add it and work with the performance aspect of it. This is also why when sampling charge volume
		-- or changing the active configuration, it wipes the report table to begin with and waits for it to be refreshed.
END
GO


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

-- fp.procPopulateReportFactChargeVolume_Units_Projection
/*********************************************************************
** Change History
**********************************************************************
** CID  Date        Author      WI				Description
** 1    2020-03-11  MY          JAZZ-16618      Initial
** 2    2020-02-14  MY          JAZZ-33542      Add Targeting
** 3	2023-03-21	MY		    JAZZ-49993		Update reporting to support new data model
** 4	2023-06-12	MY		    JAZZ-54952		Update to new columns
*********************************************************************/
CREATE   PROCEDURE fp.procPopulateReportFactChargeVolume_Units_Projection (
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN	

	EXEC [dbo].[procSysDropTempTable] '#source'
	EXEC [dbo].[procSysDropTempTable] '#recordsUpdated'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	DECLARE @ProjectionYear INT;
	SET @ProjectionYear = (SELECT FiscalYearID - 1 FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID);
		
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID  = @BudgetConfigID	
	END

	CREATE TABLE #source (
		ChargeVolumeID INT,
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		PatientClassID INT,
		ChargeCodeID INT,
		ServiceLineID INT,
		AgeCohortID INT,
		MedicalSurgicalID INT,
		ServiceEntityID INT,
		MSDRGID INT,
		UBRevCodeID INT,
		PrimaryCPTID INT,
		ServiceProviderID INT,
		ServiceProviderSpecialtyID INT,
		PerformingProviderID INT,
		PerformingProviderSpecialtyID INT,
		BillingCPTID INT,
		UnitTypeID INT,
		TimeClassID INT,
		FiscalMonthID INT,
		FiscalYearID INT,
		Projection01 DECIMAL(19, 8),
		Projection02 DECIMAL(19, 8),
		Projection03 DECIMAL(19, 8),
		Projection04 DECIMAL(19, 8),
		Projection05 DECIMAL(19, 8),
		Projection06 DECIMAL(19, 8),
		Projection07 DECIMAL(19, 8),
		Projection08 DECIMAL(19, 8),
		Projection09 DECIMAL(19, 8),
		Projection10 DECIMAL(19, 8),
		Projection11 DECIMAL(19, 8),
		Projection12 DECIMAL(19, 8),
		ProjectionTotal DECIMAL(19, 8)
	)
	
	-- Projection
	INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID,	ServiceEntityID,
			MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID,
			BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, 
			Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12, ProjectionTotal)
	SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID,	fcv.ServiceEntityID,
			fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID,
			fcv.BillingCPTID, fcv.UnitTypeID, 12 AS TimeClassID, @ProjectionYear AS FiscalYearID, 
			fcv.ProjectionAdjusted01, fcv.ProjectionAdjusted02, fcv.ProjectionAdjusted03, fcv.ProjectionAdjusted04, fcv.ProjectionAdjusted05, fcv.ProjectionAdjusted06, fcv.ProjectionAdjusted07, fcv.ProjectionAdjusted08, fcv.ProjectionAdjusted09, fcv.ProjectionAdjusted10, fcv.ProjectionAdjusted11, fcv.ProjectionAdjusted12, fcv.ProjectionAdjustedTotal
	FROM fp.ChargeVolume fcv
		INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID
	WHERE fcv.BudgetConfigID  = @BudgetConfigID
		AND fcv.UnitTypeID = 145
		
	CREATE CLUSTERED INDEX inx_src ON #source ( 
		ChargeVolumeID,
		BudgetConfigID,
		EntityID,
		DepartmentID,
		PatientClassID,
		ChargeCodeID,
		ServiceLineID,
		AgeCohortID,
		MedicalSurgicalID,
		ServiceEntityID,
		MSDRGID,
		UBRevCodeID,
		PrimaryCPTID,
		ServiceProviderID,
		ServiceProviderSpecialtyID,
		PerformingProviderID,
		PerformingProviderSpecialtyID,
		BillingCPTID,
		UnitTypeID,
		TimeClassID,
		FiscalYearID 
	)  with (data_compression = page)
			
	;WITH TGT AS 
	(
		SELECT 
			ChargeVolumeID,
			BudgetConfigID,
			EntityID,
			FRS.DepartmentID,
			PatientClassID,
			ChargeCodeID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
			ServiceEntityID,
			MSDRGID,
			UBRevCodeID,
			PrimaryCPTID,
			ServiceProviderID,
			ServiceProviderSpecialtyID,
			PerformingProviderID,
			PerformingProviderSpecialtyID,
			BillingCPTID,
			UnitTypeID,
			Projection01, 
			Projection02, 
			Projection03, 
			Projection04, 
			Projection05, 
			Projection06, 
			Projection07, 
			Projection08, 
			Projection09, 
			Projection10, 
			Projection11, 
			Projection12, 
			ProjectionTotal
		FROM [fp].[FactReportChargeVolume] FRS
			INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)
			MERGE TGT AS target
			USING #source AS source
				ON (
							target.ChargeVolumeID				 = source.ChargeVolumeID
						AND	target.BudgetConfigID				 = source.BudgetConfigID
						AND target.EntityID						 = source.EntityID
						AND target.DepartmentID					 = source.DepartmentID
						AND target.PatientClassID				 = source.PatientClassID
						AND target.ChargeCodeID					 = source.ChargeCodeID
						AND target.ServiceLineID				 = source.ServiceLineID
						AND target.AgeCohortID					 = source.AgeCohortID
						AND target.MedicalSurgicalID			 = source.MedicalSurgicalID
						AND target.ServiceEntityID				 = source.ServiceEntityID
						AND target.MSDRGID						 = source.MSDRGID
						AND target.UBRevCodeID					 = source.UBRevCodeID
						AND target.PrimaryCPTID					 = source.PrimaryCPTID
						AND target.ServiceProviderID			 = source.ServiceProviderID
						AND target.ServiceProviderSpecialtyID    = source.ServiceProviderSpecialtyID
						AND target.PerformingProviderID          = source.PerformingProviderID
						AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID
						AND target.BillingCPTID					 = source.BillingCPTID
						AND target.UnitTypeID					 = source.UnitTypeID

						)
			WHEN MATCHED AND (
						  target.Projection01 <> source.Projection01
					   OR target.Projection02 <> source.Projection02
					   OR target.Projection03 <> source.Projection03
					   OR target.Projection04 <> source.Projection04
					   OR target.Projection05 <> source.Projection05
					   OR target.Projection06 <> source.Projection06
					   OR target.Projection07 <> source.Projection07
					   OR target.Projection08 <> source.Projection08
					   OR target.Projection09 <> source.Projection09
					   OR target.Projection10 <> source.Projection10
					   OR target.Projection11 <> source.Projection11
					   OR target.Projection12 <> source.Projection12
					   OR target.ProjectionTotal <> source.ProjectionTotal)
				THEN
					UPDATE SET
					target.Projection01 = ISNULL(source.Projection01, 0),
					target.Projection02 = ISNULL(source.Projection02, 0),
					target.Projection03 = ISNULL(source.Projection03, 0),
					target.Projection04 = ISNULL(source.Projection04, 0),
					target.Projection05 = ISNULL(source.Projection05, 0),
					target.Projection06 = ISNULL(source.Projection06, 0),
					target.Projection07 = ISNULL(source.Projection07, 0),
					target.Projection08 = ISNULL(source.Projection08, 0),
					target.Projection09 = ISNULL(source.Projection09, 0),
					target.Projection10 = ISNULL(source.Projection10, 0),
					target.Projection11 = ISNULL(source.Projection11, 0),
					target.Projection12 = ISNULL(source.Projection12, 0),
					target.ProjectionTotal = ISNULL(source.ProjectionTotal, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
								ChargeVolumeID,
								BudgetConfigID,
								EntityID,
								DepartmentID,
								PatientClassID,
								ChargeCodeID,
								ServiceLineID,
								AgeCohortID,
								MedicalSurgicalID,
								ServiceEntityID,
								MSDRGID,
								UBRevCodeID,
								PrimaryCPTID,
								ServiceProviderID,
								ServiceProviderSpecialtyID,
								PerformingProviderID,
								PerformingProviderSpecialtyID,
								BillingCPTID,
								UnitTypeID,
								Projection01, 
								Projection02, 
								Projection03, 
								Projection04, 
								Projection05, 
								Projection06, 
								Projection07, 
								Projection08, 
								Projection09, 
								Projection10, 
								Projection11, 
								Projection12, 
								ProjectionTotal
						)
					VALUES (
							source.ChargeVolumeID,
							source.BudgetConfigID,
							source.EntityID,
							source.DepartmentID,
							source.PatientClassID,
							source.ChargeCodeID,
							source.ServiceLineID,
							source.AgeCohortID,
							source.MedicalSurgicalID,
							source.ServiceEntityID,
							source.MSDRGID,
							source.UBRevCodeID,
							source.PrimaryCPTID,
							source.ServiceProviderID,
							source.ServiceProviderSpecialtyID,
							source.PerformingProviderID,
							source.PerformingProviderSpecialtyID,
							source.BillingCPTID,
							source.UnitTypeID,
							ISNULL(Projection01, 0), 
							ISNULL(Projection02, 0), 
							ISNULL(Projection03, 0), 
							ISNULL(Projection04, 0), 
							ISNULL(Projection05, 0), 
							ISNULL(Projection06, 0), 
							ISNULL(Projection07, 0), 
							ISNULL(Projection08, 0), 
							ISNULL(Projection09, 0), 
							ISNULL(Projection10, 0), 
							ISNULL(Projection11, 0), 
							ISNULL(Projection12, 0), 
							ISNULL(ProjectionTotal, 0)
						);
		-- NOTE: We are not deleting for performance reasons, otherwise we would have to join the report information on what's being passed in
		-- If this ends up being a problem we can add it and work with the performance aspect of it. This is also why when sampling charge volume
		-- or changing the active configuration, it wipes the report table to begin with and waits for it to be refreshed.
END
GO


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

-- fp.procPopulateServiceLineEncounterPayorGroupMix
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2021-09-15	MY		JAZZ-25836	Initial
** 2	2022-09-19	BK		JAZZ-42503	Add distinct to select from mapping table
** 3	2023-02-24	BW		JAZZ-48306	Updated for new data model, use [fp].[ServiceLineEncounter]
** 4	6-27-2023   MY      JAZZ-56923	Adding Service Line into the SLE to Charge payor mix calc
** 5	2024-01-11	AO		JAZZ-64530	Data transfer for SLE is based on selected Model in Plan Config 
** 6	2024-04-17	MY		JAZZ-70660	Updating payor group charge mix temporary workaround
** 7	2024-04-18	MY		JAZZ-70774	Remove temporary workaround
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateServiceLineEncounterPayorGroupMix]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
WITH RECOMPILE
AS
BEGIN	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter;
	IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass;
	IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup;
	IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues;
	IF OBJECT_ID('tempdb..#mixesRanked') IS NOT NULL DROP TABLE #mixesRanked;
	IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix;
	
	-- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc
	DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0)

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE EntityGroupConfigID  = @EntityGroupConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
	
	-- Translate the CV Departments to Encounter dimensionality
	CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT);
	INSERT INTO #TargetingFilter (EntityID, ServiceLineID)
	SELECT DISTINCT slecvm.EntityID, ServiceLineID
	FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm
		INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID
	WHERE slecvm.BudgetConfigID = @BudgetConfigID
		
	IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table
	BEGIN 
		SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments
	END
	
	-- We no longer need the charge volume departments, so we can drop it here.
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix (
		[BudgetConfigID] [int] NOT NULL DEFAULT(0),
		[EntityGroupConfigID] [int] NOT NULL DEFAULT(0),
		[EntityID] [int] NOT NULL DEFAULT(0),
		[PatientClassID] [int] NOT NULL DEFAULT(0),
		[ServiceLineID] [int] NOT NULL DEFAULT(0),
		[PayorGroupID] [int] NOT NULL DEFAULT(0),
		[TimeClassID] [int] NOT NULL DEFAULT(0),
		[MixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0)
	)
	
	-- Find the total values for each payor group
	SELECT fsle.EntityID, fsle.PatientClassID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END AS ServiceLineID, fsle.PayorGroupID, SUM(fsle.BudgetAdjustedTotal) AS BudgetTotal, SUM(fsle.ProjectionAdjustedTotal) AS ProjectionTotal
	INTO #MixByPayorGroup
	FROM fp.ServiceLineEncounter fsle 
		INNER JOIN #TargetingFilter targeting ON fsle.EntityID = targeting.EntityID 
			AND fsle.ServiceLineID = targeting.ServiceLineID
	WHERE fsle.EntityGroupConfigID = @EntityGroupConfigID
	GROUP BY fsle.EntityID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END, fsle.PatientClassID, fsle.PayorGroupID
	
	-- Find the rolled up values by Service Line / Patient Class
	SELECT EntityID, PatientClassID, ServiceLineID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal
	INTO #MixByEntityAndPatientClass
	FROM #MixByPayorGroup
	GROUP BY EntityID, PatientClassID, ServiceLineID
		
	-- Populate Budget
	INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, MixPercentage)
	SELECT
		@BudgetConfigID,
		@EntityGroupConfigID,
		pg.EntityID,
		pg.PatientClassID,
		pg.ServiceLineID,
		pg.PayorGroupID,
		2 AS TimeClassID,
		COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS MixPercentage
	FROM #MixByPayorGroup pg
		INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID 
			AND pg.PatientClassID = roll.PatientClassID
			AND pg.ServiceLineID = roll.ServiceLineID
	
	-- Populate Projection
	INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, MixPercentage)
	SELECT
		@BudgetConfigID,
		@EntityGroupConfigID,
		pg.EntityID,
		pg.PatientClassID,
		pg.ServiceLineID,
		pg.PayorGroupID,
		12 AS TimeClassID,
		CAST(COALESCE(pg.ProjectionTotal / NULLIF(roll.ProjectionTotal, 0), 0) AS DECIMAL(22, 18)) AS MixPercentage
	FROM #MixByPayorGroup pg
		INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID 
			AND pg.PatientClassID = roll.PatientClassID
			AND pg.ServiceLineID = roll.ServiceLineID
	
	---------------------
	-- Rounding
	---------------------
	-- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. 
	-- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. 
	-- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example.
	-- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small
	-- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. 
	--
	-- If this logic is working correctly, the following SQL should return nothing:
	--    SELECT BudgetConfigID, EntityID, PatientClassID, TimeClassID, SUM(MixPercentage)
	--    FROM [fp].[ServiceLineEncounterPayorGroupMix]
	--    GROUP BY BudgetConfigID, EntityID, PatientClassID, TimeClassID
	--    HAVING SUM(MixPercentage) != 1 AND SUM(MixPercentage) != 0
				
	-- First, find the rounding issues
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID, SUM(MixPercentage) AS MixPercentageTotal, 1 - SUM(MixPercentage) AS RoundingDifference
	INTO #DimesionalityWithRoundingIssues
	FROM #Working_ServiceLineEncounterPayorGroupMix
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID
	HAVING SUM(MixPercentage) != 1 AND SUM(MixPercentage) != 0
	
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.TimeClassID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.MixPercentage, rounding.RoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.TimeClassID, mix.EntityID, mix.PatientClassID ORDER BY mix.MixPercentage DESC) AS RowID
	INTO #mixesRanked
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID
			AND mix.TimeClassID = rounding.TimeClassID
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.MixPercentage = mix.MixPercentage + rounding.RoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRanked rounding ON mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID
			AND mix.TimeClassID = rounding.TimeClassID 
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder
		
	IF (@IsDebug = 1)
	BEGIN		
		SELECT '#TargetingFilter', * FROM #TargetingFilter
		SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass
		SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup
		SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues
		SELECT '#mixesRanked', * FROM #mixesRanked
		SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix		
	END ELSE
	BEGIN 
		-- Publish
		;WITH TGT AS   
		(  
			SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.TimeClassID, mix.MixPercentage
			FROM [fp].[ServiceLineEncounterPayorGroupMix] mix  
				INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID
			WHERE mix.EntityGroupConfigID = @EntityGroupConfigID
		)  
  
		MERGE TGT AS target  
		USING #Working_ServiceLineEncounterPayorGroupMix AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID 
			AND target.ServiceLineID = src.ServiceLineID
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.TimeClassID = src.TimeClassID 
		)  
		WHEN MATCHED AND (target.MixPercentage <> src.MixPercentage)  
		THEN  
			UPDATE SET target.MixPercentage = src.MixPercentage
		WHEN NOT MATCHED BY TARGET THEN  
	    	INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, MixPercentage)  
	    	VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.PayorGroupID, src.TimeClassID, src.MixPercentage);

	END

END
GO


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

-- fp.procPopulateServiceLineEncounterPayorGroup_InitialMix
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2021-09-15	MY		JAZZ-25836	Initial
** 2	2022-09-19	BK		JAZZ-42503	Add distinct to select on fp.ServiceLineEncounterChargeVolumeMapping because of ProviderID addition
** 3	2023-02-24	BW		JAZZ-48306	Updated for new data model, use [fp].[ServiceLineEncounter]
** 4	6-27-2023   MY      JAZZ-56923	Adding Service Line into the SLE to Charge payor mix calc
** 5	2024-01-11	AO		JAZZ-64530	Data transfer for SLE is based on selected Model in Plan Config 
** 6	2024-04-17	MY		JAZZ-70660	Updating payor group charge mix temporary workaround
** 7	2024-04-18	MY		JAZZ-70774	Remove temporary workaround
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateServiceLineEncounterPayorGroup_InitialMix]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
WITH RECOMPILE
AS
BEGIN	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter;
	IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass;
	IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup;
	IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues;
	IF OBJECT_ID('tempdb..#mixesRanked') IS NOT NULL DROP TABLE #mixesRanked;
	IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc
	DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE EntityGroupConfigID  = @EntityGroupConfigID
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
	
	-- Translate the CV Departments to Encounter dimensionality
	CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT);
	INSERT INTO #TargetingFilter (EntityID, ServiceLineID)
	SELECT DISTINCT slecvm.EntityID, ServiceLineID
	FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm
		INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID
	WHERE slecvm.BudgetConfigID = @BudgetConfigID
		
	IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table
	BEGIN 
		SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments
	END
	
	-- We no longer need the charge volume departments, so we can drop it here.
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix (
		[BudgetConfigID] [int] NOT NULL DEFAULT(0),
		[EntityGroupConfigID] [int] NOT NULL DEFAULT(0),
		[EntityID] [int] NOT NULL DEFAULT(0),
		[PatientClassID] [int] NOT NULL DEFAULT(0),
		[ServiceLineID] [int] NOT NULL DEFAULT(0),
		[PayorGroupID] [int] NOT NULL DEFAULT(0),
		[TimeClassID] [int] NOT NULL DEFAULT(0),
		[InitialMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0)
	)
	
	-- Find the total values for each payor group
	SELECT fsle.EntityID, fsle.PatientClassID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END AS ServiceLineID, fsle.PayorGroupID, SUM(fsle.InitialBudgetTotal) AS BudgetTotal, SUM(fsle.InitialProjectionTotal) AS ProjectionTotal
	INTO #MixByPayorGroup
	FROM fp.ServiceLineEncounter fsle 
		INNER JOIN #TargetingFilter targeting ON fsle.EntityID = targeting.EntityID AND fsle.ServiceLineID = targeting.ServiceLineID
	WHERE fsle.EntityGroupConfigID = @EntityGroupConfigID
	GROUP BY fsle.EntityID, fsle.PatientClassID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END, fsle.PayorGroupID
	
	-- Find the rolled up values by Service Line / Patient Class
	SELECT EntityID, ServiceLineID, PatientClassID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal
	INTO #MixByEntityAndPatientClass
	FROM #MixByPayorGroup
	GROUP BY EntityID, ServiceLineID, PatientClassID
		
	-- Populate Budget
	INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, InitialMixPercentage)
	SELECT
		@BudgetConfigID,
		@EntityGroupConfigID,
		pg.EntityID,
		pg.PatientClassID,
		pg.ServiceLineID,
		pg.PayorGroupID,
		2 AS TimeClassID,
		COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS InitialMixPercentage
	FROM #MixByPayorGroup pg
		INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID 
			AND pg.PatientClassID = roll.PatientClassID
			AND pg.ServiceLineID = roll.ServiceLineID
	
	-- Populate Projection
	INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, InitialMixPercentage)
	SELECT
		@BudgetConfigID,
		@EntityGroupConfigID,
		pg.EntityID,
		pg.PatientClassID,
		pg.ServiceLineID,
		pg.PayorGroupID,
		12 AS TimeClassID,
		CAST(COALESCE(pg.ProjectionTotal / NULLIF(roll.ProjectionTotal, 0), 0) AS DECIMAL(22, 18)) AS InitialMixPercentage
	FROM #MixByPayorGroup pg
		INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID 
			AND pg.PatientClassID = roll.PatientClassID
			AND pg.ServiceLineID = roll.ServiceLineID
	
	---------------------
	-- Rounding
	---------------------
	-- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. 
	-- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. 
	-- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example.
	-- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small
	-- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. 
	--
	-- If this logic is working correctly, the following SQL should return nothing:
	--    SELECT BudgetConfigID, EntityID, PatientClassID, TimeClassID, SUM(InitialMixPercentage)
	--    FROM [fp].[ServiceLineEncounterPayorGroupMix]
	--    GROUP BY BudgetConfigID, EntityID, PatientClassID, TimeClassID
	--    HAVING SUM(InitialMixPercentage) != 1 AND SUM(InitialMixPercentage) != 0
				
	-- First, find the rounding issues
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID, SUM(InitialMixPercentage) AS MixPercentageTotal, 1 - SUM(InitialMixPercentage) AS RoundingDifference
	INTO #DimesionalityWithRoundingIssues
	FROM #Working_ServiceLineEncounterPayorGroupMix
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID
	HAVING SUM(InitialMixPercentage) != 1 AND SUM(InitialMixPercentage) != 0
	
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.TimeClassID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.InitialMixPercentage, rounding.RoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.TimeClassID, mix.EntityID, mix.PatientClassID ORDER BY mix.InitialMixPercentage DESC) AS RowID
	INTO #mixesRanked
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.TimeClassID = rounding.TimeClassID
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.InitialMixPercentage = mix.InitialMixPercentage + rounding.RoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRanked rounding ON mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.TimeClassID = rounding.TimeClassID 
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder
		
	IF (@IsDebug = 1)
	BEGIN		
		SELECT '#TargetingFilter', * FROM #TargetingFilter
		SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass
		SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup
		SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues
		SELECT '#mixesRanked', * FROM #mixesRanked
		SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix		
	END ELSE
	BEGIN 
		-- Publish
		;WITH TGT AS   
		(  
			SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.TimeClassID, mix.InitialMixPercentage
			FROM [fp].[ServiceLineEncounterPayorGroupMix] mix  
				INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID
			WHERE mix.EntityGroupConfigID = @EntityGroupConfigID
		)  
  
		MERGE TGT AS target  
		USING #Working_ServiceLineEncounterPayorGroupMix AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID  
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.TimeClassID = src.TimeClassID 
		)  
		WHEN MATCHED AND (target.InitialMixPercentage <> src.InitialMixPercentage)  
		THEN  
			UPDATE SET target.InitialMixPercentage = src.InitialMixPercentage
		WHEN NOT MATCHED BY TARGET THEN  
	    	INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, InitialMixPercentage)  
	    	VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.PayorGroupID, src.TimeClassID, src.InitialMixPercentage);
		
	END

END
GO


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

-- fp.procPopulateServiceLineEncounterToChargeVolumePayorMix
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2022-01-10	MY		JAZZ-31850	Initial
** 2	2023-01-17	BK		JAZZ-48267	Update for new data structure
** 3	2023-06-21	MY		JAZZ-55363	Clear out data that is no longer valid
** 4	2024-01-11	AO		JAZZ-64530	Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateServiceLineEncounterToChargeVolumePayorMix]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter;
	IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass;
	IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup;
	IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues;
	IF OBJECT_ID('tempdb..#mixesRankedBudget') IS NOT NULL DROP TABLE #mixesRankedBudget;
	IF OBJECT_ID('tempdb..#mixesRankedProjection') IS NOT NULL DROP TABLE #mixesRankedProjection;
	IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE d.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
	
	-- Translate the CV Departments to Encounter dimensionality
	CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT);
	INSERT INTO #TargetingFilter (EntityID, ServiceLineID)
	SELECT DISTINCT slecvm.EntityID, ServiceLineID
	FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm
		INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID
		INNER JOIN fp.BudgetConfig bc ON slecvm.BudgetConfigID = bc.BudgetConfigID 
		INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID 
		INNER JOIN fp.EntityGroupConfigMapping egcm ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID AND egcm.EntityID = slecvm.EntityID
	WHERE slecvm.BudgetConfigID = @BudgetConfigID
		AND egc.EntityGroupConfigID = @EntityGroupConfigID
		
	IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table
	BEGIN 
		SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments
	END
	
	-- We no longer need the charge volume departments, so we can drop it here.
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix (
		[BudgetConfigID] [int] NOT NULL DEFAULT(0),
		[EntityGroupConfigID] [int] NOT NULL DEFAULT(0),
		[EntityID] [int] NOT NULL DEFAULT(0),
		[PatientClassID] [int] NOT NULL DEFAULT(0),
		[ServiceLineID] [int] NOT NULL DEFAULT(0),
		[AgeCohortID] [int] NOT NULL DEFAULT(0),
		[MedicalSurgicalID] [int] NOT NULL DEFAULT(0),
		[MSDRGID] [int] NOT NULL DEFAULT(0),
		[CPTID] [int] NOT NULL DEFAULT(0),
		[ProviderID] [int] NOT NULL DEFAULT(0),
		[PayorID] [int] NOT NULL DEFAULT(0),
		[PayorGroupID] [int] NOT NULL DEFAULT(0),
		[InitialMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0),
		[ProjectionMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0),
		[BudgetMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0) -- Note: We're not including Target and only using budget becuase they are going to be the same. The only difference would be the spread which wouldn't matter for this case.
	)
	
	-- Find the total values for each payor group
	SELECT sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID, 
		SUM(TargetAdjustedTotal) AS BudgetTotal, -- this was joining on the budget table with BudgetPhaseID = 2, so used Target instead of Budget
		SUM(ProjectionAdjustedTotal) AS ProjectionTotal
	INTO #MixByPayorGroup
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN #TargetingFilter targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
	WHERE sle.EntityGroupConfigID = @EntityGroupConfigID
	GROUP BY sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID
	
	-- Find the rolled up values by Service Line / Patient Class
	SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal
	INTO #MixByEntityAndPatientClass
	FROM #MixByPayorGroup
	GROUP BY EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
		
	-- Populate Budget, Target, and Projection
	INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, 
		MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, ProjectionMixPercentage, BudgetMixPercentage)
	SELECT
		@BudgetConfigID,
		@EntityGroupConfigID,
		pg.EntityID, 
		pg.PatientClassID, 
		pg.ServiceLineID, 
		pg.AgeCohortID, 
		pg.MedicalSurgicalID, 
		pg.MSDRGID, 
		pg.CPTID, 
		pg.ProviderID, 
		pg.PayorID,
		pg.PayorGroupID,
		COALESCE(CAST(pg.ProjectionTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.ProjectionTotal, 0) AS DECIMAL(36, 18)), 0) AS ProjectionMixPercentage,
		COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS BudgetMixPercentage
	FROM #MixByPayorGroup pg
		INNER JOIN #MixByEntityAndPatientClass roll ON 
				pg.EntityID = roll.EntityID 
			AND pg.PatientClassID = roll.PatientClassID
			AND pg.ServiceLineID = roll.ServiceLineID
			AND pg.AgeCohortID = roll.AgeCohortID
			AND pg.MedicalSurgicalID = roll.MedicalSurgicalID
			AND pg.MSDRGID = roll.MSDRGID
			AND pg.CPTID = roll.CPTID
			AND pg.ProviderID = roll.ProviderID
					
	---------------------
	-- Rounding
	---------------------
	-- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. 
	-- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. 
	-- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example.
	-- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small
	-- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. 
	--
	-- If this logic is working correctly, the following SQL should return nothing:
	--    SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetMixPercentage)
	--    FROM [fp].[ServiceLineEncounterToChargePayorMix]
	--    GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
	--    HAVING SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0
				
	-- First, find the rounding issues
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, 
		1 - SUM(ProjectionMixPercentage) AS ProjectionRoundingDifference, 
		1 - SUM(BudgetMixPercentage) AS BudgetRoundingDifference
	INTO #DimesionalityWithRoundingIssues
	FROM #Working_ServiceLineEncounterPayorGroupMix
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
	HAVING (SUM(ProjectionMixPercentage) != 1 AND SUM(ProjectionMixPercentage) != 0) OR (SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0)
	
	-- Check Remainder for Projection
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, 
		mix.PayorID, mix.PayorGroupID, mix.ProjectionMixPercentage, rounding.ProjectionRoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.ProjectionMixPercentage DESC) AS RowID
	INTO #mixesRankedProjection
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.ProjectionMixPercentage = mix.ProjectionMixPercentage + rounding.ProjectionRoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRankedProjection rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
			AND mix.PayorID = rounding.PayorID
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder
		
	-- Check Remainder for Budget
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, 
		mix.PayorID, mix.PayorGroupID, mix.BudgetMixPercentage, rounding.BudgetRoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.BudgetMixPercentage DESC) AS RowID
	INTO #mixesRankedBudget
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.BudgetMixPercentage = mix.BudgetMixPercentage + rounding.BudgetRoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRankedBudget rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
			AND mix.PayorID = rounding.PayorID
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder
		
	IF (@IsDebug = 1)
	BEGIN		
		SELECT '#TargetingFilter', * FROM #TargetingFilter
		SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass
		SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup
		SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues
		SELECT '#mixesRankedProjection', * FROM #mixesRankedProjection
		SELECT '#mixesRankedBudget', * FROM #mixesRankedBudget
		SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix		
	END ELSE
	BEGIN 
		-- Publish
		;WITH TGT AS   
		(  
			SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID,
				mix.ProjectionMixPercentage, BudgetMixPercentage
			FROM [fp].[ServiceLineEncounterToChargePayorMix] mix  
				INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID
			WHERE mix.EntityGroupConfigID = @EntityGroupConfigID
		)  
  
		MERGE TGT AS target  
		USING #Working_ServiceLineEncounterPayorGroupMix AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.AgeCohortID = src.AgeCohortID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.ProviderID = src.ProviderID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN MATCHED AND ((target.ProjectionMixPercentage <> src.ProjectionMixPercentage) OR (target.BudgetMixPercentage <> src.BudgetMixPercentage))
		THEN  
			UPDATE SET target.ProjectionMixPercentage = src.ProjectionMixPercentage,
					   target.BudgetMixPercentage = src.BudgetMixPercentage
		WHEN NOT MATCHED BY TARGET THEN  
	    	INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID,
				ProjectionMixPercentage, BudgetMixPercentage)  
	    	VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID,
				src.ProjectionMixPercentage, BudgetMixPercentage);
	    --Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example,
	    --the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc
	    --WHEN NOT MATCHED BY SOURCE THEN DELETE; 
	END

END
GO


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

-- fp.procPopulateServiceLineEncounterToChargeVolumePayorMix_History
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2022-01-10	MY		JAZZ-31850	Initial
** 2	2022-09-19	BK		JAZZ-42503	Filter by EGC immediately instead of during second step
** 3	2023-01-17	BK		JAZZ-48267	Update for new data structure
** 4	2023-06-21	MY		JAZZ-55363	Clear out data that is no longer valid
** 5	2024-01-11	AO		JAZZ-64530	Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateServiceLineEncounterToChargeVolumePayorMix_History]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter;
	IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass;
	IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup;
	IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues;
	IF OBJECT_ID('tempdb..#mixesRankedActualYTD') IS NOT NULL DROP TABLE #mixesRankedActualYTD;
	IF OBJECT_ID('tempdb..#mixesRankedPriorYearActual') IS NOT NULL DROP TABLE #mixesRankedPriorYearActual;
	IF OBJECT_ID('tempdb..#mixesRankedCurrentYearBudget') IS NOT NULL DROP TABLE #mixesRankedCurrentYearBudget;
	IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE EntityGroupConfigID  = @EntityGroupConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
	
	-- Translate the CV Departments to Encounter dimensionality
	CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT);
	INSERT INTO #TargetingFilter (EntityID, ServiceLineID)
	SELECT DISTINCT slecvm.EntityID, ServiceLineID
	FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm
		INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID
	WHERE slecvm.BudgetConfigID = @BudgetConfigID
		
	IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table
	BEGIN 
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
	END
	
	-- We no longer need the charge volume departments, so we can drop it here.
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix (
		[BudgetConfigID] [int] NOT NULL DEFAULT(0),
		[EntityGroupConfigID] [int] NOT NULL DEFAULT(0),
		[EntityID] [int] NOT NULL DEFAULT(0),
		[PatientClassID] [int] NOT NULL DEFAULT(0),
		[ServiceLineID] [int] NOT NULL DEFAULT(0),
		[AgeCohortID] [int] NOT NULL DEFAULT(0),
		[MedicalSurgicalID] [int] NOT NULL DEFAULT(0),
		[MSDRGID] [int] NOT NULL DEFAULT(0),
		[CPTID] [int] NOT NULL DEFAULT(0),
		[ProviderID] [int] NOT NULL DEFAULT(0),
		[PayorID] [int] NOT NULL DEFAULT(0),
		[PayorGroupID] [int] NOT NULL DEFAULT(0),
		[ActualYTDMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0),
		[PriorYearActualMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0),
		[CurrentYearBudgetMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0)
	)

	-- Find the total values for each payor group
	SELECT sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID, 
		SUM(hist.ActualYTDValueTotal) AS ActualYTDValueTotal, SUM(hist.PriorYearActualValueTotal) AS PriorYearActualValueTotal, SUM(hist.CurrentYearBudgetTotal) AS CurrentYearBudgetTotal
	INTO #MixByPayorGroup
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN fp.ServiceLineEncounterHistory hist ON sle.ServiceLineEncounterID = hist.ServiceLineEncounterID
		INNER JOIN #TargetingFilter targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
	WHERE sle.EntityGroupConfigID = @EntityGroupConfigID
	GROUP BY sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID
	
	-- Find the rolled up values by Service Line / Patient Class
	SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, 
		SUM(ActualYTDValueTotal) AS ActualYTDValueTotal, SUM(PriorYearActualValueTotal) AS PriorYearActualValueTotal, SUM(CurrentYearBudgetTotal) AS CurrentYearBudgetTotal
	INTO #MixByEntityAndPatientClass
	FROM #MixByPayorGroup
	GROUP BY EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
		
	-- Populate Budget, Target, and Projection
	INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, 
		MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, ActualYTDMixPercentage, PriorYearActualMixPercentage, CurrentYearBudgetMixPercentage)
	SELECT
		@BudgetConfigID,
		@EntityGroupConfigID,
		pg.EntityID, 
		pg.PatientClassID, 
		pg.ServiceLineID, 
		pg.AgeCohortID, 
		pg.MedicalSurgicalID, 
		pg.MSDRGID, 
		pg.CPTID, 
		pg.ProviderID, 
		pg.PayorID,
		pg.PayorGroupID,
		COALESCE(CAST(pg.ActualYTDValueTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.ActualYTDValueTotal, 0) AS DECIMAL(36, 18)), 0) AS ActualYTDMixPercentage,
		COALESCE(CAST(pg.PriorYearActualValueTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.PriorYearActualValueTotal, 0) AS DECIMAL(36, 18)), 0) AS PriorYearActualMixPercentage,
		COALESCE(CAST(pg.CurrentYearBudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.CurrentYearBudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS CurrentYearBudgetMixPercentage
	FROM #MixByPayorGroup pg
		INNER JOIN #MixByEntityAndPatientClass roll ON 
				pg.EntityID = roll.EntityID 
			AND pg.PatientClassID = roll.PatientClassID
			AND pg.ServiceLineID = roll.ServiceLineID
			AND pg.AgeCohortID = roll.AgeCohortID
			AND pg.MedicalSurgicalID = roll.MedicalSurgicalID
			AND pg.MSDRGID = roll.MSDRGID
			AND pg.CPTID = roll.CPTID
			AND pg.ProviderID = roll.ProviderID
					
	---------------------
	-- Rounding
	---------------------
	-- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. 
	-- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. 
	-- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example.
	-- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small
	-- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. 
	--
	-- If this logic is working correctly, the following SQL should return nothing:
	--    SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetMixPercentage)
	--    FROM [fp].[ServiceLineEncounterToChargePayorMix]
	--    GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
	--    HAVING SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0
				
	-- First, find the rounding issues
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, 
		1 - SUM(ActualYTDMixPercentage) AS ActualYTDRoundingDifference, 
		1 - SUM(PriorYearActualMixPercentage) AS PriorYearActualRoundingDifference, 
		1 - SUM(CurrentYearBudgetMixPercentage) AS CurrentYearBudgetRoundingDifference
	INTO #DimesionalityWithRoundingIssues
	FROM #Working_ServiceLineEncounterPayorGroupMix
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
	HAVING SUM(ActualYTDMixPercentage) != 1 AND SUM(ActualYTDMixPercentage) != 0 OR
		   SUM(PriorYearActualMixPercentage) != 1 AND SUM(PriorYearActualMixPercentage) != 0 OR
		   SUM(CurrentYearBudgetMixPercentage) != 1 AND SUM(CurrentYearBudgetMixPercentage) != 0
	
	-- Check Remainder for ActualYTDMix
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, 
		mix.PayorID, mix.PayorGroupID, mix.ActualYTDMixPercentage, rounding.ActualYTDRoundingDifference, 
		ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.ActualYTDMixPercentage DESC) AS RowID
	INTO #mixesRankedActualYTD
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.ActualYTDMixPercentage = mix.ActualYTDMixPercentage + rounding.ActualYTDRoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRankedActualYTD rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
			AND mix.PayorID = rounding.PayorID
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder
		
	-- Check Remainder for PriorYearActual
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, 
		mix.PayorID, mix.PayorGroupID, mix.PriorYearActualMixPercentage, rounding.PriorYearActualRoundingDifference, 
		ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.PriorYearActualMixPercentage DESC) AS RowID
	INTO #mixesRankedPriorYearActual
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.PriorYearActualMixPercentage = mix.PriorYearActualMixPercentage + rounding.PriorYearActualRoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRankedPriorYearActual rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
			AND mix.PayorID = rounding.PayorID
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder
		
	-- Check Remainder for CurrentYearBudget
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, 
		mix.PayorID, mix.PayorGroupID, mix.CurrentYearBudgetMixPercentage, rounding.CurrentYearBudgetRoundingDifference, 
		ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.CurrentYearBudgetMixPercentage DESC) AS RowID
	INTO #mixesRankedCurrentYearBudget
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.CurrentYearBudgetMixPercentage = mix.CurrentYearBudgetMixPercentage + rounding.CurrentYearBudgetRoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRankedCurrentYearBudget rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
			AND mix.PayorID = rounding.PayorID
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder

	IF (@IsDebug = 1)
	BEGIN		
		SELECT '#TargetingFilter', * FROM #TargetingFilter
		SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass
		SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup
		SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues
		SELECT '#mixesRankedActualYTD', * FROM #mixesRankedActualYTD
		SELECT '#mixesRankedPriorYearActual', * FROM #mixesRankedPriorYearActual
		SELECT '#mixesRankedCurrentYearBudget', * FROM #mixesRankedCurrentYearBudget
		SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix		
	END ELSE
	BEGIN 
		-- Publish
		;WITH TGT AS   
		(  
			SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID,
				mix.ActualYTDMixPercentage, mix.PriorYearActualMixPercentage, mix.CurrentYearBudgetMixPercentage
			FROM [fp].[ServiceLineEncounterToChargePayorMix] mix  
				INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID
			WHERE mix.EntityGroupConfigID = @EntityGroupConfigID
		)  
  
		MERGE TGT AS target  
		USING #Working_ServiceLineEncounterPayorGroupMix AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.AgeCohortID = src.AgeCohortID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.ProviderID = src.ProviderID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN MATCHED AND (
							target.ActualYTDMixPercentage <> src.ActualYTDMixPercentage OR
							target.PriorYearActualMixPercentage <> src.PriorYearActualMixPercentage OR
							target.CurrentYearBudgetMixPercentage <> src.CurrentYearBudgetMixPercentage
						 )
		THEN  
			UPDATE SET 
				target.ActualYTDMixPercentage = src.ActualYTDMixPercentage,
				target.PriorYearActualMixPercentage = src.PriorYearActualMixPercentage,
				target.CurrentYearBudgetMixPercentage = src.CurrentYearBudgetMixPercentage
		WHEN NOT MATCHED BY TARGET THEN  
	    	INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID,
				ActualYTDMixPercentage, PriorYearActualMixPercentage, CurrentYearBudgetMixPercentage)  
	    	VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID,
				src.ActualYTDMixPercentage, src.PriorYearActualMixPercentage, src.CurrentYearBudgetMixPercentage);
	    --Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example,
	    --the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc
	    --WHEN NOT MATCHED BY SOURCE THEN DELETE; 
	END

END
GO


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

-- fp.procPopulateServiceLineEncounterToChargeVolumePayorMix_Initial
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1	2022-01-10	MY		JAZZ-31850	Initial
** 2	2023-01-17	BK		JAZZ-48267	Update for new data structure
** 3	2023-06-21	MY		JAZZ-55363	Clear out data that is no longer valid
** 4	2024-01-11	AO		JAZZ-64530	Data transfer for SLE is based on selected Model in Plan Config 
** 5	2024-09-16  MY		JAZZ-70683	Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix
*************************************************************/
CREATE   PROCEDURE [fp].[procPopulateServiceLineEncounterToChargeVolumePayorMix_Initial]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter;
	IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass;
	IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup;
	IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues;
	IF OBJECT_ID('tempdb..#mixesRankedBudget') IS NOT NULL DROP TABLE #mixesRankedBudget;
	IF OBJECT_ID('tempdb..#mixesRankedProjection') IS NOT NULL DROP TABLE #mixesRankedProjection;
	IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix;
	
	-- JAZZ-70683: Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix
	DECLARE @IsProjectionMixEnabled BIT = ISNULL((SELECT Value 
												FROM fp.viewBudgetConfigSetting setting
													INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID
													INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
													AND setting.Name = 'Enable Initial Projection Mix for Encounter to Charge Payor Group Mix'), 0)

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE d.BudgetConfigID  = @BudgetConfigID
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
	
	-- Translate the CV Departments to Encounter dimensionality
	CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT);
	INSERT INTO #TargetingFilter (EntityID, ServiceLineID)
	SELECT DISTINCT slecvm.EntityID, ServiceLineID
	FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm
		INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID
		INNER JOIN fp.BudgetConfig bc ON slecvm.BudgetConfigID = bc.BudgetConfigID 
		INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID 
		INNER JOIN fp.EntityGroupConfigMapping egcm ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID AND egcm.EntityID = slecvm.EntityID
	WHERE slecvm.BudgetConfigID = @BudgetConfigID
		AND egc.EntityGroupConfigID = @EntityGroupConfigID
		
	IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table
	BEGIN 
		SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments
	END
	
	-- We no longer need the charge volume departments, so we can drop it here.
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	
	CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix (
		[BudgetConfigID] [int] NOT NULL DEFAULT(0),
		[EntityGroupConfigID] [int] NOT NULL DEFAULT(0),
		[EntityID] [int] NOT NULL DEFAULT(0),
		[PatientClassID] [int] NOT NULL DEFAULT(0),
		[ServiceLineID] [int] NOT NULL DEFAULT(0),
		[AgeCohortID] [int] NOT NULL DEFAULT(0),
		[MedicalSurgicalID] [int] NOT NULL DEFAULT(0),
		[MSDRGID] [int] NOT NULL DEFAULT(0),
		[CPTID] [int] NOT NULL DEFAULT(0),
		[ProviderID] [int] NOT NULL DEFAULT(0),
		[PayorID] [int] NOT NULL DEFAULT(0),
		[PayorGroupID] [int] NOT NULL DEFAULT(0),
		[InitialMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0),
		[InitialProjectionMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0)
	)
	
	-- Find the total values for each payor group
	SELECT sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID, 
		SUM(sle.InitialBudgetTotal) AS BudgetTotal, SUM(sle.InitialProjectionTotal) AS ProjectionTotal
	INTO #MixByPayorGroup
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN #TargetingFilter targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
	WHERE sle.EntityGroupConfigID = @EntityGroupConfigID
	GROUP BY sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID
	
	-- Find the rolled up values by Service Line / Patient Class
	SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal
	INTO #MixByEntityAndPatientClass
	FROM #MixByPayorGroup
	GROUP BY EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
		
	-- Populate Budget, Target, and Projection
	INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, 
		MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, InitialMixPercentage, InitialProjectionMixPercentage)
	SELECT
		@BudgetConfigID,
		@EntityGroupConfigID,
		pg.EntityID, 
		pg.PatientClassID, 
		pg.ServiceLineID, 
		pg.AgeCohortID, 
		pg.MedicalSurgicalID, 
		pg.MSDRGID, 
		pg.CPTID, 
		pg.ProviderID, 
		pg.PayorID,
		pg.PayorGroupID,
		COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS InitialMixPercentage,
		COALESCE(CAST(pg.ProjectionTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.ProjectionTotal, 0) AS DECIMAL(36, 18)), 0) AS InitialProjectionMixPercentage
	FROM #MixByPayorGroup pg
		INNER JOIN #MixByEntityAndPatientClass roll ON 
				pg.EntityID = roll.EntityID 
			AND pg.PatientClassID = roll.PatientClassID
			AND pg.ServiceLineID = roll.ServiceLineID
			AND pg.AgeCohortID = roll.AgeCohortID
			AND pg.MedicalSurgicalID = roll.MedicalSurgicalID
			AND pg.MSDRGID = roll.MSDRGID
			AND pg.CPTID = roll.CPTID
			AND pg.ProviderID = roll.ProviderID
					
	---------------------
	-- Rounding
	---------------------
	-- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. 
	-- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. 
	-- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example.
	-- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small
	-- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. 
	--
	-- If this logic is working correctly, the following SQL should return nothing:
	--    SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetMixPercentage)
	--    FROM [fp].[ServiceLineEncounterToChargePayorMix]
	--    GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
	--    HAVING SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0
				
	-- First, find the rounding issues
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, 
		1 - SUM(InitialMixPercentage) AS BudgetRoundingDifference
	INTO #DimesionalityWithRoundingIssues
	FROM #Working_ServiceLineEncounterPayorGroupMix
	GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
	HAVING SUM(InitialMixPercentage) != 1 AND SUM(InitialMixPercentage) != 0
	
	-- Check Remainder for Budget
	-- Next we need to find the highest value of each group so we know where we need to put the remainder
	SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, 
		mix.PayorID, mix.PayorGroupID, mix.InitialMixPercentage, rounding.BudgetRoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.InitialMixPercentage DESC) AS RowID
	INTO #mixesRankedBudget
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #DimesionalityWithRoundingIssues rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
		
	-- Update the mixed percentage
	UPDATE mix
	SET mix.InitialMixPercentage = mix.InitialMixPercentage + rounding.BudgetRoundingDifference
	FROM #Working_ServiceLineEncounterPayorGroupMix mix
		INNER JOIN #mixesRankedBudget rounding ON 
				mix.EntityID = rounding.EntityID 
			AND mix.PatientClassID = rounding.PatientClassID 
			AND mix.ServiceLineID = rounding.ServiceLineID 
			AND mix.AgeCohortID = rounding.AgeCohortID 
			AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
			AND mix.MSDRGID = rounding.MSDRGID 
			AND mix.CPTID = rounding.CPTID 
			AND mix.ProviderID = rounding.ProviderID 
			AND mix.PayorID = rounding.PayorID
			AND mix.PayorGroupID = rounding.PayorGroupID
	WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder

	IF (@IsProjectionMixEnabled = 1)
	BEGIN

		--------------------------------------------------------
		-- Projection
		--------------------------------------------------------

		-- First, find the rounding issues
		SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, 
			1 - SUM(InitialProjectionMixPercentage) AS RoundingDifference
		INTO #DimesionalityWithRoundingIssues_Projection
		FROM #Working_ServiceLineEncounterPayorGroupMix
		GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID
		HAVING SUM(InitialProjectionMixPercentage) != 1 AND SUM(InitialProjectionMixPercentage) != 0
	
		-- Check Remainder for Budget
		-- Next we need to find the highest value of each group so we know where we need to put the remainder
		SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, 
			mix.PayorID, mix.PayorGroupID, mix.InitialProjectionMixPercentage, rounding.RoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.InitialMixPercentage DESC) AS RowID
		INTO #mixesRankedProjection
		FROM #Working_ServiceLineEncounterPayorGroupMix mix
			INNER JOIN #DimesionalityWithRoundingIssues_Projection rounding ON 
					mix.EntityID = rounding.EntityID 
				AND mix.PatientClassID = rounding.PatientClassID 
				AND mix.ServiceLineID = rounding.ServiceLineID 
				AND mix.AgeCohortID = rounding.AgeCohortID 
				AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
				AND mix.MSDRGID = rounding.MSDRGID 
				AND mix.CPTID = rounding.CPTID 
				AND mix.ProviderID = rounding.ProviderID 
		
		-- Update the mixed percentage
		UPDATE mix
		SET mix.InitialProjectionMixPercentage = mix.InitialProjectionMixPercentage + rounding.RoundingDifference
		FROM #Working_ServiceLineEncounterPayorGroupMix mix
			INNER JOIN #mixesRankedProjection rounding ON 
					mix.EntityID = rounding.EntityID 
				AND mix.PatientClassID = rounding.PatientClassID 
				AND mix.ServiceLineID = rounding.ServiceLineID 
				AND mix.AgeCohortID = rounding.AgeCohortID 
				AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID 
				AND mix.MSDRGID = rounding.MSDRGID 
				AND mix.CPTID = rounding.CPTID 
				AND mix.ProviderID = rounding.ProviderID 
				AND mix.PayorID = rounding.PayorID
				AND mix.PayorGroupID = rounding.PayorGroupID
		WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder
	
	END

	IF (@IsDebug = 1)
	BEGIN		
		SELECT '#TargetingFilter', * FROM #TargetingFilter
		SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass
		SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup
		SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues
		SELECT '#mixesRankedBudget', * FROM #mixesRankedBudget
		SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix		
	END ELSE
	BEGIN 
		-- Publish
		;WITH TGT AS   
		(  
			SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID,
				mix.InitialMixPercentage
			FROM [fp].[ServiceLineEncounterToChargePayorMix] mix  
				INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID
			WHERE mix.EntityGroupConfigID = @EntityGroupConfigID
		)  
  
		MERGE TGT AS target  
		USING #Working_ServiceLineEncounterPayorGroupMix AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.AgeCohortID = src.AgeCohortID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.ProviderID = src.ProviderID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN MATCHED AND (target.InitialMixPercentage <> src.InitialMixPercentage)
		THEN  
			UPDATE SET target.InitialMixPercentage = src.InitialMixPercentage
		WHEN NOT MATCHED BY TARGET THEN  
	    	INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID,
				InitialMixPercentage)  
	    	VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID,
				src.InitialMixPercentage);
	    --Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example,
	    --the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc
	    --WHEN NOT MATCHED BY SOURCE THEN DELETE; 

		IF (@IsProjectionMixEnabled = 1)
		BEGIN
			
			-- Publish
			;WITH TGT AS   
			(  
				SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID,
					mix.InitialProjectionMixPercentage
				FROM [fp].[ServiceLineEncounterToChargePayorMix] mix  
					INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID
				WHERE mix.EntityGroupConfigID = @EntityGroupConfigID
			)  
  
			MERGE TGT AS target  
			USING #Working_ServiceLineEncounterPayorGroupMix AS src  
			ON (  
					target.BudgetConfigID = src.BudgetConfigID  
				AND target.EntityGroupConfigID = src.EntityGroupConfigID  
				AND target.EntityID = src.EntityID  
				AND target.PatientClassID = src.PatientClassID  
				AND target.ServiceLineID = src.ServiceLineID 
				AND target.AgeCohortID = src.AgeCohortID 
				AND target.MedicalSurgicalID = src.MedicalSurgicalID 
				AND target.MSDRGID = src.MSDRGID 
				AND target.CPTID = src.CPTID 
				AND target.ProviderID = src.ProviderID 
				AND target.PayorID = src.PayorID 
				AND target.PayorGroupID = src.PayorGroupID 
			)  
			WHEN MATCHED AND (target.InitialProjectionMixPercentage <> src.InitialProjectionMixPercentage)
			THEN  
				UPDATE SET target.InitialProjectionMixPercentage = src.InitialProjectionMixPercentage
			WHEN NOT MATCHED BY TARGET THEN  
	    		INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID,
					InitialProjectionMixPercentage)  
	    		VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID,
					src.InitialProjectionMixPercentage);
			--Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example,
			--the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc
			--WHEN NOT MATCHED BY SOURCE THEN DELETE; 

		END
	END

END
GO


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

-- fp.procPopulateStaffingVariabilityByBudgetConfig_PayCode
CREATE PROC fp.procPopulateStaffingVariabilityByBudgetConfig_PayCode
	@BudgetConfigID INT
AS
BEGIN
	DECLARE @EntityGroupConfigGuid UNIQUEIDENTIFIER
	DECLARE @EntityGroupConfigId INT
	DECLARE @FiscalYearId INT

	DECLARE entityGroupConfigCrs CURSOR FOR
	SELECT 
		EntityGroupConfigGUID,
		EntityGroupConfigID,
		FiscalYearID
	FROM [fp].[EntityGroupConfig] egc
		INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigId;

	OPEN entityGroupConfigCrs

	FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId, @FiscalYearId

	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC [fp].[procPopulateStaffingVariability_PayCode] @EntityGroupConfigGuid, @EntityGroupConfigId, @FiscalYearId
		
		FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId, @FiscalYearId
	END

	CLOSE entityGroupConfigCrs;
	DEALLOCATE entityGroupConfigCrs;
END
GO


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

-- fp.procPopulateStaffingVariability_PayCode
CREATE PROCEDURE [fp].[procPopulateStaffingVariability_PayCode]
	 @EntityGroupConfigGUID UNIQUEIDENTIFIER,
	 @EntityGroupConfigID INT,
	 @FiscalYearID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
 AS
 BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	2022-06-30   MD      JAZZ-13102		Use original department when populating variability
	** 2	2022-08-16   MY      JAZZ-40590		Exclude Dollars Only from Variability
	** 3	2022-11-07   MY      JAZZ-35951		Refactor and add debug
	** 4	2022-11-07   MY      JAZZ-35951		Add Employee to FactStaffingVariabilityDetail
	** 5	2023-04-24   NT      JAZZ-53870		Add option recompile to improve performance
	** 6	2023-09-20   BK      JAZZ-60973		Update for new data structure
	** 7	2024-01-30   BK      JAZZ-63880		Change JobCodeID and PayCodeID to int from smallint
	** 8	2024-01-31   NH      JAZZ-64064		Move Provider Planning FF as a setting in Plan Config
	** 9	2024-05-09   AO		 JAZZ-71284		Added index to #staffingDim to improve performance
	** 10	2024-06-25   JB		 JAZZ-72523		Added index to #StaffingVariability and #providerVariability
	*************************************************************/

	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#staffingDim') IS NOT NULL DROP TABLE #staffingDim
	IF OBJECT_ID('tempdb..#staffingVariability') IS NOT NULL DROP TABLE #staffingVariability
	IF OBJECT_ID('tempdb..#providerVariability') IS NOT NULL DROP TABLE #providerVariability
	IF OBJECT_ID('tempdb..#StaffingVariabilityDetail') IS NOT NULL DROP TABLE #StaffingVariabilityDetail
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	  
	
	DECLARE @StaffingSubsectionID INT,
			@ProviderSubsectionID INT,
			@BudgetConfigID INT,
			@IsProviderPlanningEnabled BIT,
			@IsForceDollarsOnlyToFixedFlag BIT;

	SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID
	SET @IsForceDollarsOnlyToFixedFlag = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Force Dollars Only to be Fixed' AND BudgetConfigID = @BudgetConfigID), 0);

	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

	SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' 
	SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' 

	CREATE TABLE #staffingDim (DepartmentID INT, JobCodeID INT, PayCodeID INT, ProviderLineItemID INT, SubsectionID INT, INDEX BASE CLUSTERED (SubsectionID, DepartmentID) );
	CREATE TABLE #StaffingVariabilityDetail (EntityGroupConfigGUID UNIQUEIDENTIFIER, DepartmentID INT, JobCodeID INT, PayCodeID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(19, 8))

	/*
		NOTE ABOUT JAZZ-35951
		-----------------------------
		We now store variability at the Employee level, this is to allow cases where a Department/Job Code combination is set to variable, however
		it has employee budgeting enabled and they add an employee to it. This would add the employee, but we want it to be 100% Fixed.

		Employees in Employee Budgeting are always 100% Fixed. This is why we are setting EmployeeID = 0, essentially all rows where EmployeeID > 0, it should
		always have a Fixed Percentage of 100%. Anything that is variable is going to have EmployeeID = 0.
	*/

	IF EXISTS(SELECT 1 FROM [fp].[EntityGroupConfig] WHERE IsPatientActivityFlexingForStaffing = 1 AND EntityGroupConfigGUID = @EntityGroupConfigGUID )
	BEGIN
		-------------------------------------------------------------------------------------------
		-- Patient Activity
		-------------------------------------------------------------------------------------------
		INSERT INTO #StaffingVariabilityDetail (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID)
		SELECT 
			a.EntityGroupConfigGUID,
			a.DepartmentID,
			a.JobCodeID,
			a.PayCodeID,
			a.FixedPercentage,
			-- Employee and Provider Line Item will not be on the Detailed Costing table and thus not used
			0 as ProviderLineItemID,
			0 as EmployeeID 
		FROM (
		    SELECT 
		        fp.EntityGroupConfigGUID,
		        fp.DepartmentID, 
		        fp.JobCodeID, 
		        fp.PayCodeID, 
		        CASE 
		            WHEN TotalCost = 0 THEN 0 
		            WHEN (TotalFixedDirectCost/TotalCost) > .9999 THEN 1.0 
		            ELSE (TotalFixedDirectCost/TotalCost) 
		        END AS [FixedPercentage],
		        COALESCE(conovr.FlexMethodID, fp.FlexMethodID) as [FlexMethodID]
		    FROM (
					SELECT
						ec.EntityGroupConfigGuid,
						pay.OriginalDepartmentID as DepartmentID, --use original department (not reclassed) to insert into fp tables
						pay.OriginalJobCodeID as JobCodeID,
						pay.OriginalPayCodeID as PayCodeID,
						fc.FlexMethodID,
						SUM(pay.FixedDirectUnitCost * pay.Volume) as TotalFixedDirectCost,
						SUM(pay.TotalCost) as TotalCost
					FROM
						[dss].[FactCostingOutDetailPayroll] pay
						INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID
						INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID
						INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.EntityGroupConfigGUID = ec.EntityGroupConfigGUID AND fc.DepartmentID = pay.OriginalDepartmentID  
						INNER JOIN fw.DimPayCode pc ON pay.OriginalPayCodeID = pc.PayCodeID
						INNER JOIN fw.DimPayCodeGroup pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID
						INNER JOIN #FilterByDepartment ff on ff.DepartmentID = pay.OriginalDepartmentID  
					WHERE
						pay.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0)
						AND pay.TimeClassID = ec.CostingConfigTimeClassID
						AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID
						AND (@IsForceDollarsOnlyToFixedFlag = 0 OR pcg.ProductiveClassID != 4) -- 4 = Dollars Only; 
					GROUP BY
						ec.EntityGroupConfigGuid, pay.OriginalDepartmentID, pay.OriginalJobCodeID, pay.OriginalPayCodeID, pay.FiscalYearID, fc.FlexMethodID
		        ) fp
		    LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr 
		        ON fp.EntityGroupConfigGuid = conovr.EntityGroupConfigGuid 
		        AND fp.DepartmentID = conovr.DepartmentID 
		        AND fp.JobCodeID = conovr.JobCodeID
		    ) a
		WHERE 
		    a.FlexMethodID = 2
		    AND FixedPercentage < 1

		IF (@IsDebug = 1)
		BEGIN
			SELECT 'After Patient Activity Flexing', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage
			FROM #StaffingVariabilityDetail
		END
	END
	
	-------------------------------------------------------------------------------------------
	-- Process Regular (Non-Paf) Variability
	-------------------------------------------------------------------------------------------

	INSERT INTO #staffingDim (DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, SubsectionID)
	SELECT DISTINCT
		fs.DepartmentID,
		JobCodeID,
		ISNULL(pc.PayCodeID, 0) as PayCodeID,
		fs.ProviderLineItemID,
		fs.SubsectionID
	FROM [fp].[Staffing] fs
		INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fs.DepartmentID
		LEFT JOIN [fw].[DimPayCode] pc ON fs.PayCodeGroupID = pc.PayCodeGroupID
		LEFT JOIN [fw].[DimPayCodeGroup] pcg ON fs.PayCodeGroupID = pcg.PayCodeGroupID
	-- limit to variability = 1 only to make query faster, all unit types should be there but we only need Dept/JobCode/PayCode/ProviderLineItem/Employee
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
		AND fs.VariabilityID = 1  
		AND (@IsForceDollarsOnlyToFixedFlag = 0 OR fs.ProductiveClassID != 4 AND pcg.ProductiveClassID != 4) -- 4 = Dollars Only; 
	
	-------------------------------------------------------------------------------------------
    -- Regular Staffing Variability
	-------------------------------------------------------------------------------------------
	CREATE TABLE #StaffingVariability (
    DepartmentID INT,
    JobCodeID INT,
    PayCodeID INT,
    FixedPercentage DECIMAL(19, 8),
    ProviderLineItemID INT,
    EmployeeID INT
);

INSERT INTO #StaffingVariability (DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID)
	  SELECT
		a.DepartmentID,
		a.JobCodeID,
		fs.PayCodeID,
		a.FixedPercentage,
		0 as ProviderLineItemID,
		0 as EmployeeID
	 FROM
	 ( 
		SELECT 
	        pvc.EntityGroupConfigGUID,
	        COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID',
	        COALESCE(conovr.JobCodeID, pvc.JobCodeID) AS 'JobCodeID',
	        (1 - COALESCE(varovr.Variability, pvc.Variability)) AS 'FixedPercentage',
	        COALESCE(conovr.FlexMethodID, efc.FlexMethodID) AS 'FlexMethodID'
	    FROM 
	        [fp].[PayrollVariabilityConfig] pvc
	        INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID
			INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID
	        LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID
	        LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID
	    WHERE
	        pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID
	        AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 1
	        AND COALESCE(varovr.Variability, pvc.Variability) != 0
	    ) a
		INNER JOIN 
		(
		    SELECT DISTINCT
				DepartmentID,
				JobCodeID,
				PayCodeID
			FROM #staffingDim
			WHERE SubSectionID = @StaffingSubsectionID
	    ) fs ON fs.DepartmentID = a.DepartmentID AND fs.JobCodeID = a.JobCodeID
		OPTION (RECOMPILE);
CREATE INDEX idx_staffingVariability ON #StaffingVariability (DepartmentID, JobCodeID);

	-------------------------------------------------------------------------------------------
	-- Provider Staffing Variability (overrides regular Staffing Variability)
	-------------------------------------------------------------------------------------------

	CREATE TABLE #ProviderVariability (
    DepartmentID INT,
    JobCodeID INT,
    PayCodeID INT,
    ProviderLineItemID INT,
    EmployeeID INT,
    ProviderFixedPercentage DECIMAL(19, 8)
);

INSERT INTO #ProviderVariability (DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, ProviderFixedPercentage)
	 SELECT DISTINCT
			fs.DepartmentID,
			fs.JobCodeID,
			fs.PayCodeID,
			fs.ProviderLineItemID,
			0 as EmployeeID,
			CASE WHEN psc.VariabilityID = 1 THEN 1 ELSE 0 END as ProviderFixedPercentage
		FROM #staffingDim fs
			INNER JOIN [fp].[ProviderStaffingConfig] psc ON fs.ProviderLineItemID = psc.ProviderLineItemID
			LEFT JOIN ( 
						SELECT 
					        COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID'
					    FROM 
					        [fp].[PayrollVariabilityConfig] pvc
					        INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID
							  INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID
					        LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID
					        LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID
					    WHERE
					        pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID
					        AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 6
					    ) fixed ON fs.DepartmentID = fixed.DepartmentID		
		WHERE fs.SubSectionID = @ProviderSubsectionID 
			AND @IsProviderPlanningEnabled = 1 
			AND fixed.DepartmentID IS NULL 
			AND psc.BudgetConfigID = @BudgetConfigID
CREATE INDEX idx_providerVariability ON #ProviderVariability (DepartmentID, JobCodeID);

	-------------------------------------------------------------------------------------------
	-- Stat Accounts
	-------------------------------------------------------------------------------------------
	INSERT INTO #StaffingVariabilityDetail (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID)
	SELECT 
		@EntityGroupConfigGUID,
		s.DepartmentID,
		s.JobCodeID,
		s.PayCodeID,
		s.FixedPercentage,
		0 as ProviderLineItemID,
		0 as EmployeeID 
	FROM #StaffingVariability s 
		LEFT JOIN #ProviderVariability p ON s.DepartmentID = p.DepartmentID AND s.JobCodeID = p.JobCodeID
	WHERE p.DepartmentID IS NULL 
		AND p.JobCodeID IS NULL   
		  
	IF (@IsDebug = 1)
	BEGIN
		SELECT 'After Regular Flexing', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage
		FROM #StaffingVariabilityDetail
	END

	-------------------------------------------------------------------------------------------
	-- Provider Stat Accounts
	-------------------------------------------------------------------------------------------
	INSERT INTO #StaffingVariabilityDetail (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID)
	SELECT 
		@EntityGroupConfigGUID,
		p.DepartmentID,
		p.JobCodeID,
		p.PayCodeID,
		p.ProviderFixedPercentage,
		p.ProviderLineItemID,
		0 as EmployeeID 
	FROM  #ProviderVariability p
				
	IF (@IsDebug = 1)
	BEGIN
		SELECT 'After Provider', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage
		FROM #StaffingVariabilityDetail
	END

	-------------------------------------------------------------------------------------------
	-- Publish	
	-------------------------------------------------------------------------------------------
	IF (@IsDebug = 0)
	BEGIN
			
		DELETE pv FROM [fp].[FactStaffingVariabilityDetail] pv
			INNER JOIN #FilterByDepartment ff on ff.DepartmentID = pv.DepartmentID
		WHERE pv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				
		INSERT INTO [fp].[FactStaffingVariabilityDetail] (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage)
		SELECT 
			@EntityGroupConfigGUID,
			DepartmentID,
			JobCodeID,
			PayCodeID,
			ProviderLineItemID,
			EmployeeID, -- Employee should always be 0 as Employees are treated as 100% fixed and thus should never have a row in [fp].[FactStaffingVariabilityDetail]
			FixedPercentage
		FROM #StaffingVariabilityDetail
		WHERE FixedPercentage < 1 -- We assume when something isn't in the table that it's 100% fixed.

	END ELSE
	BEGIN
		SELECT 'Final', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage
		FROM #StaffingVariabilityDetail
	END

 END
GO


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

-- fp.procProcessReportFactGeneralLedger
CREATE     PROCEDURE [fp].[procProcessReportFactGeneralLedger] (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    2018-12-24   IP        B-21543     Added temp table to index source as well
	** 2    2018-12-24   IP        B-21543     Added temp table to index source as well
	** 3    2019-01-09   GF        B-21715     Optimize full config refresh case
	** 4    2019-01-11   GF        B-21715     Optimize targeted refresh case
	** 5    2019-05-02   GF        			   Remove special handling of all case to make concurrency work
	** 6    2019-07-22   MY        			   Performance updates
	** 7    2020-01-13   MY        D-09168	   CCF: Data not flowing through into reports
	** 8    2021-11-10   BW        JAZZ-1358   Add dept to the filter when untargeted, to remove orphans 
	** 9    2022-10-28   MY        JAZZ-45443  Roll proc back to before perf changes
    ** 10   2023-08-11   BK        JAZZ-58752  Rename from 'procProcessReportFactGeneralLedger_TargetBudget' and update for new gl data structure
	** 11	2024-04-11	 DM		    JAZZ-70189  Budget Config used for Report comparison is processed as well
	*************************************************************/

	exec [dbo].[procSysDropTempTable] '#SRC'
	exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
	exec [dbo].[procSysDropTempTable] '#departments'		
	exec [dbo].[procSysDropTempTable] '#adjustedRecords'
	exec [dbo].[procSysDropTempTable] '#tempUnpivoted'
	exec [dbo].[procSysDropTempTable] '#dataToUpdate'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) 
	
	CREATE TABLE #departments (DepartmentID INT);

	CREATE TABLE #SRC (
		GeneralLedgerID INT, 
		BudgetConfigID INT, 
		EntityGroupConfigID INT, 
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		FinancialReportingID INT, 
		APEModelSectionID INT, 
		VariabilityID INT, 
		UnitTypeID SMALLINT, 
		TimeClassID TINYINT,
		FiscalYearID SMALLINT, 
		FiscalMonthID TINYINT,
		LockType TINYINT,
		OriginalValue DECIMAL(19, 8), 
		Value DECIMAL(19, 8), 
		ManagerValue DECIMAL(19, 8),
		Rate DECIMAL(19, 8)
	)

	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN

		INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate)
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate
		FROM [fp].[viewFactGeneralLedger_Unpivoted_source] VW
			INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID
		WHERE VW.BudgetConfigID  = @BudgetConfigID
			AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0)
			
	END ELSE BEGIN

		INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate)
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate
		FROM [fp].[viewFactGeneralLedger_Unpivoted_source] VW
		WHERE VW.BudgetConfigID  = @BudgetConfigID
			AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0)
			
	END

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		GeneralLedgerID 
		,BudgetConfigID 
		,EntityGroupConfigID 
		,EntityID
		,DepartmentID
		,AccountID
		,FinancialReportingID
		,APEModelSectionID
		,VariabilityID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,FiscalMonthID
	)


	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #departments (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.GeneralLedger 
		WHERE BudgetConfigID = @BudgetConfigID
	END
	ELSE BEGIN
		-- Get all of the departments in that could be affected. We need to get this list to eliminate
		-- the null check in the join in the with statement.
		INSERT INTO #departments (DepartmentID) 
		SELECT DISTINCT DepartmentID
		FROM (
			SELECT DISTINCT DepartmentID FROM #SRC
			UNION ALL
			SELECT DISTINCT DepartmentID FROM #SourceDimensionality
		) data
	END
			

	;WITH TGT AS 
	(
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate 
		FROM fp.FactReportGeneralLedger FRS
			INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)

		MERGE TGT AS target
		USING #SRC AS source
			ON (
						target.GeneralLedgerID = source.GeneralLedgerID
					AND target.BudgetConfigID = source.BudgetConfigID
					AND target.EntityGroupConfigID = source.EntityGroupConfigID
					AND target.EntityID = source.EntityID
					AND target.DepartmentID = source.DepartmentID
					AND target.AccountID = source.AccountID
					AND target.FinancialReportingID = source.FinancialReportingID
					AND target.APEModelSectionID = source.APEModelSectionID
					AND target.VariabilityID = source.VariabilityID
					AND target.UnitTypeID = source.UnitTypeID
					AND target.TimeClassID = source.TimeClassID
					AND target.FiscalYearID = source.FiscalYearID
					AND target.FiscalMonthID = source.FiscalMonthID 
					)
		WHEN MATCHED AND (target.LockType <> source.LockType
				OR target.OriginalValue <> source.OriginalValue
				OR target.Value <> source.Value
				OR target.ManagerValue <> source.ManagerValue
				OR target.Rate <> source.Rate)
			THEN
				UPDATE
				SET target.LockType = ISNULL(source.LockType, 0),
					target.OriginalValue = ISNULL(source.OriginalValue, 0),
					target.Value = ISNULL(source.Value, 0),
					target.ManagerValue = ISNULL(source.ManagerValue, 0),
					target.Rate = ISNULL(source.Rate, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					GeneralLedgerID
					,BudgetConfigID
					,EntityGroupConfigID
					,EntityID
					,DepartmentID
					,AccountID
					,FinancialReportingID
					,APEModelSectionID
					,VariabilityID
					,UnitTypeID
					,TimeClassID
					,FiscalYearID
					,FiscalMonthID
					,LockType
					,OriginalValue
					,Value
					,ManagerValue
					,Rate
					)
				VALUES (
					source.GeneralLedgerID
					,source.BudgetConfigID
					,source.EntityGroupConfigID
					,source.EntityID
					,source.DepartmentID
					,source.AccountID
					,source.FinancialReportingID
					,source.APEModelSectionID
					,source.VariabilityID
					,source.UnitTypeID
					,source.TimeClassID
					,source.FiscalYearID
					,source.FiscalMonthID
					,ISNULL(source.LockType, 0)
					,ISNULL(source.OriginalValue, 0)
					,ISNULL(source.Value, 0)
					,ISNULL(source.ManagerValue, 0)
					,ISNULL(source.Rate, 0)
					)
		WHEN NOT MATCHED BY Source
			THEN
				DELETE;		
				
	
	-------------------------------------------------------------------------------------------------------
	-- D-09168 : CCF: Data not flowing through into reports
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above. This is a short term solution until we can get a more performant solution.
	-------------------------------------------------------------------------------------------------------
	
	-- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments
	-- We can't rely on the existing departments because of the check for the padded rows.
	IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
	
		TRUNCATE TABLE #departments;
	
		INSERT INTO #departments (DepartmentID)
		SELECT DepartmentID
		FROM [fw].[DimDepartment] dept
	
	END

	-- Get all records that were adjusted
	SELECT DISTINCT chg.GeneralLedgerID
	INTO #adjustedRecords
	FROM [fp].[GeneralLedgerChangeHistory] chg
		INNER JOIN [fp].[GeneralLedger] gl ON chg.GeneralLedgerID = gl.GeneralLedgerID
		INNER JOIN [fp].[GeneralLedgerAdjustment] adj ON chg.AdjustmentGUID = adj.AdjustmentGUID
		INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN #departments ft on ft.DepartmentID = gl.DepartmentID
	WHERE bc.BudgetConfigID = @BudgetConfigID

	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	SELECT src.*
	INTO #tempUnpivoted
	FROM #adjustedRecords adj
		INNER JOIN [fp].[viewFactGeneralLedger_Unpivoted_source] src ON src.GeneralLedgerID = adj.GeneralLedgerID
	WHERE src.BudgetConfigID = @BudgetConfigID
		AND (src.OriginalValue = 0 OR src.Value = 0 OR src.ManagerValue = 0)

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT VW.*
	INTO #dataToUpdate
	FROM [fp].[FactReportGeneralLedger] frgl
		INNER JOIN #departments ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted VW ON VW.GeneralLedgerID = frgl.GeneralLedgerID 
			AND VW.FiscalMonthID = frgl.FiscalMonthID 
			AND VW.UnitTypeID = frgl.UnitTypeID 
			AND VW.FiscalYearID = frgl.FiscalYearID
			AND VW.TimeClassID = frgl.TimeClassID
	WHERE frgl.BudgetConfigID = @BudgetConfigID
		AND (VW.OriginalValue != frgl.OriginalValue OR VW.Value != frgl.Value OR VW.ManagerValue != frgl.ManagerValue)	

	-- Update the records
	UPDATE frgl
	SET frgl.OriginalValue = 		ISNULL(upd.OriginalValue, 0), 
		frgl.Value = 		ISNULL(upd.Value, 0),
		frgl.ManagerValue = ISNULL(upd.ManagerValue, 0)
	FROM [fp].[FactReportGeneralLedger] frgl
		INNER JOIN #departments ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #dataToUpdate upd ON upd.GeneralLedgerID = frgl.GeneralLedgerID AND upd.FiscalMonthID = frgl.FiscalMonthID AND upd.UnitTypeID = frgl.UnitTypeID 


END
GO


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

-- fp.procProcessReportFactGeneralLedgerSnapshot
CREATE   PROCEDURE [fp].[procProcessReportFactGeneralLedgerSnapshot] (
	@SnapshotID INT
)
WITH RECOMPILE
AS
BEGIN

	/*************************************************************
	** Change History
	**************************************************************
	** CID    Date        Author      WI			Description
	** 1      2024-11-04  MY          JAZZ-77737	Initial
	***************************************************************/

	exec [dbo].[procSysDropTempTable] '#SRC'
	exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
	exec [dbo].[procSysDropTempTable] '#departments'		
	exec [dbo].[procSysDropTempTable] '#adjustedRecords'
	exec [dbo].[procSysDropTempTable] '#tempUnpivoted'
	exec [dbo].[procSysDropTempTable] '#dataToUpdate'

	DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.BudgetSnapshot WHERE SnapshotID = @SnapshotID);
	
	CREATE TABLE #SRC (
		GeneralLedgerID INT, 
		BudgetConfigID INT, 
		EntityGroupConfigID INT, 
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		FinancialReportingID INT, 
		APEModelSectionID INT, 
		VariabilityID INT, 
		UnitTypeID SMALLINT, 
		TimeClassID TINYINT,
		FiscalYearID SMALLINT, 
		FiscalMonthID TINYINT,
		LockType TINYINT,
		OriginalValue DECIMAL(19, 8), 
		Value DECIMAL(19, 8), 
		ManagerValue DECIMAL(19, 8),
		Rate DECIMAL(19, 8)
	)

	INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate)
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate
	FROM [fp].[viewFactGeneralLedger_Snapshot] VW
	WHERE VW.SnapshotID = @SnapshotID
		AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0)

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		GeneralLedgerID 
		,BudgetConfigID 
		,EntityGroupConfigID 
		,EntityID
		,DepartmentID
		,AccountID
		,FinancialReportingID
		,APEModelSectionID
		,VariabilityID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,FiscalMonthID
	)		

	;WITH TGT AS 
	(
		SELECT GeneralLedgerID, SnapshotID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate 
		FROM fp.FactReportGeneralLedgerSnapshot FRS
		WHERE FRS.SnapshotID  = @SnapshotID
	)

		MERGE TGT AS target
		USING #SRC AS source
			ON (
						target.GeneralLedgerID = source.GeneralLedgerID
					AND target.SnapshotID = @SnapshotID
					AND target.BudgetConfigID = source.BudgetConfigID
					AND target.EntityGroupConfigID = source.EntityGroupConfigID
					AND target.EntityID = source.EntityID
					AND target.DepartmentID = source.DepartmentID
					AND target.AccountID = source.AccountID
					AND target.FinancialReportingID = source.FinancialReportingID
					AND target.APEModelSectionID = source.APEModelSectionID
					AND target.VariabilityID = source.VariabilityID
					AND target.UnitTypeID = source.UnitTypeID
					AND target.TimeClassID = source.TimeClassID
					AND target.FiscalYearID = source.FiscalYearID
					AND target.FiscalMonthID = source.FiscalMonthID 
					)
		WHEN MATCHED AND (target.LockType <> source.LockType
				OR target.OriginalValue <> source.OriginalValue
				OR target.Value <> source.Value
				OR target.ManagerValue <> source.ManagerValue
				OR target.Rate <> source.Rate)
			THEN
				UPDATE
				SET target.LockType = ISNULL(source.LockType, 0),
					target.OriginalValue = ISNULL(source.OriginalValue, 0),
					target.Value = ISNULL(source.Value, 0),
					target.ManagerValue = ISNULL(source.ManagerValue, 0),
					target.Rate = ISNULL(source.Rate, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					 GeneralLedgerID
					,SnapshotID
					,BudgetConfigID
					,EntityGroupConfigID
					,EntityID
					,DepartmentID
					,AccountID
					,FinancialReportingID
					,APEModelSectionID
					,VariabilityID
					,UnitTypeID
					,TimeClassID
					,FiscalYearID
					,FiscalMonthID
					,LockType
					,OriginalValue
					,Value
					,ManagerValue
					,Rate
					)
				VALUES (
					 source.GeneralLedgerID
					,@SnapshotID
					,source.BudgetConfigID
					,source.EntityGroupConfigID
					,source.EntityID
					,source.DepartmentID
					,source.AccountID
					,source.FinancialReportingID
					,source.APEModelSectionID
					,source.VariabilityID
					,source.UnitTypeID
					,source.TimeClassID
					,source.FiscalYearID
					,source.FiscalMonthID
					,ISNULL(source.LockType, 0)
					,ISNULL(source.OriginalValue, 0)
					,ISNULL(source.Value, 0)
					,ISNULL(source.ManagerValue, 0)
					,ISNULL(source.Rate, 0)
					)
		WHEN NOT MATCHED BY Source
			THEN
				DELETE;		

	-- Copy the UK to US Datatransfer data at the time of the snapshot
	INSERT INTO [fp].[FactReportGeneralLedgerDataTransferSnapshot] (SnapshotID, BudgetconfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID,
		TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue, Value, ManagerValue, Rate)
	SELECT @SnapshotID, BudgetConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID,
		TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue, Value, ManagerValue, Rate
	FROM [fp].[FactReportGeneralLedgerDataTransfer]
	WHERE BudgetConfigID = @BudgetConfigID

END
GO


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

-- fp.procProcessReportFactGeneralLedger_Initial
CREATE     PROCEDURE [fp].[procProcessReportFactGeneralLedger_Initial] (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI           Description
** 1    2022-08-30   MY        JAZZ-42472   Initial
** 2    2023-08-11   BK        JAZZ-58752   Update for new gl data structure
** 3	2024-04-11	 DM			JAZZ-70189	Budget Config used for Report comparison is processed as well
*************************************************************/

	exec [dbo].[procSysDropTempTable] '#SRC'
	exec [dbo].[procSysDropTempTable] '#SourceDimensionality'
	exec [dbo].[procSysDropTempTable] '#departments'		
	exec [dbo].[procSysDropTempTable] '#adjustedRecords'
	exec [dbo].[procSysDropTempTable] '#tempUnpivoted'
	exec [dbo].[procSysDropTempTable] '#dataToUpdate'
	exec [dbo].[procSysDropTempTable] '#joinedGLData'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) 
	
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.GeneralLedger 
		WHERE BudgetConfigID = @BudgetConfigID
	END

	CREATE TABLE #SRC (
		GeneralLedgerID INT, 
		BudgetConfigID INT, 
		EntityGroupConfigID INT, 
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		FinancialReportingID INT, 
		APEModelSectionID INT, 
		VariabilityID INT, 
		UnitTypeID SMALLINT, 
		TimeClassID TINYINT,
		FiscalYearID SMALLINT, 
		FiscalMonthID TINYINT,
		OriginalValue DECIMAL(19, 8)
	)

	CREATE TABLE #joinedGLData (
		GeneralLedgerID INT, 
		BudgetConfigID INT, 
		EntityGroupConfigID INT, 
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		FinancialReportingID INT, 
		APEModelSectionID INT, 
		VariabilityID INT, 
		UnitTypeID SMALLINT, 
		TimeClassID TINYINT,
		FiscalYearID SMALLINT, 
		Month01 DECIMAL(19, 8), 
		Month02 DECIMAL(19, 8), 
		Month03 DECIMAL(19, 8), 
		Month04 DECIMAL(19, 8), 
		Month05 DECIMAL(19, 8), 
		Month06 DECIMAL(19, 8), 
		Month07 DECIMAL(19, 8), 
		Month08 DECIMAL(19, 8), 
		Month09 DECIMAL(19, 8), 
		Month10 DECIMAL(19, 8), 
		Month11 DECIMAL(19, 8), 
		Month12 DECIMAL(19, 8)
	)
	
	INSERT INTO #joinedGLData (GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,
		Month09, Month10, Month11, Month12)
	SELECT
		gl.GeneralLedgerID, 
		gl.BudgetConfigID, 
		gl.EntityGroupConfigID, 
		gl.EntityID, 
		gl.DepartmentID, 
		gl.AccountID, 
		gl.FinancialReportingID, 
		gl.APEModelSectionID, 
		gl.VariabilityID, 
		34 as UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		gl.InitialBudget01 AS Month01,
		gl.InitialBudget02 AS Month02,
		gl.InitialBudget03 AS Month03,
		gl.InitialBudget04 AS Month04,
		gl.InitialBudget05 AS Month05,
		gl.InitialBudget06 AS Month06,
		gl.InitialBudget07 AS Month07,
		gl.InitialBudget08 AS Month08,
		gl.InitialBudget09 AS Month09,
		gl.InitialBudget10 AS Month10,
		gl.InitialBudget11 AS Month11,
		gl.InitialBudget12 AS Month12
	FROM fp.GeneralLedger gl 
		INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = gl.DepartmentID
	WHERE gl.BudgetConfigID = @BudgetConfigID
	
	INSERT INTO #joinedGLData (GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
		VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,
		Month09, Month10, Month11, Month12)
	SELECT
		gl.GeneralLedgerID, 
		gl.BudgetConfigID, 
		gl.EntityGroupConfigID, 
		gl.EntityID, 
		gl.DepartmentID, 
		gl.AccountID, 
		gl.FinancialReportingID, 
		gl.APEModelSectionID, 
		gl.VariabilityID, 
		34 as UnitTypeID, 
		12 as TimeClassID,
		bc.FiscalYearID - 1, 
		gl.InitialProjection01 AS Month01,
		gl.InitialProjection02 AS Month02,
		gl.InitialProjection03 AS Month03,
		gl.InitialProjection04 AS Month04,
		gl.InitialProjection05 AS Month05,
		gl.InitialProjection06 AS Month06,
		gl.InitialProjection07 AS Month07,
		gl.InitialProjection08 AS Month08,
		gl.InitialProjection09 AS Month09,
		gl.InitialProjection10 AS Month10,
		gl.InitialProjection11 AS Month11,
		gl.InitialProjection12 AS Month12
	FROM fp.GeneralLedger gl 
		INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = gl.DepartmentID
	WHERE gl.BudgetConfigID = @BudgetConfigID

	CREATE CLUSTERED INDEX inx_src ON #SRC (
		GeneralLedgerID 
		,BudgetConfigID 
		,EntityGroupConfigID 
		,EntityID
		,DepartmentID
		,AccountID
		,FinancialReportingID
		,APEModelSectionID
		,VariabilityID
		,UnitTypeID
		,TimeClassID
		,FiscalYearID
		,FiscalMonthID
	)

	-- Pivot the data into the #SRC Table
	INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue)
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, m.FiscalMonthID, OriginalValue
		FROM #joinedGLData FGL
		CROSS APPLY (
			VALUES 
			(1, Month01),
			(2, Month02),
			(3, Month03),
			(4, Month04),
			(5, Month05),
			(6, Month06),
			(7, Month07),
			(8, Month08),
			(9, Month09),
			(10, Month10),
			(11, Month11),
			(12, Month12)) cv (FiscalMonth, OriginalValue)
	INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = cv.FiscalMonth
	WHERE cv.OriginalValue != 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some.
	

	-- Get all of the departments in that could be affected. We need to get this list to eliminate
	-- the null check in the join in the with statement.
	SELECT DISTINCT DepartmentID INTO #departments 
	FROM (
		SELECT DISTINCT DepartmentID FROM #SRC
		UNION ALL
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality
	) data		

	;WITH TGT AS 
	(
		SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue
		FROM fp.FactReportGeneralLedger FRS
			INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)

		MERGE TGT AS target
		USING #SRC AS source
			ON (
						target.GeneralLedgerID = source.GeneralLedgerID
					AND target.BudgetConfigID = source.BudgetConfigID
					AND target.EntityGroupConfigID = source.EntityGroupConfigID
					AND target.EntityID = source.EntityID
					AND target.DepartmentID = source.DepartmentID
					AND target.AccountID = source.AccountID
					AND target.FinancialReportingID = source.FinancialReportingID
					AND target.APEModelSectionID = source.APEModelSectionID
					AND target.VariabilityID = source.VariabilityID
					AND target.UnitTypeID = source.UnitTypeID
					AND target.TimeClassID = source.TimeClassID
					AND target.FiscalYearID = source.FiscalYearID
					AND target.FiscalMonthID = source.FiscalMonthID 
					)
		WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue)
			THEN
				UPDATE
				SET target.OriginalValue = ISNULL(source.OriginalValue, 0)
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					GeneralLedgerID
					,BudgetConfigID
					,EntityGroupConfigID
					,EntityID
					,DepartmentID
					,AccountID
					,FinancialReportingID
					,APEModelSectionID
					,VariabilityID
					,UnitTypeID
					,TimeClassID
					,FiscalYearID
					,FiscalMonthID
					,OriginalValue
					)
				VALUES (
					source.GeneralLedgerID
					,source.BudgetConfigID
					,source.EntityGroupConfigID
					,source.EntityID
					,source.DepartmentID
					,source.AccountID
					,source.FinancialReportingID
					,source.APEModelSectionID
					,source.VariabilityID
					,source.UnitTypeID
					,source.TimeClassID
					,source.FiscalYearID
					,source.FiscalMonthID
					,ISNULL(source.OriginalValue, 0)
					);
	-- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted.

	-------------------------------------------------------------------------------------------------------
	-- Data not flowing through into reports after setting the record to 0
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above because we only populate records that are not 0
	-------------------------------------------------------------------------------------------------------

	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	/*SELECT 
		cv.GeneralLedgerID, 
		cv.BudgetConfigID, 
		cv.EntityGroupConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.FinancialReportingID, 
		cv.APEModelSectionID, 
		cv.VariabilityID, 
		cv.UnitTypeID, 
		cv.TimeClassID,
		cv.FiscalYearID, 
		m.FiscalMonthID,
		SUM(cv.OriginalValue) AS OriginalValue
	FROM (*/
	SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FGL.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, 
			VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, m.FiscalMonthID, OriginalValue
	INTO #tempUnpivoted
		FROM #joinedGLData FGL
			INNER JOIN #SourceDimensionality dept ON FGL.DepartmentID = dept.DepartmentID
		CROSS APPLY (
			VALUES 
			(1, Month01),
			(2, Month02),
			(3, Month03),
			(4, Month04),
			(5, Month05),
			(6, Month06),
			(7, Month07),
			(8, Month08),
			(9, Month09),
			(10, Month10),
			(11, Month11),
			(12, Month12)) cv (FiscalMonth, OriginalValue)	
	INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = cv.FiscalMonth
	WHERE cv.OriginalValue = 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some.
	
		
	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT	
		vw.GeneralLedgerID,
		vw.TimeClassID,
		vw.FiscalMonthID,
		vw.UnitTypeID,
		vw.OriginalValue
	INTO #dataToUpdate
	FROM [fp].[FactReportGeneralLedger] frgl
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #tempUnpivoted vw ON vw.GeneralLedgerID = frgl.GeneralLedgerID 
			AND vw.FiscalMonthID = frgl.FiscalMonthID 
			AND vw.UnitTypeID = frgl.UnitTypeID 
			AND vw.FiscalYearID = frgl.FiscalYearID
			AND vw.TimeClassID = frgl.TimeClassID
	WHERE frgl.BudgetConfigID = @BudgetConfigID
		AND vw.OriginalValue != frgl.OriginalValue

	-- Update the records
	UPDATE frgl
	SET 
		frgl.OriginalValue = ISNULL(upd.OriginalValue, 0)
	FROM [fp].[FactReportGeneralLedger] frgl
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = frgl.DepartmentID
		INNER JOIN #dataToUpdate upd ON upd.GeneralLedgerID = frgl.GeneralLedgerID AND upd.FiscalMonthID = frgl.FiscalMonthID AND upd.UnitTypeID = frgl.UnitTypeID AND frgl.TimeClassID = upd.TimeClassID

END
GO


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

-- fp.procProcessReportFactStaffing_Initial
/**************************************************************  
** Change History  
**************************************************************  
** CID  Date         Author    WI          Description  
** 1    2022-08-30   MY        JAZZ-42472  Initial
** 2    2023-11-01   BW        JAZZ-62798  New data model update
** 3	2024-07-04	 DM		   JAZZ-70314  Budget Config used for Report comparison is processed as well
*************************************************************/  
CREATE     PROCEDURE [fp].[procProcessReportFactStaffing_Initial] (  
	@BudgetConfigID INT,  
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)  
WITH RECOMPILE  
AS  
BEGIN  
	exec [dbo].[procSysDropTempTable] '#SRC'  
	exec [dbo].[procSysDropTempTable] '#SourceDimensionality'  
	exec [dbo].[procSysDropTempTable] '#departments'  
	exec [dbo].[procSysDropTempTable] '#joinedStaffingData'  
	exec [dbo].[procSysDropTempTable] '#tempUnpivoted'  
	exec [dbo].[procSysDropTempTable] '#dataToUpdate'  
  
	--only the active config is supported currently  
	if (not exists(select 1 from fp.BudgetConfig where (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) begin return end  
  
	SELECT DISTINCT DepartmentID INTO #SourceDimensionality 
	FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)   
  
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.Staffing 
		WHERE BudgetConfigID = @BudgetConfigID
	END

	CREATE TABLE #SRC (  
		[BudgetConfigID] INT,   
		[EntityID] INT,   
		[DepartmentID] INT,   
		[JobCodeID] INT,   
		[PayCodeGroupID] INT,   
		[VariabilityID] INT,   
		[ProductiveClassID] INT,   
		[EmployeeID] INT,
		[ProviderID] INT,
		[ProviderLineItemID] INT,
		[ProviderTypeID] INT,
		[ProviderSpecialtyID] INT,
		[UnitTypeID] SMALLINT,   
		[TimeClassID] TINYINT,   
		[FiscalMonthID] TINYINT,   
		[FiscalYearID] SMALLINT,   
		[OriginalValue] DECIMAL(19, 8)
	);  

	CREATE TABLE #joinedStaffingData (
		[StaffingID] INT, 
		[BudgetConfigID] INT,   
		[EntityID] INT,   
		[DepartmentID] INT,   
		[JobCodeID] INT,   
		[PayCodeGroupID] INT,   
		[VariabilityID] INT,   
		[ProductiveClassID] INT,   
		[EmployeeID] INT,
		[ProviderID] INT,
		[ProviderLineItemID] INT,
		[ProviderTypeID] INT,
		[ProviderSpecialtyID] INT,
		UnitTypeID SMALLINT, 
		TimeClassID TINYINT,
		FiscalYearID SMALLINT, 
		Month01 DECIMAL(19, 8), 
		Month02 DECIMAL(19, 8), 
		Month03 DECIMAL(19, 8), 
		Month04 DECIMAL(19, 8), 
		Month05 DECIMAL(19, 8), 
		Month06 DECIMAL(19, 8), 
		Month07 DECIMAL(19, 8), 
		Month08 DECIMAL(19, 8), 
		Month09 DECIMAL(19, 8), 
		Month10 DECIMAL(19, 8), 
		Month11 DECIMAL(19, 8), 
		Month12 DECIMAL(19, 8)
	)

	INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		34 AS UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		fs.InitialBudgetDollars01 AS Month01,
		fs.InitialBudgetDollars02 AS Month02,
		fs.InitialBudgetDollars03 AS Month03,
		fs.InitialBudgetDollars04 AS Month04,
		fs.InitialBudgetDollars05 AS Month05,
		fs.InitialBudgetDollars06 AS Month06,
		fs.InitialBudgetDollars07 AS Month07,
		fs.InitialBudgetDollars08 AS Month08,
		fs.InitialBudgetDollars09 AS Month09,
		fs.InitialBudgetDollars10 AS Month10,
		fs.InitialBudgetDollars11 AS Month11,
		fs.InitialBudgetDollars12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

	INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		51 AS UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		fs.InitialBudgetHours01 AS Month01,
		fs.InitialBudgetHours02 AS Month02,
		fs.InitialBudgetHours03 AS Month03,
		fs.InitialBudgetHours04 AS Month04,
		fs.InitialBudgetHours05 AS Month05,
		fs.InitialBudgetHours06 AS Month06,
		fs.InitialBudgetHours07 AS Month07,
		fs.InitialBudgetHours08 AS Month08,
		fs.InitialBudgetHours09 AS Month09,
		fs.InitialBudgetHours10 AS Month10,
		fs.InitialBudgetHours11 AS Month11,
		fs.InitialBudgetHours12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

	INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		144 AS UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		fs.InitialBudgetFTEs01 AS Month01,
		fs.InitialBudgetFTEs02 AS Month02,
		fs.InitialBudgetFTEs03 AS Month03,
		fs.InitialBudgetFTEs04 AS Month04,
		fs.InitialBudgetFTEs05 AS Month05,
		fs.InitialBudgetFTEs06 AS Month06,
		fs.InitialBudgetFTEs07 AS Month07,
		fs.InitialBudgetFTEs08 AS Month08,
		fs.InitialBudgetFTEs09 AS Month09,
		fs.InitialBudgetFTEs10 AS Month10,
		fs.InitialBudgetFTEs11 AS Month11,
		fs.InitialBudgetFTEs12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

	INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		172 AS UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		fs.InitialBudgetRate01 AS Month01,
		fs.InitialBudgetRate02 AS Month02,
		fs.InitialBudgetRate03 AS Month03,
		fs.InitialBudgetRate04 AS Month04,
		fs.InitialBudgetRate05 AS Month05,
		fs.InitialBudgetRate06 AS Month06,
		fs.InitialBudgetRate07 AS Month07,
		fs.InitialBudgetRate08 AS Month08,
		fs.InitialBudgetRate09 AS Month09,
		fs.InitialBudgetRate10 AS Month10,
		fs.InitialBudgetRate11 AS Month11,
		fs.InitialBudgetRate12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID
	
	INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		34 AS UnitTypeID, 
		12 as TimeClassID,
		bc.FiscalYearID - 1, 
		fs.InitialProjectionDollars01 AS Month01,
		fs.InitialProjectionDollars02 AS Month02,
		fs.InitialProjectionDollars03 AS Month03,
		fs.InitialProjectionDollars04 AS Month04,
		fs.InitialProjectionDollars05 AS Month05,
		fs.InitialProjectionDollars06 AS Month06,
		fs.InitialProjectionDollars07 AS Month07,
		fs.InitialProjectionDollars08 AS Month08,
		fs.InitialProjectionDollars09 AS Month09,
		fs.InitialProjectionDollars10 AS Month10,
		fs.InitialProjectionDollars11 AS Month11,
		fs.InitialProjectionDollars12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID
  
  	INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		51 AS UnitTypeID, 
		12 as TimeClassID,
		bc.FiscalYearID - 1, 
		fs.InitialProjectionHours01 AS Month01,
		fs.InitialProjectionHours02 AS Month02,
		fs.InitialProjectionHours03 AS Month03,
		fs.InitialProjectionHours04 AS Month04,
		fs.InitialProjectionHours05 AS Month05,
		fs.InitialProjectionHours06 AS Month06,
		fs.InitialProjectionHours07 AS Month07,
		fs.InitialProjectionHours08 AS Month08,
		fs.InitialProjectionHours09 AS Month09,
		fs.InitialProjectionHours10 AS Month10,
		fs.InitialProjectionHours11 AS Month11,
		fs.InitialProjectionHours12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

		INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		144 AS UnitTypeID, 
		12 as TimeClassID,
		bc.FiscalYearID - 1, 
		fs.InitialProjectionFTEs01 AS Month01,
		fs.InitialProjectionFTEs02 AS Month02,
		fs.InitialProjectionFTEs03 AS Month03,
		fs.InitialProjectionFTEs04 AS Month04,
		fs.InitialProjectionFTEs05 AS Month05,
		fs.InitialProjectionFTEs06 AS Month06,
		fs.InitialProjectionFTEs07 AS Month07,
		fs.InitialProjectionFTEs08 AS Month08,
		fs.InitialProjectionFTEs09 AS Month09,
		fs.InitialProjectionFTEs10 AS Month10,
		fs.InitialProjectionFTEs11 AS Month11,
		fs.InitialProjectionFTEs12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

		INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, 
		ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08,	Month09, Month10, Month11, Month12)
	SELECT
		fs.StaffingID, 
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.VariabilityID, 
		fs.ProductiveClassID, 
		fs.EmployeeID, 
		fs.ProviderID, 
		fs.ProviderLineItemID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		172 AS UnitTypeID, 
		12 as TimeClassID,
		bc.FiscalYearID - 1, 
		fs.InitialProjectionRate01 AS Month01,
		fs.InitialProjectionRate02 AS Month02,
		fs.InitialProjectionRate03 AS Month03,
		fs.InitialProjectionRate04 AS Month04,
		fs.InitialProjectionRate05 AS Month05,
		fs.InitialProjectionRate06 AS Month06,
		fs.InitialProjectionRate07 AS Month07,
		fs.InitialProjectionRate08 AS Month08,
		fs.InitialProjectionRate09 AS Month09,
		fs.InitialProjectionRate10 AS Month10,
		fs.InitialProjectionRate11 AS Month11,
		fs.InitialProjectionRate12 AS Month12
	FROM fp.Staffing fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

	-- Pivot the data into the #SRC Table
	INSERT INTO #SRC([BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID], 
			[EmployeeID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID],   
			[UnitTypeID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [OriginalValue])
	SELECT 
		cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.JobCodeID, 
		cv.PayCodeGroupID,
		cv.VariabilityID, 
		cv.ProductiveClassID, 
		cv.EmployeeID, 
		cv.ProviderID, 
		cv.ProviderLineItemID, 
		cv.ProviderTypeID, 
		cv.ProviderSpecialtyID, 
		cv.UnitTypeID, 
		cv.TimeClassID,
		cv.FiscalYearID, 
		m.FiscalMonthID,
		SUM(cv.Value) AS OriginalValue
	FROM (
		SELECT BudgetConfigID, EntityID, DepartmentID, JobCodeID, VariabilityID, ProductiveClassID, PayCodeGroupID, 
			EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, 
			TimeClassID, FiscalYearID, FiscalMonth, Value
		FROM #joinedStaffingData FGL
		CROSS APPLY (
			VALUES 
			('Month01', Month01),
			('Month02', Month02),
			('Month03', Month03),
			('Month04', Month04),
			('Month05', Month05),
			('Month06', Month06),
			('Month07', Month07),
			('Month08', Month08),
			('Month09', Month09),
			('Month10', Month10),
			('Month11', Month11),
			('Month12', Month12)) X (FiscalMonth, Value)
	) cv
		INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
	WHERE cv.Value != 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some.
	GROUP BY cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.JobCodeID, 
		cv.VariabilityID, 
		cv.ProductiveClassID, 
		cv.PayCodeGroupID,
		cv.EmployeeID, 
		cv.ProviderID, 
		cv.ProviderLineItemID, 
		cv.ProviderTypeID, 
		cv.ProviderSpecialtyID, 
		cv.UnitTypeID, 
		cv.TimeClassID,
		cv.FiscalYearID, 
		m.FiscalMonthID

	CREATE CLUSTERED INDEX inx_src ON #SRC (  
		 BudgetConfigID  
		,EntityID  
		,DepartmentID  
		,JobCodeID  
		,PayCodeGroupID  
		,VariabilityID  
		,ProductiveClassID  
		,UnitTypeID  
		,TimeClassID  
		,FiscalMonthID  
		,FiscalYearID  
		,EmployeeID
		,ProviderID
		,ProviderLineItemID
		,ProviderTypeID
		,ProviderSpecialtyID
	)  
  
	-- Get all of the departments in that could be affected. We need to get this list to eliminate  
	-- the null check in the join in the with statement.  
	SELECT DISTINCT DepartmentID INTO #departments   
	FROM (  
		SELECT DISTINCT DepartmentID FROM #SRC  
		UNION ALL  
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality  
	) data   
  
	;WITH TGT AS   
	(  
		SELECT [BudgetConfigID], [EntityID], [FRS].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],   
			[ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue], [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID]
		FROM fp.FactReportStaffing FRS  
			INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID  
		WHERE FRS.BudgetConfigID  = @BudgetConfigID  
	)  
  
   MERGE TGT AS target  
   USING #SRC AS source  
    ON (  
       target.BudgetConfigID = source.BudgetConfigID  
      AND target.EntityID   = source.EntityID  
      AND target.DepartmentID  = source.DepartmentID  
      AND target.JobCodeID  = source.JobCodeID  
      AND target.PayCodeGroupID = source.PayCodeGroupID  
      AND target.VariabilityID = source.VariabilityID  
      AND target.ProductiveClassID= source.ProductiveClassID  
      AND target.UnitTypeID= source.UnitTypeID  
      AND target.TimeClassID= source.TimeClassID  
      AND target.FiscalMonthID= source.FiscalMonthID  
      AND target.FiscalYearID= source.FiscalYearID  
      AND target.EmployeeID= source.EmployeeID  
	  AND target.ProviderID= source.ProviderID
	  AND target.ProviderLineItemID= source.ProviderLineItemID
	  AND target.ProviderTypeID= source.ProviderTypeID
	  AND target.ProviderSpecialtyID= source.ProviderSpecialtyID  
      )  
   WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue)  
    THEN  
     UPDATE SET   
		 target.OriginalValue = ISNULL(source.OriginalValue, 0)
   WHEN NOT MATCHED BY TARGET  
    THEN  
     INSERT (  
        BudgetConfigID  
       ,EntityID  
       ,DepartmentID  
       ,JobCodeID  
       ,PayCodeGroupID  
       ,VariabilityID  
       ,ProductiveClassID  
       ,UnitTypeID  
       ,TimeClassID  
       ,FiscalMonthID  
       ,FiscalYearID  
       ,OriginalValue  
	   ,EmployeeID
	   ,ProviderID
	   ,ProviderLineItemID
	   ,ProviderTypeID
	   ,ProviderSpecialtyID
      )  
     VALUES (  
      source. BudgetConfigID  
      ,source.EntityID  
      ,source.DepartmentID  
      ,source.JobCodeID  
      ,source.PayCodeGroupID  
      ,source.VariabilityID  
      ,source.ProductiveClassID  
      ,source.UnitTypeID  
      ,source.TimeClassID  
      ,source.FiscalMonthID  
      ,source.FiscalYearID  
      ,ISNULL(source.OriginalValue, 0)
	  ,source.EmployeeID
	  ,source.ProviderID
	  ,source.ProviderLineItemID
	  ,source.ProviderTypeID
	  ,source.ProviderSpecialtyID
    );  
	-- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted.
		
	--remove invalid FTE data  
	DELETE fs FROM fp.FactReportStaffing fs INNER JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON fs.PayCodeGroupID = exc.PayCodeGroupID WHERE fs.UnitTypeID = 144; 

	-------------------------------------------------------------------------------------------------------
	-- Data not flowing through into reports after setting the record to 0
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above because we only populate records that are not 0
	-------------------------------------------------------------------------------------------------------
	
	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	SELECT 
		cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.JobCodeID, 
		cv.PayCodeGroupID,
		cv.VariabilityID, 
		cv.ProductiveClassID, 
		cv.EmployeeID, 
		cv.ProviderID, 
		cv.ProviderLineItemID, 
		cv.ProviderTypeID, 
		cv.ProviderSpecialtyID, 
		cv.UnitTypeID, 
		cv.TimeClassID,
		cv.FiscalYearID, 
		m.FiscalMonthID,
		SUM(cv.Value) AS OriginalValue
	INTO #tempUnpivoted
	FROM (
		SELECT BudgetConfigID, EntityID, FGL.DepartmentID, JobCodeID, VariabilityID, ProductiveClassID, PayCodeGroupID, 
			EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, 
			TimeClassID, FiscalYearID, FiscalMonth, Value
		FROM #joinedStaffingData FGL
			INNER JOIN #SourceDimensionality dept ON FGL.DepartmentID = dept.DepartmentID
		CROSS APPLY (
			VALUES 
			('Month01', Month01),
			('Month02', Month02),
			('Month03', Month03),
			('Month04', Month04),
			('Month05', Month05),
			('Month06', Month06),
			('Month07', Month07),
			('Month08', Month08),
			('Month09', Month09),
			('Month10', Month10),
			('Month11', Month11),
			('Month12', Month12)) X (FiscalMonth, Value)
	) cv
		INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
	WHERE cv.Value = 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some.
	GROUP BY cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.JobCodeID, 
		cv.VariabilityID, 
		cv.ProductiveClassID, 
		cv.PayCodeGroupID,
		cv.EmployeeID, 
		cv.ProviderID, 
		cv.ProviderLineItemID, 
		cv.ProviderTypeID, 
		cv.ProviderSpecialtyID, 
		cv.UnitTypeID, 
		cv.TimeClassID,
		cv.FiscalYearID, 
		m.FiscalMonthID

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		target.BudgetConfigID,
		target.EntityID,
		target.DepartmentID,
		target.JobCodeID,
		target.VariabilityID,
		target.ProductiveClassID,
		target.PayCodeGroupID,
		target.EmployeeID,
		target.ProviderID,
		target.ProviderTypeID,
		target.ProviderSpecialtyID,
		target.ProviderLineItemID,
		target.UnitTypeID,
		target.TimeClassID, 
		target.FiscalMonthID,
		target.FiscalYearID,
		SUM(target.OriginalValue) AS OriginalValue
	INTO #dataToUpdate
	FROM [fp].[FactReportStaffing] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID				= source.EntityID
						AND target.DepartmentID			= source.DepartmentID
						AND target.JobCodeID			= source.JobCodeID
						AND target.PayCodeGroupID		= source.PayCodeGroupID
						AND target.ProductiveClassID	= source.ProductiveClassID
						AND target.VariabilityID		= source.VariabilityID
						AND target.EmployeeID			= source.EmployeeID
						AND target.UnitTypeID			= source.UnitTypeID
						AND target.TimeClassID			= source.TimeClassID
						AND target.FiscalMonthID		= source.FiscalMonthID
						AND target.FiscalYearID			= source.FiscalYearID
						AND target.ProviderID			= source.ProviderID
						AND target.ProviderTypeID		= source.ProviderTypeID
						AND target.ProviderSpecialtyID	= source.ProviderSpecialtyID
						AND target.ProviderLineItemID	= source.ProviderLineItemID
	WHERE source.BudgetConfigID = @BudgetConfigID
		AND target.OriginalValue != source.OriginalValue
	GROUP BY target.BudgetConfigID,
		target.EntityID,
		target.DepartmentID,
		target.JobCodeID,
		target.PayCodeGroupID,
		target.ProductiveClassID,
		target.VariabilityID,
		target.EmployeeID,
		target.UnitTypeID,
		target.TimeClassID, 
		target.FiscalMonthID,
		target.FiscalYearID,
		target.ProviderID,
		target.ProviderTypeID,
		target.ProviderSpecialtyID,
		target.ProviderLineItemID

	-- Update the records
	UPDATE source
	SET 
		source.OriginalValue = ISNULL(target.OriginalValue, 0)
	FROM [fp].[FactReportStaffing] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID				= source.EntityID
						AND target.DepartmentID			= source.DepartmentID
						AND target.JobCodeID			= source.JobCodeID
						AND target.PayCodeGroupID		= source.PayCodeGroupID
						AND target.ProductiveClassID	= source.ProductiveClassID
						AND target.VariabilityID		= source.VariabilityID
						AND target.EmployeeID			= source.EmployeeID
						AND target.UnitTypeID			= source.UnitTypeID
						AND target.TimeClassID			= source.TimeClassID
						AND target.FiscalMonthID		= source.FiscalMonthID
						AND target.FiscalYearID			= source.FiscalYearID
						AND target.ProviderID			= source.ProviderID
						AND target.ProviderTypeID		= source.ProviderTypeID
						AND target.ProviderSpecialtyID	= source.ProviderSpecialtyID
						AND target.ProviderLineItemID	= source.ProviderLineItemID
END
GO


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

-- fp.procProcessReportFactStaffing_TargetBudget
/**************************************************************  
** Change History  
**************************************************************  
** CID  Date         Author    WI          Description  
** 1    2018-12-24   IP        B-21543     Added temp table to index source as well  
** 2    2019-01-09   GF        B-21715     Optimize full config refresh case  
** 3    2019-01-11   GF        B-21715     Optimize targeted refresh case  
** 4    2019-04-15   GF        D-08357     Removed differential and dollars-only FTEs  
** 5    2019-05-02   GF        X-XXXXX     Remove special handling of all case to make concurrency work  
** 6    2019-07-22   MY        X-XXXXX     Performance updates to reports  
** 7    2019-11-13   MD        B-24632     Add EmployeeID to staffing sampling
** 8    2020-02-18   MY        JAZZ-15375  Roll-up data above Provider for Report
** 9	2021-11-30	 SD		   JAZZ-30301  Add provider dimensions to Staffing reporting data sources
** 10   2022-08-30   MY        JAZZ-42472  Improve Pivoting of Data for Reports
** 11   2022-10-28   MY        JAZZ-45443  Roll proc back to before perf changes
** 12	2024-07-04	 DM		   JAZZ-70314  Budget Config used for Report comparison is processed as well
*************************************************************/  
CREATE     PROCEDURE [fp].[procProcessReportFactStaffing_TargetBudget] (  
	@BudgetConfigID INT,  
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)  
WITH RECOMPILE  
AS  
BEGIN  
	
	exec [dbo].[procSysDropTempTable] '#SRC'  
	exec [dbo].[procSysDropTempTable] '#SourceDimensionality'  
	exec [dbo].[procSysDropTempTable] '#departments'  
  
	--only the active and used for comparison configs are supported currently  
	if (not exists(select 1 from fp.BudgetConfig where (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) begin return end  
  
	SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)   
  
	CREATE TABLE #SRC (  
		[BudgetConfigID] INT,   
		[EntityID] INT,   
		[DepartmentID] INT,   
		[JobCodeID] INT,   
		[PayCodeGroupID] INT,   
		[VariabilityID] INT,   
		[ProductiveClassID] INT,   
		[UnitTypeID] SMALLINT,   
		[TimeClassID] TINYINT,   
		[FiscalMonthID] TINYINT,   
		[FiscalYearID] SMALLINT,   
		[OriginalValue] DECIMAL(19, 8),   
		[Value] DECIMAL(19, 8),   
		[ManagerValue] DECIMAL(19, 8), 
		[EmployeeID] INT,
		[ProviderID] INT,
		[ProviderLineItemID] INT,
		[ProviderTypeID] INT,
		[ProviderSpecialtyID] INT
	);  
  
	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)  
	BEGIN  
		INSERT INTO #SRC ([BudgetConfigID], [EntityID], [VW].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID],   
			[UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue], [Value], [ManagerValue], [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID])  
		SELECT [BudgetConfigID], [EntityID], VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],   
			[ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], 
			SUM([OriginalValue]), SUM([Value]), SUM([ManagerValue]), [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID]
		FROM [fp].[viewFactStaffing_Unpivoted_source] VW  
			INNER JOIN #SourceDimensionality ft ON ft.DepartmentID = VW.DepartmentID  
		WHERE VW.BudgetConfigID  = @BudgetConfigID  
			AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) 
		GROUP BY [BudgetConfigID], [EntityID], VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],   
			[ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID]
	END ELSE BEGIN  
		INSERT INTO #SRC ([BudgetConfigID], [EntityID], [VW].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID],   
			[UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue], [Value], [ManagerValue], [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID])  
		SELECT [BudgetConfigID], [EntityID],  VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],   
			[ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], 
			SUM([OriginalValue]), SUM([Value]), SUM([ManagerValue]), [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID]
		FROM [fp].[viewFactStaffing_Unpivoted_source] VW  
		WHERE VW.BudgetConfigID  = @BudgetConfigID  
			AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0)  
		GROUP BY [BudgetConfigID], [EntityID], VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],   
			[ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID]
	END  
  
	CREATE CLUSTERED INDEX inx_src ON #SRC (  
		 BudgetConfigID  
		,EntityID  
		,DepartmentID  
		,JobCodeID  
		,PayCodeGroupID  
		,VariabilityID  
		,ProductiveClassID  
		,UnitTypeID  
		,TimeClassID  
		,FiscalMonthID  
		,FiscalYearID  
		,EmployeeID
		,ProviderID
		,ProviderLineItemID
		,ProviderTypeID
		,ProviderSpecialtyID
	)  
  
	-- Get all of the departments in that could be affected. We need to get this list to eliminate  
	-- the null check in the join in the with statement.  
	SELECT DISTINCT DepartmentID INTO #departments   
	FROM (  
		SELECT DISTINCT DepartmentID FROM #SRC  
		UNION ALL  
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality  
	) data   
  
	;WITH TGT AS   
	(  
		SELECT [BudgetConfigID], [EntityID], [FRS].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID],   
			[ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue],   
			[Value], [ManagerValue], [EmployeeID], [ProviderID], [ProviderLineItemID],
			[ProviderTypeID], [ProviderSpecialtyID]
		FROM fp.FactReportStaffing FRS  
			INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID  
		WHERE FRS.BudgetConfigID  = @BudgetConfigID  
	)  
  
   MERGE TGT AS target  
   USING #SRC AS source  
    ON (  
       target.BudgetConfigID = source.BudgetConfigID  
      AND target.EntityID   = source.EntityID  
      AND target.DepartmentID  = source.DepartmentID  
      AND target.JobCodeID  = source.JobCodeID  
      AND target.PayCodeGroupID = source.PayCodeGroupID  
      AND target.VariabilityID = source.VariabilityID  
      AND target.ProductiveClassID= source.ProductiveClassID  
      AND target.UnitTypeID= source.UnitTypeID  
      AND target.TimeClassID= source.TimeClassID  
      AND target.FiscalMonthID= source.FiscalMonthID  
      AND target.FiscalYearID= source.FiscalYearID  
      AND target.EmployeeID= source.EmployeeID  
	  AND target.ProviderID= source.ProviderID
	  AND target.ProviderLineItemID= source.ProviderLineItemID
	  AND target.ProviderTypeID= source.ProviderTypeID
	  AND target.ProviderSpecialtyID= source.ProviderSpecialtyID  
      )  
   WHEN MATCHED AND (  
     target.OriginalValue <> source.OriginalValue  
     OR target.Value <> source.Value  
     OR target.ManagerValue <> source.ManagerValue)  
    THEN  
     UPDATE SET  
     target.OriginalValue = source.OriginalValue,  
     target.Value = source.Value,  
     target.ManagerValue = source.ManagerValue  
   WHEN NOT MATCHED BY TARGET  
    THEN  
     INSERT (  
        BudgetConfigID  
       ,EntityID  
       ,DepartmentID  
       ,JobCodeID  
       ,PayCodeGroupID  
       ,VariabilityID  
       ,ProductiveClassID  
       ,UnitTypeID  
       ,TimeClassID  
       ,FiscalMonthID  
       ,FiscalYearID  
       ,OriginalValue  
       ,Value  
       ,ManagerValue  
	   ,EmployeeID
	   ,ProviderID
	   ,ProviderLineItemID
	   ,ProviderTypeID
	   ,ProviderSpecialtyID
      )  
     VALUES (  
      source. BudgetConfigID  
      ,source.EntityID  
      ,source.DepartmentID  
      ,source.JobCodeID  
      ,source.PayCodeGroupID  
      ,source.VariabilityID  
      ,source.ProductiveClassID  
      ,source.UnitTypeID  
      ,source.TimeClassID  
      ,source.FiscalMonthID  
      ,source.FiscalYearID  
      ,source.OriginalValue  
      ,source.Value  
      ,source.ManagerValue  
	  ,source.EmployeeID
	  ,source.ProviderID
	  ,source.ProviderLineItemID
	  ,source.ProviderTypeID
	  ,source.ProviderSpecialtyID
      )  
   WHEN NOT MATCHED BY Source  
    THEN  
     DELETE;  
  
	--remove invalid FTE data  
	DELETE fs FROM fp.FactReportStaffing fs INNER JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON fs.PayCodeGroupID = exc.PayCodeGroupID WHERE fs.UnitTypeID = 144; 
	
END
GO


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

-- fp.procProcessReportFactStatistics_Initial
CREATE   PROCEDURE [fp].[procProcessReportFactStatistics_Initial] (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI		   Description
	** 1    2018-12-24   IP        B-21543	   Added temp table to index source as well
	** 2    2019-01-09   GF        B-21715	   Optimize full config refresh case
	** 3    2019-01-11   GF        B-21715	   Optimize targeted refresh case
	** 4    2019-05-02   GF        X-XXXXX     Remove special handling of all case to make concurrency work
	** 5    2019-07-22   MY        X-XXXXX	   Performance updates
	** 6    2020-01-13   MY        D-09168	   CCF: Data not flowing through into reports
	** 7    2020-02-18   MY        JAZZ-15375  Roll-up data above Provider for Report
	** 8    2021-05-10   MD        JAZZ-15686  Add Provider dimensions to Stats data sources 
	** 9    2021-11-10   BW        JAZZ-1358   Add dept to the filter when untargeted, to remove orphans 
	** 10   2022-08-30   MY        JAZZ-42472  Improve Pivoting of Data for Reports
	** 11   2024-07-16   YR        JAZZ-70315  Budget Config used for Report comparison is processed as well
	*************************************************************/
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#departments'
	EXEC [dbo].[procSysDropTempTable] '#joinedStatData'
	EXEC [dbo].[procSysDropTempTable] '#tempUnpivoted'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1)  AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.FactStatistics 
		WHERE BudgetConfigID = @BudgetConfigID
	END

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		PatientClassID INT,
		PayorID INT,
		FinancialReportingID INT,
		UnitTypeID SMALLINT,
		TimeClassID TINYINT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		ProviderID INT,
		ProviderTypeID INT,
		ProviderSpecialtyID INT,
		ProviderLineItemID INT,
		OriginalValue DECIMAL(19, 8)
	)

	CREATE TABLE #joinedStatData (
		StatisticsID INT, 
		BudgetConfigID INT, 
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		PatientClassID INT, 
		PayorID INT, 
		FinancialReportingID INT, 
		ProviderID INT, 
		ProviderTypeID INT, 
		ProviderSpecialtyID INT, 
		ProviderLineItemID INT, 
		UnitTypeID SMALLINT, 
		TimeClassID TINYINT,
		FiscalYearID SMALLINT, 
		Month01 DECIMAL(19, 8), 
		Month02 DECIMAL(19, 8), 
		Month03 DECIMAL(19, 8), 
		Month04 DECIMAL(19, 8), 
		Month05 DECIMAL(19, 8), 
		Month06 DECIMAL(19, 8), 
		Month07 DECIMAL(19, 8), 
		Month08 DECIMAL(19, 8), 
		Month09 DECIMAL(19, 8), 
		Month10 DECIMAL(19, 8), 
		Month11 DECIMAL(19, 8), 
		Month12 DECIMAL(19, 8)
	)

	INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, 
		ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID,  
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)
	SELECT
		fs.StatisticsID,
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.AccountID, 
		fs.PatientClassID, 
		fs.PayorID, 
		fs.FinancialReportingID, 
		fs.ProviderID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		fs.ProviderLineItemID,
		fs.UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		fs.InitialBudget01 AS Month01,
		fs.InitialBudget02 AS Month02,
		fs.InitialBudget03 AS Month03,
		fs.InitialBudget04 AS Month04,
		fs.InitialBudget05 AS Month05,
		fs.InitialBudget06 AS Month06,
		fs.InitialBudget07 AS Month07,
		fs.InitialBudget08 AS Month08,
		fs.InitialBudget09 AS Month09,
		fs.InitialBudget10 AS Month10,
		fs.InitialBudget11 AS Month11,
		fs.InitialBudget12 AS Month12
	FROM fp.FactStatistics fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

	INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, 
		ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID,  
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)
	SELECT
		fs.StatisticsID,
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.AccountID, 
		fs.PatientClassID, 
		fs.PayorID, 
		fs.FinancialReportingID, 
		fs.ProviderID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		fs.ProviderLineItemID,
		fs.UnitTypeID, 
		12 as TimeClassID,
		bc.FiscalYearID - 1, 
		fs.InitialProjection01 AS Month01,
		fs.InitialProjection02 AS Month02,
		fs.InitialProjection03 AS Month03,
		fs.InitialProjection04 AS Month04,
		fs.InitialProjection05 AS Month05,
		fs.InitialProjection06 AS Month06,
		fs.InitialProjection07 AS Month07,
		fs.InitialProjection08 AS Month08,
		fs.InitialProjection09 AS Month09,
		fs.InitialProjection10 AS Month10,
		fs.InitialProjection11 AS Month11,
		fs.InitialProjection12 AS Month12
	FROM fp.FactStatistics fs 
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID
	   
	CREATE CLUSTERED INDEX inx_src ON #SRC (
		BudgetConfigID	
		,EntityID			
		,DepartmentID		
		,AccountID		
		,PatientClassID	
		,PayorID			
		,FinancialReportingID
		,UnitTypeID		
		,TimeClassID		
		,FiscalMonthID	
		,FiscalYearID	
		,ProviderID
		,ProviderTypeID
		,ProviderSpecialtyID
		,ProviderLineItemID
	) WITH (DATA_COMPRESSION = PAGE)
						
	-- Pivot the data into the #SRC Table
	INSERT INTO #SRC(BudgetConfigID, EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, 
			ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID,
			OriginalValue)
	SELECT 
		cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID,
		m.FiscalMonthID, 
		SUM(cv.Value) AS OrginalValue
	FROM (
		SELECT BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID,
			ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonth, Value
		FROM #joinedStatData stat
		CROSS APPLY (
			VALUES 
			('Month01', Month01),
			('Month02', Month02),
			('Month03', Month03),
			('Month04', Month04),
			('Month05', Month05),
			('Month06', Month06),
			('Month07', Month07),
			('Month08', Month08),
			('Month09', Month09),
			('Month10', Month10),
			('Month11', Month11),
			('Month12', Month12)) X (FiscalMonth, Value)
	) cv
		INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
	WHERE cv.Value != 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some.
	GROUP BY cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID, 
		m.FiscalMonthID

	-- Get all of the departments in that could be affected. We need to get this list to eliminate
	-- the null check in the join in the with statement.
	SELECT DISTINCT DepartmentID INTO #departments 
	FROM (
		SELECT DISTINCT DepartmentID FROM #SRC
		UNION ALL
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality
	) data						

	;WITH TGT AS 
	(
		SELECT BudgetConfigID, EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID,
					TimeClassID, FiscalMonthID, FiscalYearID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID,
					OriginalValue 
		FROM fp.FactReportStatistics FRS
				INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)
			MERGE TGT AS target
			USING #SRC AS source
				ON (
							target.BudgetConfigID			= source.BudgetConfigID
						AND target.EntityID					= source.EntityID
						AND target.DepartmentID				= source.DepartmentID
						AND target.AccountID				= source.AccountID
						AND target.PatientClassID			= source.PatientClassID
						AND target.PayorID					= source.PayorID
						AND target.FinancialReportingID		= source.FinancialReportingID
						AND target.UnitTypeID				= source.UnitTypeID
						AND target.TimeClassID				= source.TimeClassID
						AND target.FiscalMonthID			= source.FiscalMonthID
						AND target.FiscalYearID				= source.FiscalYearID
						AND target.ProviderID				= source.ProviderID
						AND target.ProviderTypeID			= source.ProviderTypeID
						AND target.ProviderSpecialtyID		= source.ProviderSpecialtyID
						AND target.ProviderLineItemID		= source.ProviderLineItemID

						)
			WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue)
				THEN
					UPDATE SET
						target.OriginalValue = ISNULL(source.OriginalValue, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
							 BudgetConfigID
							,EntityID
							,DepartmentID
							,AccountID
							,PatientClassID
							,PayorID
							,FinancialReportingID
							,UnitTypeID
							,TimeClassID
							,FiscalMonthID
							,FiscalYearID
							,ProviderID
							,ProviderTypeID
							,ProviderSpecialtyID
							,ProviderLineItemID
							,OriginalValue
						)
					VALUES (
						source. BudgetConfigID
						,source.EntityID
						,source.DepartmentID
						,source.AccountID
						,source.PatientClassID
						,source.PayorID
						,source.FinancialReportingID
						,source.UnitTypeID
						,source.TimeClassID
						,source.FiscalMonthID
						,source.FiscalYearID
						,source.ProviderID
						,source.ProviderTypeID
						,source.ProviderSpecialtyID
						,source.ProviderLineItemID
						,ISNULL(source.OriginalValue, 0)
						);
	-- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted.

			
	-------------------------------------------------------------------------------------------------------
	-- Data not flowing through into reports after setting the record to 0
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above because we only populate records that are not 0
	-------------------------------------------------------------------------------------------------------		

	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	SELECT 
		cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID,
		m.FiscalMonthID, 
		SUM(cv.Value) AS OriginalValue
	INTO #tempUnpivoted
	FROM (
		SELECT BudgetConfigID, EntityID, stat.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID,
			ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonth, Value
		FROM #joinedStatData stat
			INNER JOIN #SourceDimensionality dept ON stat.DepartmentID = dept.DepartmentID
		CROSS APPLY (
			VALUES 
			('Month01', Month01),
			('Month02', Month02),
			('Month03', Month03),
			('Month04', Month04),
			('Month05', Month05),
			('Month06', Month06),
			('Month07', Month07),
			('Month08', Month08),
			('Month09', Month09),
			('Month10', Month10),
			('Month11', Month11),
			('Month12', Month12)) X (FiscalMonth, Value)
	) cv
		INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
	WHERE cv.Value = 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some.
	GROUP BY cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID, 
		m.FiscalMonthID

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		target.BudgetConfigID,
		target.EntityID,
		target.DepartmentID,
		target.AccountID,
		target.PatientClassID,
		target.PayorID,
		target.FinancialReportingID,
		target.UnitTypeID,
		target.TimeClassID, 
		target.FiscalMonthID,
		target.FiscalYearID,
		target.ProviderID,
		target.ProviderTypeID,
		target.ProviderSpecialtyID,
		target.ProviderLineItemID,
		SUM(target.OriginalValue) AS OriginalValue
	INTO #dataToUpdate
	FROM [fp].[FactReportStatistics] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID				= source.EntityID
						AND target.DepartmentID			= source.DepartmentID
						AND target.AccountID			= source.AccountID
						AND target.PatientClassID		= source.PatientClassID
						AND target.PayorID				= source.PayorID
						AND target.FinancialReportingID = source.FinancialReportingID
						AND target.UnitTypeID			= source.UnitTypeID
						AND target.TimeClassID			= source.TimeClassID
						AND target.FiscalMonthID		= source.FiscalMonthID
						AND target.FiscalYearID			= source.FiscalYearID
						AND target.ProviderID			= source.ProviderID
						AND target.ProviderTypeID		= source.ProviderTypeID
						AND target.ProviderSpecialtyID	= source.ProviderSpecialtyID
						AND target.ProviderLineItemID	= source.ProviderLineItemID
	WHERE source.BudgetConfigID = @BudgetConfigID
		AND target.OriginalValue != source.OriginalValue
	GROUP BY target.BudgetConfigID,
		target.EntityID,
		target.DepartmentID,
		target.AccountID,
		target.PatientClassID,
		target.PayorID,
		target.FinancialReportingID,
		target.UnitTypeID,
		target.TimeClassID, 
		target.FiscalMonthID,
		target.FiscalYearID,
		target.ProviderID,
		target.ProviderTypeID,
		target.ProviderSpecialtyID,
		target.ProviderLineItemID

	-- Update the records
	UPDATE source
	SET 
		source.OriginalValue = ISNULL(target.OriginalValue, 0)
	FROM [fp].[FactReportStatistics] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID				= source.EntityID
						AND target.DepartmentID			= source.DepartmentID
						AND target.AccountID			= source.AccountID
						AND target.PatientClassID		= source.PatientClassID
						AND target.PayorID				= source.PayorID
						AND target.FinancialReportingID = source.FinancialReportingID
						AND target.UnitTypeID			= source.UnitTypeID
						AND target.TimeClassID			= source.TimeClassID
						AND target.FiscalMonthID		= source.FiscalMonthID
						AND target.FiscalYearID			= source.FiscalYearID
						AND target.ProviderID			= source.ProviderID
						AND target.ProviderTypeID		= source.ProviderTypeID
						AND target.ProviderSpecialtyID	= source.ProviderSpecialtyID
						AND target.ProviderLineItemID	= source.ProviderLineItemID

END
GO


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

-- fp.procProcessReportFactStatistics_TargetBudget
CREATE   PROCEDURE [fp].[procProcessReportFactStatistics_TargetBudget] (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI		   Description
	** 1    2018-12-24   IP        B-21543	   Added temp table to index source as well
	** 2    2019-01-09   GF        B-21715	   Optimize full config refresh case
	** 3    2019-01-11   GF        B-21715	   Optimize targeted refresh case
	** 4    2019-05-02   GF        X-XXXXX     Remove special handling of all case to make concurrency work
	** 5    2019-07-22   MY        X-XXXXX	   Performance updates
	** 6    2020-01-13   MY        D-09168	   CCF: Data not flowing through into reports
	** 7    2020-02-18   MY        JAZZ-15375  Roll-up data above Provider for Report
	** 8    2021-05-10   MD        JAZZ-15686  Add Provider dimensions to Stats data sources 
	** 9    2021-11-10   BW        JAZZ-1358   Add dept to the filter when untargeted, to remove orphans 
	** 10   2022-08-30   MY        JAZZ-42472  Improve Pivoting of Data for Reports
	** 11   2024-07-16   YR        JAZZ-70315  Budget Config used for Report comparison is processed as well
	*************************************************************/
	
	EXEC [dbo].[procSysDropTempTable] '#SRC'
	EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality'
	EXEC [dbo].[procSysDropTempTable] '#departments'
	EXEC [dbo].[procSysDropTempTable] '#joinedStatData'
	EXEC [dbo].[procSysDropTempTable] '#tempUnpivoted'

	--only the active config is supported currently
	IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1)  AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END

	SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #SourceDimensionality (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.FactStatistics 
		WHERE BudgetConfigID = @BudgetConfigID
	END

	CREATE TABLE #SRC (
		BudgetConfigID INT,
		EntityID INT,
		DepartmentID INT,
		AccountID INT,
		PatientClassID INT,
		PayorID INT,
		FinancialReportingID INT,
		UnitTypeID SMALLINT,
		TimeClassID TINYINT,
		FiscalMonthID TINYINT,
		FiscalYearID SMALLINT,
		ProviderID INT,
		ProviderTypeID INT,
		ProviderSpecialtyID INT,
		ProviderLineItemID INT,
		Value DECIMAL(19, 8),
		ManagerValue DECIMAL(19, 8)
	)

	CREATE TABLE #joinedStatData (
		StatisticsID INT, 
		BudgetConfigID INT, 
		EntityID INT, 
		DepartmentID INT, 
		AccountID INT, 
		PatientClassID INT, 
		PayorID INT, 
		FinancialReportingID INT, 
		ProviderID INT, 
		ProviderTypeID INT, 
		ProviderSpecialtyID INT, 
		ProviderLineItemID INT, 
		UnitTypeID SMALLINT, 
		TimeClassID TINYINT,
		FiscalYearID SMALLINT, 
		BudgetPhaseID TINYINT,
		Month01 DECIMAL(19, 8), 
		Month02 DECIMAL(19, 8), 
		Month03 DECIMAL(19, 8), 
		Month04 DECIMAL(19, 8), 
		Month05 DECIMAL(19, 8), 
		Month06 DECIMAL(19, 8), 
		Month07 DECIMAL(19, 8), 
		Month08 DECIMAL(19, 8), 
		Month09 DECIMAL(19, 8), 
		Month10 DECIMAL(19, 8), 
		Month11 DECIMAL(19, 8), 
		Month12 DECIMAL(19, 8)
	)

	INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, 
		ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)
	SELECT
		fs.StatisticsID,
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.AccountID, 
		fs.PatientClassID, 
		fs.PayorID, 
		fs.FinancialReportingID, 
		fs.ProviderID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		fs.ProviderLineItemID,
		fs.UnitTypeID, 
		2 as TimeClassID,
		bc.FiscalYearID, 
		bdgt.BudgetPhaseID,
		bdgt.AdjustedValue01 AS Month01,
		bdgt.AdjustedValue02 AS Month02,
		bdgt.AdjustedValue03 AS Month03,
		bdgt.AdjustedValue04 AS Month04,
		bdgt.AdjustedValue05 AS Month05,
		bdgt.AdjustedValue06 AS Month06,
		bdgt.AdjustedValue07 AS Month07,
		bdgt.AdjustedValue08 AS Month08,
		bdgt.AdjustedValue09 AS Month09,
		bdgt.AdjustedValue10 AS Month10,
		bdgt.AdjustedValue11 AS Month11,
		bdgt.AdjustedValue12 AS Month12
	FROM fp.FactStatistics fs 
		INNER JOIN fp.FactStatisticsBudget bdgt ON fs.StatisticsID = bdgt.StatisticsID
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID

	INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, 
		ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, 
		Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)
	SELECT
		fs.StatisticsID,
		fs.BudgetConfigID, 
		fs.EntityID, 
		fs.DepartmentID, 
		fs.AccountID, 
		fs.PatientClassID, 
		fs.PayorID, 
		fs.FinancialReportingID, 
		fs.ProviderID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		fs.ProviderLineItemID,
		fs.UnitTypeID, 
		12 as TimeClassID,
		bc.FiscalYearID - 1, 
		bdgt.BudgetPhaseID,
		bdgt.AdjustedValue01 AS Month01,
		bdgt.AdjustedValue02 AS Month02,
		bdgt.AdjustedValue03 AS Month03,
		bdgt.AdjustedValue04 AS Month04,
		bdgt.AdjustedValue05 AS Month05,
		bdgt.AdjustedValue06 AS Month06,
		bdgt.AdjustedValue07 AS Month07,
		bdgt.AdjustedValue08 AS Month08,
		bdgt.AdjustedValue09 AS Month09,
		bdgt.AdjustedValue10 AS Month10,
		bdgt.AdjustedValue11 AS Month11,
		bdgt.AdjustedValue12 AS Month12
	FROM fp.FactStatistics fs 
		INNER JOIN fp.FactStatisticsProjection bdgt ON fs.StatisticsID = bdgt.StatisticsID
		INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID
	WHERE fs.BudgetConfigID = @BudgetConfigID
	   
	CREATE CLUSTERED INDEX inx_src ON #SRC (
		BudgetConfigID	
		,EntityID			
		,DepartmentID		
		,AccountID		
		,PatientClassID	
		,PayorID			
		,FinancialReportingID
		,UnitTypeID		
		,TimeClassID		
		,FiscalMonthID	
		,FiscalYearID	
		,ProviderID
		,ProviderTypeID
		,ProviderSpecialtyID
		,ProviderLineItemID
	) WITH (DATA_COMPRESSION = PAGE)
						
	-- Pivot the data into the #SRC Table
	INSERT INTO #SRC(BudgetConfigID, EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, 
			ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID,
			Value, ManagerValue)
	SELECT 
		cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID,
		m.FiscalMonthID, 
		SUM(CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END) AS Value, 
		SUM(CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END) AS ManagerValue
	FROM (
		SELECT BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID,
			ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, FiscalMonth, Value
		FROM #joinedStatData stat
		CROSS APPLY (
			VALUES 
			('Month01', Month01),
			('Month02', Month02),
			('Month03', Month03),
			('Month04', Month04),
			('Month05', Month05),
			('Month06', Month06),
			('Month07', Month07),
			('Month08', Month08),
			('Month09', Month09),
			('Month10', Month10),
			('Month11', Month11),
			('Month12', Month12)) X (FiscalMonth, Value)
	) cv
		INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
	WHERE 1 = 1
		AND (
			CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END != 0 OR 
			CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END != 0
		) -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some.
	GROUP BY cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID, 
		m.FiscalMonthID

	-- Get all of the departments in that could be affected. We need to get this list to eliminate
	-- the null check in the join in the with statement.
	SELECT DISTINCT DepartmentID INTO #departments 
	FROM (
		SELECT DISTINCT DepartmentID FROM #SRC
		UNION ALL
		SELECT DISTINCT DepartmentID FROM #SourceDimensionality
	) data						

	;WITH TGT AS 
	(
		SELECT BudgetConfigID, EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID,
					TimeClassID, FiscalMonthID, FiscalYearID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID,
					Value, ManagerValue 
		FROM fp.FactReportStatistics FRS
				INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID
		WHERE FRS.BudgetConfigID  = @BudgetConfigID
	)
			MERGE TGT AS target
			USING #SRC AS source
				ON (
							target.BudgetConfigID			= source.BudgetConfigID
						AND target.EntityID					= source.EntityID
						AND target.DepartmentID				= source.DepartmentID
						AND target.AccountID				= source.AccountID
						AND target.PatientClassID			= source.PatientClassID
						AND target.PayorID					= source.PayorID
						AND target.FinancialReportingID		= source.FinancialReportingID
						AND target.UnitTypeID				= source.UnitTypeID
						AND target.TimeClassID				= source.TimeClassID
						AND target.FiscalMonthID			= source.FiscalMonthID
						AND target.FiscalYearID				= source.FiscalYearID
						AND target.ProviderID				= source.ProviderID
						AND target.ProviderTypeID			= source.ProviderTypeID
						AND target.ProviderSpecialtyID		= source.ProviderSpecialtyID
						AND target.ProviderLineItemID		= source.ProviderLineItemID

						)
			WHEN MATCHED AND	(
					   target.Value <> source.Value
					OR target.ManagerValue <> source.ManagerValue)
				THEN
					UPDATE SET
						target.Value = ISNULL(source.Value, 0),
						target.ManagerValue = ISNULL(source.ManagerValue, 0)
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
							 BudgetConfigID
							,EntityID
							,DepartmentID
							,AccountID
							,PatientClassID
							,PayorID
							,FinancialReportingID
							,UnitTypeID
							,TimeClassID
							,FiscalMonthID
							,FiscalYearID
							,ProviderID
							,ProviderTypeID
							,ProviderSpecialtyID
							,ProviderLineItemID
							,Value
							,ManagerValue
						)
					VALUES (
						source. BudgetConfigID
						,source.EntityID
						,source.DepartmentID
						,source.AccountID
						,source.PatientClassID
						,source.PayorID
						,source.FinancialReportingID
						,source.UnitTypeID
						,source.TimeClassID
						,source.FiscalMonthID
						,source.FiscalYearID
						,source.ProviderID
						,source.ProviderTypeID
						,source.ProviderSpecialtyID
						,source.ProviderLineItemID
						,ISNULL(source.Value, 0)
						,ISNULL(source.ManagerValue, 0)
						);
	-- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted.
						
	-------------------------------------------------------------------------------------------------------
	-- Data not flowing through into reports after setting the record to 0
	-- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the 
	-- targeting above because we only populate records that are not 0
	-------------------------------------------------------------------------------------------------------
	
	-- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments
	-- We can't rely on the existing departments because of the check for the padded rows.
	IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
	
		TRUNCATE TABLE #departments;
	
		INSERT INTO #departments (DepartmentID)
		SELECT DepartmentID
		FROM [fw].[DimDepartment] dept
	
	END
	
	-- Get all records that were adjusted
	SELECT DISTINCT chg.StatisticsID
	INTO #adjustedRecords
	FROM [fp].[StatisticsChangeHistory] chg
		INNER JOIN [fp].[FactStatistics] fgl ON chg.BudgetConfigID = fgl.BudgetConfigID AND chg.StatisticsID = fgl.StatisticsID
		INNER JOIN #departments ft on ft.DepartmentID = fgl.DepartmentID
	WHERE chg.BudgetConfigID = @BudgetConfigID

	-- Get the records that have 0's in them that might have been filtered out from the previous logic
	SELECT 
		cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID,
		m.FiscalMonthID, 
		SUM(CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END) AS Value, 
		SUM(CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END) AS ManagerValue
	INTO #tempUnpivoted
	FROM (
		SELECT BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID,
			ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, FiscalMonth, Value
		FROM #joinedStatData stat
		CROSS APPLY (
			VALUES 
			('Month01', Month01),
			('Month02', Month02),
			('Month03', Month03),
			('Month04', Month04),
			('Month05', Month05),
			('Month06', Month06),
			('Month07', Month07),
			('Month08', Month08),
			('Month09', Month09),
			('Month10', Month10),
			('Month11', Month11),
			('Month12', Month12)) X (FiscalMonth, Value)
	) cv
		INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
	WHERE 1 = 1
		AND (
			CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END = 0 OR 
			CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END = 0
		)
	GROUP BY cv.BudgetConfigID, 
		cv.EntityID, 
		cv.DepartmentID, 
		cv.AccountID, 
		cv.PatientClassID, 
		cv.PayorID, 
		cv.FinancialReportingID, 
		cv.ProviderID,
		cv.ProviderTypeID,
		cv.ProviderSpecialtyID,
		cv.ProviderLineItemID,
		cv.UnitTypeID, 
		cv.TimeClassID, 
		cv.FiscalYearID, 
		m.FiscalMonthID

	-- Find the records that need to be updated by comparing the source to the reporting table
	SELECT 
		target.BudgetConfigID,
		target.EntityID,
		target.DepartmentID,
		target.AccountID,
		target.PatientClassID,
		target.PayorID,
		target.FinancialReportingID,
		target.UnitTypeID,
		target.TimeClassID, 
		target.FiscalMonthID,
		target.FiscalYearID,
		target.ProviderID,
		target.ProviderTypeID,
		target.ProviderSpecialtyID,
		target.ProviderLineItemID,
		SUM(target.Value) AS Value,
		SUM(target.ManagerValue) AS ManagerValue
	INTO #dataToUpdate
	FROM [fp].[FactReportStatistics] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID				= source.EntityID
						AND target.DepartmentID			= source.DepartmentID
						AND target.AccountID			= source.AccountID
						AND target.PatientClassID		= source.PatientClassID
						AND target.PayorID				= source.PayorID
						AND target.FinancialReportingID = source.FinancialReportingID
						AND target.UnitTypeID			= source.UnitTypeID
						AND target.TimeClassID			= source.TimeClassID
						AND target.FiscalMonthID		= source.FiscalMonthID
						AND target.FiscalYearID			= source.FiscalYearID
						AND target.ProviderID			= source.ProviderID
						AND target.ProviderTypeID		= source.ProviderTypeID
						AND target.ProviderSpecialtyID	= source.ProviderSpecialtyID
						AND target.ProviderLineItemID	= source.ProviderLineItemID
	WHERE source.BudgetConfigID = @BudgetConfigID
		AND (target.Value != source.Value OR target.ManagerValue != source.ManagerValue)
	GROUP BY target.BudgetConfigID,
		target.EntityID,
		target.DepartmentID,
		target.AccountID,
		target.PatientClassID,
		target.PayorID,
		target.FinancialReportingID,
		target.UnitTypeID,
		target.TimeClassID, 
		target.FiscalMonthID,
		target.FiscalYearID,
		target.ProviderID,
		target.ProviderTypeID,
		target.ProviderSpecialtyID,
		target.ProviderLineItemID

	-- Update the records
	UPDATE source
	SET 
		source.Value = 		   ISNULL(target.Value, 0),
		source.ManagerValue =  ISNULL(target.ManagerValue, 0)
	FROM [fp].[FactReportStatistics] source
		INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID
		INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID
						AND target.EntityID				= source.EntityID
						AND target.DepartmentID			= source.DepartmentID
						AND target.AccountID			= source.AccountID
						AND target.PatientClassID		= source.PatientClassID
						AND target.PayorID				= source.PayorID
						AND target.FinancialReportingID = source.FinancialReportingID
						AND target.UnitTypeID			= source.UnitTypeID
						AND target.TimeClassID			= source.TimeClassID
						AND target.FiscalMonthID		= source.FiscalMonthID
						AND target.FiscalYearID			= source.FiscalYearID
						AND target.ProviderID			= source.ProviderID
						AND target.ProviderTypeID		= source.ProviderTypeID
						AND target.ProviderSpecialtyID	= source.ProviderSpecialtyID
						AND target.ProviderLineItemID	= source.ProviderLineItemID
END
GO


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

-- fp.procProviderBudgetStampOff
CREATE   PROCEDURE [fp].[procProviderBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	01-31-2023  MY      JAZZ-48962		Initial Creation
	** 2	05-15-2023  BW      JAZZ-51541		Add provider compensation
	** 3	01-03-2024  MZ      JAZZ-65385		Added Target TimeClass
	** 4 	12-04-2023  BW/MZ   JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 5	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	
	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)
	
	-- Clear out existing records for the selected FiscalYear and Budgeted Time Class
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) FROM [int].[FactProvider] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		ph.PhysicianID,
		ph.PhysicianCode ,
		ProviderLineItemID,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		ut.UnitTypeID,
		ut.Name AS UnitTypeName,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, providerlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
		FROM (
			SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, cv.ProviderlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, 
				bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, 
				bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.FactStatistics cv
				INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID
				Inner JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID
			WHERE bdgt.BudgetPhaseID = 3
				AND cv.BudgetConfigID = @BudgetConfigID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
		INNER JOIN dss.DimPhysician ph ON ph.PhysicianID = BudgetedData.ProviderID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID

	-- Compensation
	INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT 
			d.DepartmentID,
			d.DepartmentCode,
			ph.PhysicianID,
			ph.PhysicianCode ,
			staff.ProviderLineItemID,
			@TargetTimeClassID AS TimeClassID,
			@TimeClassCode AS TimeClassCode,
			bc.FiscalYearID,
			bc.FiscalYearID AS FiscalYearCode,
			m.FiscalMonthID,
			m.FiscalMonthCode,
			ut.UnitTypeID,
			ut.Name AS UnitTypeName,
			Value AS Value,
			'0' AS IsDeleted,
			@HistoryItemGUID AS HistoryItemGUID
	FROM fp.Staffing staff (READUNCOMMITTED)
	INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID
		CROSS APPLY (
		VALUES
			( 1, 34, BudgetAdjustedDollars01), 
			( 2, 34, BudgetAdjustedDollars02),
			( 3, 34, BudgetAdjustedDollars03),
			( 4, 34, BudgetAdjustedDollars04), 
			( 5, 34, BudgetAdjustedDollars05), 
			( 6, 34, BudgetAdjustedDollars06),
			( 7, 34, BudgetAdjustedDollars07), 
			( 8, 34, BudgetAdjustedDollars08), 
			( 9, 34, BudgetAdjustedDollars09), 
			( 10, 34, BudgetAdjustedDollars10),
			( 11, 34, BudgetAdjustedDollars11), 
			( 12, 34, BudgetAdjustedDollars12)

	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID
			WHERE Value <> 0
			AND bc.BudgetConfigID = @BudgetConfigID
END
GO


---------------------------------------------

-- fp.procProviderCompensationApplySpread
CREATE   PROCEDURE [fp].[procProviderCompensationApplySpread]
  @BudgetConfigID int,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1	2021-04-13	OP		JAZZ-18025	Created
	** 2    2022-04-19  MZ		JAZZ-33812  Extended by UnitTypeID (cut with Hours and added condition on the update)
	** 3    2023-10-05  BK		JAZZ-60975  Update for new data structure
	** 4	2023-12-13	BW		JAZZ-62541	Update for new data structure - update to use the latest working hours view [fp].[viewWorkingHours]
	** 5	2023-02-21	MY		JAZZ-67948	Fix Issue where spreads to Dollars Impacts Hours
	** 6	2024-05-01	MY		JAZZ-66044	Added Change History to Spreads
	*************************************************************/ 

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #filterTable (StaffingID INT PRIMARY KEY CLUSTERED, AllowDollars bit, AllowHours bit, AllowFTEs bit);

	CREATE TABLE #spreadsChangeHistory (
		StaffingID INT,
		UnitTypeID SMALLINT NOT NULL DEFAULT(0),
		OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
	);

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
  
		INSERT INTO #filterTable (StaffingID, AllowDollars, AllowHours, AllowFTEs)
	SELECT DISTINCT basis.StaffingID, 
	CASE WHEN (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7)  THEN 1 ELSE 0 END as AllowDollars,
	CASE WHEN (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) THEN 1 ELSE 0 END as AllowHours,
	CASE WHEN (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) THEN 1 ELSE 0 END as AllowFTEs
	FROM [fp].[Staffing] basis
		INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID
		INNER JOIN [fp].[ProviderCompensationSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID 
			AND spread.DepartmentID = basis.DepartmentID 
			AND spread.JobCodeID = basis.JobCodeID 
			AND spread.PayCodeGroupID = basis.PayCodeGroupID
			AND spread.ProviderID = basis.ProviderID
			AND spread.ProviderLineItemID = basis.ProviderLineItemID
	WHERE basis.BudgetConfigID = @BudgetConfigID 
		AND basis.VariabilityID = 1 -- fixed
		AND spread.IsInactive = 0		
		AND (
		    (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments
		 OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments
		 OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments
		)
		AND basis.SubsectionID = 4 -- Provider Compensation
  
	END ELSE BEGIN
  
  		-- If the table source dimensionality is unfiltered, we don't wanna join on the department filter.
		INSERT INTO #filterTable (StaffingID, AllowDollars, AllowHours, AllowFTEs)
		SELECT DISTINCT basis.StaffingID, 
		CASE WHEN (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7)  THEN 1 ELSE 0 END as AllowDollars,
		CASE WHEN (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) THEN 1 ELSE 0 END as AllowHours,
		CASE WHEN (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) THEN 1 ELSE 0 END as AllowFTEs
		FROM [fp].[Staffing] basis
		  INNER JOIN [fp].[ProviderCompensationSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID 
			AND spread.DepartmentID = basis.DepartmentID 
			AND spread.JobCodeID = basis.JobCodeID 
			AND spread.PayCodeGroupID = basis.PayCodeGroupID
			AND spread.ProviderID = basis.ProviderID
			AND spread.ProviderLineItemID = basis.ProviderLineItemID
		WHERE basis.BudgetConfigID = @BudgetConfigID 
		  AND basis.VariabilityID = 1 -- fixed
		  AND spread.IsInactive = 0
		  AND (
				(basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments
			 OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments
			 OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments
			)
		  AND basis.SubsectionID = 4 -- Provider Compensation
  
	END
  
	  -- Update dollars
	  UPDATE dollars
	  SET   dollars.BudgetAdjustedDollars01 = CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01 AS DECIMAL(19,8))
			, dollars.BudgetAdjustedDollars02 = 
				CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars03 = 
				CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars04 = 
				CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars05 = 
				CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars06 = 
				CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars07 = 
				CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars08 = 
				CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars09 = 
				CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars10 = 
				CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars11 = 
				CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
			, dollars.BudgetAdjustedDollars12 = 
				CASE WHEN SpreadPercentage12 != 0
				THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
				ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
		, BudgetDollarsLockType = CASE WHEN dollars.BudgetDollarsLockType IN (1,4,5) THEN dollars.BudgetDollarsLockType ELSE 6 END
		, BudgetDollarsLockFlag = 1
	  OUTPUT 
	    inserted.StaffingID, 34, 
		deleted.BudgetAdjustedDollars01, deleted.BudgetAdjustedDollars02, deleted.BudgetAdjustedDollars03, deleted.BudgetAdjustedDollars04, deleted.BudgetAdjustedDollars05, deleted.BudgetAdjustedDollars06,
		deleted.BudgetAdjustedDollars07, deleted.BudgetAdjustedDollars08, deleted.BudgetAdjustedDollars09, deleted.BudgetAdjustedDollars10, deleted.BudgetAdjustedDollars11, deleted.BudgetAdjustedDollars12,
		inserted.BudgetAdjustedDollars01, inserted.BudgetAdjustedDollars02, inserted.BudgetAdjustedDollars03, inserted.BudgetAdjustedDollars04, inserted.BudgetAdjustedDollars05, inserted.BudgetAdjustedDollars06,
		inserted.BudgetAdjustedDollars07, inserted.BudgetAdjustedDollars08, inserted.BudgetAdjustedDollars09, inserted.BudgetAdjustedDollars10, inserted.BudgetAdjustedDollars11, inserted.BudgetAdjustedDollars12
	  INTO
	    #spreadsChangeHistory (StaffingID, UnitTypeID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) 
	  FROM [fp].[viewProviderCompensationSpreads] spread
		INNER JOIN [fp].[Staffing] dollars
			ON spread.BudgetConfigID = dollars.BudgetConfigID 
				AND spread.DepartmentID = dollars.DepartmentID 
				AND spread.JobCodeID = dollars.JobCodeID 
				AND spread.PayCodeGroupID = dollars.PayCodeGroupID			   
				AND spread.ProviderID = dollars.ProviderID
				AND spread.ProviderLineItemID = dollars.ProviderLineItemID
		  INNER JOIN #filterTable tmp on dollars.StaffingID = tmp.StaffingID
		WHERE spread.IsInactive = 0 
			AND tmp.AllowDollars = 1 
			AND spread.UnitTypeID = 34 -- dollars

	  -- Update hours		
	  UPDATE hours
	  SET   hours.BudgetAdjustedHours01 = CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage01 AS DECIMAL(19,8))
			, hours.BudgetAdjustedHours02 = 
				CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours03 = 
				CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours04 = 
				CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours05 = 
				CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours06 = 
				CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours07 = 
				CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours08 = 
				CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours09 = 
				CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours10 = 
				CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours11 = 
				CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
			, hours.BudgetAdjustedHours12 = 
				CASE WHEN SpreadPercentage12 != 0
				THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
				ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
		, BudgetHoursLockType = CASE WHEN hours.BudgetHoursLockType IN (1,4,5) THEN hours.BudgetHoursLockType ELSE 6 END
		, BudgetHoursLockFlag = 1
	  OUTPUT 
	    inserted.StaffingID, 51, 
		deleted.BudgetAdjustedHours01, deleted.BudgetAdjustedHours02, deleted.BudgetAdjustedHours03, deleted.BudgetAdjustedHours04, deleted.BudgetAdjustedHours05, deleted.BudgetAdjustedHours06,
		deleted.BudgetAdjustedHours07, deleted.BudgetAdjustedHours08, deleted.BudgetAdjustedHours09, deleted.BudgetAdjustedHours10, deleted.BudgetAdjustedHours11, deleted.BudgetAdjustedHours12,
		inserted.BudgetAdjustedHours01, inserted.BudgetAdjustedHours02, inserted.BudgetAdjustedHours03, inserted.BudgetAdjustedHours04, inserted.BudgetAdjustedHours05, inserted.BudgetAdjustedHours06,
		inserted.BudgetAdjustedHours07, inserted.BudgetAdjustedHours08, inserted.BudgetAdjustedHours09, inserted.BudgetAdjustedHours10, inserted.BudgetAdjustedHours11, inserted.BudgetAdjustedHours12
	  INTO
	    #spreadsChangeHistory (StaffingID, UnitTypeID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
	  FROM [fp].[viewProviderCompensationSpreads] spread
		INNER JOIN [fp].[Staffing] hours
			ON spread.BudgetConfigID = hours.BudgetConfigID 
				AND spread.DepartmentID = hours.DepartmentID 
				AND spread.JobCodeID = hours.JobCodeID 
				AND spread.PayCodeGroupID = hours.PayCodeGroupID			   
				AND spread.ProviderID = hours.ProviderID
				AND spread.ProviderLineItemID = hours.ProviderLineItemID
		  INNER JOIN #filterTable tmp on hours.StaffingID = tmp.StaffingID
		WHERE spread.IsInactive = 0 
			AND tmp.AllowHours = 1
			AND spread.UnitTypeID = 51 -- hours

	  -- Recalculate FTEs based on Hours
	  UPDATE ftes
	  SET
	    ftes.BudgetAdjustedFTEs01 = CASE WHEN hours.BudgetWorkingHours01 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours01 / hours.BudgetWorkingHours01 END,
	    ftes.BudgetAdjustedFTEs02 = CASE WHEN hours.BudgetWorkingHours02 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours02 / hours.BudgetWorkingHours02 END,
	    ftes.BudgetAdjustedFTEs03 = CASE WHEN hours.BudgetWorkingHours03 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours03 / hours.BudgetWorkingHours03 END,
	    ftes.BudgetAdjustedFTEs04 = CASE WHEN hours.BudgetWorkingHours04 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours04 / hours.BudgetWorkingHours04 END,
	    ftes.BudgetAdjustedFTEs05 = CASE WHEN hours.BudgetWorkingHours05 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours05 / hours.BudgetWorkingHours05 END,
	    ftes.BudgetAdjustedFTEs06 = CASE WHEN hours.BudgetWorkingHours06 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours06 / hours.BudgetWorkingHours06 END,
	    ftes.BudgetAdjustedFTEs07 = CASE WHEN hours.BudgetWorkingHours07 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours07 / hours.BudgetWorkingHours07 END,
	    ftes.BudgetAdjustedFTEs08 = CASE WHEN hours.BudgetWorkingHours08 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours08 / hours.BudgetWorkingHours08 END,
	    ftes.BudgetAdjustedFTEs09 = CASE WHEN hours.BudgetWorkingHours09 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours09 / hours.BudgetWorkingHours09 END,
	    ftes.BudgetAdjustedFTEs10 = CASE WHEN hours.BudgetWorkingHours10 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours10 / hours.BudgetWorkingHours10 END,
	    ftes.BudgetAdjustedFTEs11 = CASE WHEN hours.BudgetWorkingHours11 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours11 / hours.BudgetWorkingHours11 END,
	    ftes.BudgetAdjustedFTEs12 = CASE WHEN hours.BudgetWorkingHours12 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours12 / hours.BudgetWorkingHours12 END,
		ftes.BudgetFTEsLockType = CASE WHEN ftes.BudgetFTEsLockType IN (1,4,5) THEN ftes.BudgetFTEsLockType ELSE 6 END,
		ftes.BudgetFTEsLockFlag = 1
	OUTPUT 
	    inserted.StaffingID, 144, 
		deleted.BudgetAdjustedFTEs01, deleted.BudgetAdjustedFTEs02, deleted.BudgetAdjustedFTEs03, deleted.BudgetAdjustedFTEs04, deleted.BudgetAdjustedFTEs05, deleted.BudgetAdjustedFTEs06,
		deleted.BudgetAdjustedFTEs07, deleted.BudgetAdjustedFTEs08, deleted.BudgetAdjustedFTEs09, deleted.BudgetAdjustedFTEs10, deleted.BudgetAdjustedFTEs11, deleted.BudgetAdjustedFTEs12,
		inserted.BudgetAdjustedFTEs01, inserted.BudgetAdjustedFTEs02, inserted.BudgetAdjustedFTEs03, inserted.BudgetAdjustedFTEs04, inserted.BudgetAdjustedFTEs05, inserted.BudgetAdjustedFTEs06,
		inserted.BudgetAdjustedFTEs07, inserted.BudgetAdjustedFTEs08, inserted.BudgetAdjustedFTEs09, inserted.BudgetAdjustedFTEs10, inserted.BudgetAdjustedFTEs11, inserted.BudgetAdjustedFTEs12
	INTO
	    #spreadsChangeHistory (StaffingID, UnitTypeID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
	FROM [fp].[Staffing] ftes 
		INNER JOIN [fp].[viewProviderCompensationSpreads] spread 
			ON spread.BudgetConfigID = ftes.BudgetConfigID 
				AND spread.DepartmentID = ftes.DepartmentID 
				AND spread.JobCodeID = ftes.JobCodeID 
				AND spread.PayCodeGroupID = ftes.PayCodeGroupID			   
				AND spread.ProviderID = ftes.ProviderID
				AND spread.ProviderLineItemID = ftes.ProviderLineItemID
		INNER JOIN [fp].[viewWorkingHours] hours
	        ON ftes.DepartmentID = hours.DepartmentID
	          AND ftes.EntityID = hours.EntityID
	          AND ftes.JobCodeID = hours.JobCodeID
	          AND ftes.PayCodeGroupID = hours.PayCodeGroupID
	          AND ftes.ProductiveClassID = hours.ProductiveClassID
	          AND ftes.EntityGroupConfigID = hours.EntityGroupConfigID
	          AND ftes.EmployeeID = hours.EmployeeID
	          AND ftes.VariabilityID = hours.VariabilityID
	      INNER JOIN #filterTable f ON f.StaffingID = ftes.StaffingID -- should be limited to rows needing spread by this
	  WHERE ftes.VariabilityID = 1 
		  AND f.AllowFTEs = 1
		  AND spread.UnitTypeID = 51 -- Only Lock and Recalc FTEs for Hour based Spreads
	      AND ftes.ProductiveClassID NOT IN (4, 5, 6) -- Dollars-Only, Differential, Productive Non-FTE 
	      AND (
				ftes.BudgetAdjustedHours01 <> 0
			 OR ftes.BudgetAdjustedHours02 <> 0
			 OR ftes.BudgetAdjustedHours03 <> 0
			 OR ftes.BudgetAdjustedHours04 <> 0
			 OR ftes.BudgetAdjustedHours05 <> 0
			 OR ftes.BudgetAdjustedHours06 <> 0
			 OR ftes.BudgetAdjustedHours07 <> 0
			 OR ftes.BudgetAdjustedHours08 <> 0
			 OR ftes.BudgetAdjustedHours09 <> 0
			 OR ftes.BudgetAdjustedHours10 <> 0
			 OR ftes.BudgetAdjustedHours11 <> 0
			 OR ftes.BudgetAdjustedHours12 <> 0
		 )	

	-- Populate Change History
	IF EXISTS(SELECT 1 
			  FROM fp.viewBudgetConfigSetting
			  WHERE Name = 'Spreads Change History Logic Is Enabled'
			  	AND BudgetConfigID = @BudgetConfigID
				AND Value = 1)
	BEGIN

		INSERT INTO fp.StaffingSpreadsChangeHistory (StaffingID, BudgetConfigID, SubsectionID, UnitTypeID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
						OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,	NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
						NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
		SELECT StaffingID, @BudgetConfigID, 4 -- Provider
			, UnitTypeID,
			ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0),
			ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0),
			ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0),
			ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0)
		FROM #spreadsChangeHistory
		WHERE 1 = 1
			AND (
				   OldValue01 != NewValue01
				OR OldValue02 != NewValue02
				OR OldValue03 != NewValue03
				OR OldValue04 != NewValue04
				OR OldValue05 != NewValue05
				OR OldValue06 != NewValue06
				OR OldValue07 != NewValue07
				OR OldValue08 != NewValue08
				OR OldValue09 != NewValue09
				OR OldValue10 != NewValue10
				OR OldValue11 != NewValue11
				OR OldValue12 != NewValue12
			)

	END

END
GO


---------------------------------------------

-- fp.procProviderProjectionStampOff
CREATE     PROCEDURE [fp].[procProviderProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	11-10-2023 AO      JAZZ-62128		Initial Creation
	** 2	01-04-2024 MZ      JAZZ-65385		Added Target TimeClass and IsMonthsLoadedIncluded
	** 3	01-24-2024 MZ      JAZZ-64527		Fix Months Loaded
	** 4 	12-04-2023 BW/MZ   JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 5	03-18-2024 MZ      JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 6	04-03-2024 MZ      JAZZ-70053		Fix Month Loaded excluding logic
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Projected Time Class
	-- and all months if months loaded included otherwise only months NOT loaded will be cleared
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) prov FROM [int].[FactProvider] prov
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID
		WHERE prov.FiscalYearID = @FiscalYear
			AND prov.TimeClassID = @TargetTimeClassID
			AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded)
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		ph.PhysicianID,
		ph.PhysicianCode ,
		ProviderLineItemID,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		ut.UnitTypeID,
		ut.Name AS UnitTypeName,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, providerlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
		FROM (
			SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, cv.ProviderlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, 
				bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, 
				bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.FactStatistics cv
				INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID
				INNER JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID
			WHERE bdgt.BudgetPhaseID = 3
				AND cv.BudgetConfigID = @BudgetConfigID
		) cv
			UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
			LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
		INNER JOIN dss.DimPhysician ph ON ph.PhysicianID = BudgetedData.ProviderID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
		AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded)

	-- Compensation
	INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode],
		[FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) 
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		ph.PhysicianID,
		ph.PhysicianCode ,
		staff.ProviderLineItemID,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		m.FiscalMonthID,
		m.FiscalMonthCode,
		ut.UnitTypeID,
		ut.Name AS UnitTypeName,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM fp.Staffing staff (READUNCOMMITTED)
	INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID
		CROSS APPLY (
		VALUES
			( 1, 34, ProjectionAdjustedDollars01), 
			( 2, 34, ProjectionAdjustedDollars02),
			( 3, 34, ProjectionAdjustedDollars03),
			( 4, 34, ProjectionAdjustedDollars04), 
			( 5, 34, ProjectionAdjustedDollars05), 
			( 6, 34, ProjectionAdjustedDollars06),
			( 7, 34, ProjectionAdjustedDollars07), 
			( 8, 34, ProjectionAdjustedDollars08), 
			( 9, 34, ProjectionAdjustedDollars09), 
			( 10, 34, ProjectionAdjustedDollars10),
			( 11, 34, ProjectionAdjustedDollars11), 
			( 12, 34, ProjectionAdjustedDollars12)

	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID
	WHERE Value <> 0
			AND bc.BudgetConfigID = @BudgetConfigID
			AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded)

END
GO


---------------------------------------------

-- fp.procRebuildDatabaseStatistics
CREATE   PROC [fp].[procRebuildDatabaseStatistics]
	@IsDebug BIT = 0
AS
BEGIN
	SET NOCOUNT ON;

	IF OBJECT_ID('tempdb..#Debug') IS NOT NULL DROP TABLE #Debug
	CREATE TABLE #Debug (SqlToExecute NVARCHAR(1024))
	
	DECLARE @Schema NVARCHAR(2)
	DECLARE @FactTableName NVARCHAR(256)
	DECLARE @SQL nvarchar(1024)

	DECLARE FactTableCursor CURSOR FOR 
	SELECT TableName, SchemaName
	FROM fp.RefreshDatabaseStatisticsConfiguration
	WHERE IsActive = 1
	
	OPEN FactTableCursor
	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @Schema
	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @SQL = 'UPDATE STATISTICS ' + @Schema + '.' + @FactTableName + ' WITH FULLSCAN'
		
		IF @IsDebug = 1 BEGIN
			INSERT INTO #Debug (SqlToExecute) VALUES (@SQL)
		END ELSE BEGIN
			EXECUTE sp_executesql @SQL 
		END
		
		FETCH NEXT FROM FactTableCursor INTO @FactTableName, @Schema
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	IF @IsDebug = 1 BEGIN
		SELECT * FROM #Debug
	END
END
GO


---------------------------------------------

-- fp.procRebuildIndexesTargeted
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	05-16-2023  MY      JAZZ-54812		Fix issue with renamed tables
** 2	12-13-2023  MY      JAZZ-64522		Filtered out anything with OLD in the name as these are likely backup restructure tables
** 3	08-29-2024  MY      JAZZ-74223		Remove FULLSCAN
** 4	11-06-2024  NH      JAZZ-79530		Added square brackets to avoid conflicts
*************************************************************/
CREATE   PROC [fp].[procRebuildIndexesTargeted]
	@isEncounter BIT,
	@isChargeVolume BIT,
	@isStats BIT,
	@isStaffing BIT,
	@isBenefits BIT,
	@isGeneralLedger BIT,
	@isDebug BIT
AS
	SET NOCOUNT ON;

	DECLARE @SchemaID INT;
	SELECT @SchemaID = schema_id from sys.schemas where name = 'fp'
	DECLARE @SCHEMA NVARCHAR(2)
	DECLARE @FactTableName NVARCHAR(256)
	DECLARE @SQL nvarchar(1024)
		
	IF OBJECT_ID('tempdb..#Debug') IS NOT NULL DROP TABLE #Debug
	CREATE TABLE #Debug (SqlToExecute NVARCHAR(1024))
	DECLARE FactTableCursor CURSOR FOR 
	SELECT t.name, 'fp' from sys.tables t 
	WHERE 
		t.schema_id = @SchemaID
		AND t.name NOT LIKE '%Archive%'
		AND t.name NOT LIKE 'Temp%'
		AND t.name NOT LIKE '%old%'
		AND ( (@isEncounter = 1 AND t.name like '%Encounter%')
		OR  (@isChargeVolume = 1 AND (t.name like '%ChargeVolume%'))
		OR  (@isStats = 1 AND t.name like '%Statistics%')
		OR  (@isStaffing = 1 AND t.name like '%Staffing%')
		OR  (@isBenefits = 1 AND t.name like '%Benefit%')
		OR  (@isGeneralLedger = 1 AND t.name like '%General%'))
		
	ORDER BY t.name
	
	OPEN FactTableCursor

	FETCH NEXT FROM FactTableCursor 
	INTO @FactTableName, @SCHEMA
	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @SQL = 'update statistics [' + @SCHEMA + '].[' + @FactTableName + ']'
		
		IF @isDebug = 1 BEGIN
			INSERT INTO #Debug (SqlToExecute) VALUES (@SQL)
		END ELSE BEGIN
			EXECUTE sp_executesql @SQL 
		END
		
		FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA
	END

	CLOSE FactTableCursor
	DEALLOCATE FactTableCursor
	
	IF @isDebug = 1 BEGIN
		SELECT * FROM #Debug
	END
GO


---------------------------------------------

-- fp.procRecalcBenefitsTotals
CREATE PROCEDURE [fp].[procRecalcBenefitsTotals]
 	@EntityGroupConfigID INT,
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@TimeClassID INT,
	@SourceDimensionality [fp].BudgetRefreshSourceDimensionality READONLY
 AS
 BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   	   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	   Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2   2022-02-23  NT		 JAZZ-33434  Clean up by removing IS NULL JOIN and SELECT *
	 ** 3   2022-07-12  NT      JAZZ-39267  Add OPTION RECOMPILE to improve performance
	 ** 3   2022-09-07  BK      JAZZ-42570  Add hash to inner join per Oleg recommendation
	 *************************************************************/  

	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits

	CREATE TABLE #FilterByDepartment (DepartmentID int, BudgetPhaseID int)
	INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID)
	SELECT DepartmentID, BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment does not have valid data then pass all departments to avoid duplicate statements
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN 
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[FactBenefits] fb
		WHERE fb.EntityGroupConfigID = @EntityGroupConfigID
	END
 
 	DECLARE @Dollars INT = 34,
			@Ftes INT = 144,
			@DollarsPerFte INT = 171,
			@Salaries INT = 169,
			@PercentOfSalaries INT = 170
			
	DECLARE @MonthsLoaded INT	
	SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = @EntityGroupConfigID

	-- We need to return the benefits items that were adjusted to fix the change history
	CREATE TABLE #budget_basisIDs (BenefitsID INT);
	CREATE TABLE #projection_basisIDs (BenefitsID INT);
			
	CREATE TABLE #FactBenefits (BudgetConfigID INT, EntityID INT, DepartmentID INT, AccountID INT, UnitTypeID INT, FinancialReportingID INT, BudgetPhaseID INT,
						  Value01 DECIMAL(19,8), Value02 DECIMAL(19,8), Value03 DECIMAL(19,8), Value04 DECIMAL(19,8), Value05 DECIMAL(19,8),
						  Value06 DECIMAL(19,8), Value07 DECIMAL(19,8), Value08 DECIMAL(19,8), Value09 DECIMAL(19,8), Value10 DECIMAL(19,8),
						  Value11 DECIMAL(19,8), Value12 DECIMAL(19,8))
 
 	IF (@TimeClassID = 2)
	BEGIN
				
		-- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES
        INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, 
								   Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12)
        SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
			vol.BudgetPhaseID,
			vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01,
			vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02,
			vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03,
			vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04,
			vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05,
			vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06,
			vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07,
			vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08,
			vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09,
			vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10,
			vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11,
			vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12			
        FROM
            (
				 SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, budg.BudgetPhaseID, 
				 		 budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, 
				 		 budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12
				 FROM [fp].[FactBenefits] ben
				 INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID 
				 INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				 WHERE UnitTypeID = @Salaries 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
		    		AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value
			 
            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
 						budg.BudgetPhaseID, budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, 
		 		 	   budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12 
				FROM [fp].[FactBenefits] ben
				INNER JOIN #FilterByDepartment ft On ft.DepartmentID = ben.DepartmentID
				INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID 
				WHERE UnitTypeID = @PercentOfSalaries 
					AND EntityGroupConfigID = @EntityGroupConfigID
		    		AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
					AND rate.BudgetPhaseID = vol.BudgetPhaseID
        WHERE
        	  vol.FlexMethodID = 2 -- FlexAccountBySalaries
		OPTION (RECOMPILE)
								

        -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES		
		INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, 
								   Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12)
		SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
			vol.BudgetPhaseID,
			vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01,
			vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02,
			vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03,
			vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04,
			vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05,
			vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06,
			vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07,
			vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08,
			vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09,
			vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10,
			vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11,
			vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12			
        FROM
            (
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
						budg.BudgetPhaseID, budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, 
				 		budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12 
				FROM [fp].[FactBenefits] ben
				INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID		
			    INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @Ftes 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
				 	AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value

            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, 
				       budg.BudgetPhaseID, budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, 
				 	    budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12
				FROM [fp].[FactBenefits] ben
				 	INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID 
				 	INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @DollarsPerFte 
					AND EntityGroupConfigID = @EntityGroupConfigID
				 	AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
					AND rate.BudgetPhaseID = vol.BudgetPhaseID
        WHERE
        	  vol.FlexMethodID = 1 -- FlexAccountByFTEs
		OPTION (RECOMPILE)
									
		UPDATE
			budg
		SET
			budg.AdjustedValue01 = Value01,
			budg.AdjustedValue02 = Value02,
			budg.AdjustedValue03 = Value03,
			budg.AdjustedValue04 = Value04,
			budg.AdjustedValue05 = Value05,
			budg.AdjustedValue06 = Value06,
			budg.AdjustedValue07 = Value07,
			budg.AdjustedValue08 = Value08,
			budg.AdjustedValue09 = Value09,
			budg.AdjustedValue10 = Value10,
			budg.AdjustedValue11 = Value11,
			budg.AdjustedValue12 = Value12,
			budg.FlexedValue01 = Value01,
			budg.FlexedValue02 = Value02,
			budg.FlexedValue03 = Value03,
			budg.FlexedValue04 = Value04,
			budg.FlexedValue05 = Value05,
			budg.FlexedValue06 = Value06,
			budg.FlexedValue07 = Value07,
			budg.FlexedValue08 = Value08,
			budg.FlexedValue09 = Value09,
			budg.FlexedValue10 = Value10,
			budg.FlexedValue11 = Value11,
			budg.FlexedValue12 = Value12
			OUTPUT 
				INSERTED.BenefitsID
			INTO
				#budget_basisIDs (BenefitsID)
		FROM
			[fp].[FactBenefits] ben
		INNER JOIN [fp].[FactBenefitsBudget] budg ON
			ben.BenefitsID = budg.BenefitsID
		INNER JOIN #FactBenefits tmp ON 
							ben.budgetConfigID = tmp.budgetConfigID
			AND ben.EntityID = tmp.EntityID
			AND ben.DepartmentID = tmp.DepartmentID
			AND ben.AccountID = tmp.AccountID
			AND ben.UnitTypeID = tmp.UnitTypeID
			AND ben.FinancialReportingID = tmp.FinancialReportingID
			AND budg.BudgetPhaseID = tmp.BudgetPhaseID
		WHERE ben.EntityGroupConfigID = @EntityGroupConfigID	
		  AND (
				budg.AdjustedValue01 <> Value01 OR
				budg.AdjustedValue02 <> Value02 OR
				budg.AdjustedValue03 <> Value03 OR
				budg.AdjustedValue04 <> Value04 OR
				budg.AdjustedValue05 <> Value05 OR
				budg.AdjustedValue06 <> Value06 OR
				budg.AdjustedValue07 <> Value07 OR
				budg.AdjustedValue08 <> Value08 OR
				budg.AdjustedValue09 <> Value09 OR
				budg.AdjustedValue10 <> Value10 OR
				budg.AdjustedValue11 <> Value11 OR
				budg.AdjustedValue12 <> Value12 OR
				budg.FlexedValue01 <> Value01 OR
				budg.FlexedValue02 <> Value02 OR
				budg.FlexedValue03 <> Value03 OR
				budg.FlexedValue04 <> Value04 OR
				budg.FlexedValue05 <> Value05 OR
				budg.FlexedValue06 <> Value06 OR
				budg.FlexedValue07 <> Value07 OR
				budg.FlexedValue08 <> Value08 OR
				budg.FlexedValue09 <> Value09 OR
				budg.FlexedValue10 <> Value10 OR
				budg.FlexedValue11 <> Value11 OR
				budg.FlexedValue12 <> Value12
		  )

	
	END ELSE BEGIN
	
		------------------------------------------------------------
		-- Projection
		------------------------------------------------------------
		
		-- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES
        INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, 
								   Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12)
        SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
            vol.BudgetPhaseID,
			vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01,
			vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02,
			vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03,
			vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04,
			vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05,
			vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06,
			vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07,
			vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08,
			vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09,
			vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10,
			vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11,
			vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12			
        FROM
            (
				 SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				        proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, 
				 		 proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12
				 FROM [fp].[FactBenefits] ben
				 INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				 INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID 
				 WHERE UnitTypeID = @Salaries 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
				 	AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value
			
            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				       proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, 
				 	    proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12
				FROM [fp].[FactBenefits] ben
				INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID  
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @PercentOfSalaries 
					AND EntityGroupConfigID = @EntityGroupConfigID
				 	AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
					AND rate.BudgetPhaseID = vol.BudgetPhaseID
        WHERE
			  vol.FlexMethodID = 2 -- FlexAccountBySalaries
		OPTION (RECOMPILE)						

        -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES		
		INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, 
								   Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12)
		SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
			vol.BudgetPhaseID,
			vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01,
			vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02,
			vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03,
			vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04,
			vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05,
			vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06,
			vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07,
			vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08,
			vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09,
			vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10,
			vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11,
			vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12			
        FROM
            (
				 SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		 proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, 
				 		 proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12
				 FROM [fp].[FactBenefits] ben
				 	INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID   
					INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				 WHERE UnitTypeID = @Ftes 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
				 	AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value

            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
    				    proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, 
				 		 proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12
				FROM [fp].[FactBenefits] ben
				INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID   
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @DollarsPerFte 
					AND EntityGroupConfigID = @EntityGroupConfigID
				 	AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
					AND rate.BudgetPhaseID = vol.BudgetPhaseID
        WHERE
            vol.FlexMethodID = 1 -- FlexAccountByFTEs
		OPTION (RECOMPILE)
		
		UPDATE proj
		SET
			proj.AdjustedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END,
			proj.AdjustedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END,
			proj.AdjustedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END,
			proj.AdjustedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END,
			proj.AdjustedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END,
			proj.AdjustedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END,
			proj.AdjustedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END,
			proj.AdjustedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END,
			proj.AdjustedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END,
			proj.AdjustedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END,
			proj.AdjustedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END,
			proj.AdjustedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END,
			proj.FlexedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END,
			proj.FlexedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END,
			proj.FlexedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END,
			proj.FlexedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END,
			proj.FlexedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END,
			proj.FlexedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END,
			proj.FlexedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END,
			proj.FlexedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END,
			proj.FlexedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END,
			proj.FlexedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END,
			proj.FlexedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END,
			proj.FlexedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END
		OUTPUT 
	        INSERTED.BenefitsID
	    INTO
	        #projection_basisIDs (BenefitsID) 		
		FROM [fp].[FactBenefits] ben
			INNER JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID
			INNER JOIN #FactBenefits tmp ON 
					ben.BudgetConfigID = tmp.BudgetConfigID
				AND ben.EntityID = tmp.EntityID
				AND ben.DepartmentID = tmp.DepartmentID
				AND ben.AccountID = tmp.AccountID
				AND ben.UnitTypeID = tmp.UnitTypeID
				AND ben.FinancialReportingID = tmp.FinancialReportingID
				AND proj.BudgetPhaseID = tmp.BudgetPhaseID
		WHERE ben.EntityGroupConfigID = @EntityGroupConfigID
		  AND (
				(proj.AdjustedValue01 <> CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END) OR
				(proj.AdjustedValue02 <> CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END) OR
				(proj.AdjustedValue03 <> CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END) OR
				(proj.AdjustedValue04 <> CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END) OR
				(proj.AdjustedValue05 <> CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END) OR
				(proj.AdjustedValue06 <> CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END) OR
				(proj.AdjustedValue07 <> CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END) OR
				(proj.AdjustedValue08 <> CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END) OR
				(proj.AdjustedValue09 <> CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END) OR
				(proj.AdjustedValue10 <> CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END) OR
				(proj.AdjustedValue11 <> CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END) OR
				(proj.AdjustedValue12 <> CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END) OR
				(proj.FlexedValue01 <> CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END) OR
				(proj.FlexedValue02 <> CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END) OR
				(proj.FlexedValue03 <> CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END) OR
				(proj.FlexedValue04 <> CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END) OR
				(proj.FlexedValue05 <> CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END) OR
				(proj.FlexedValue06 <> CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END) OR
				(proj.FlexedValue07 <> CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END) OR
				(proj.FlexedValue08 <> CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END) OR
				(proj.FlexedValue09 <> CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END) OR
				(proj.FlexedValue10 <> CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END) OR
				(proj.FlexedValue11 <> CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END) OR
				(proj.FlexedValue12 <> CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END)
			)	
		
	END
	
	-- returns the info on the rows that were flexed in order to fix the change history
	SELECT DISTINCT BenefitsID
		,m.FiscalMonthID
		,BudgetPhaseID
		,TimeClassID
		,f.Value
	FROM (
		SELECT bdgt.BenefitsID
			,bdgt.AdjustedValue01
			,bdgt.AdjustedValue02
			,bdgt.AdjustedValue03
			,bdgt.AdjustedValue04
			,bdgt.AdjustedValue05
			,bdgt.AdjustedValue06
			,bdgt.AdjustedValue07
			,bdgt.AdjustedValue08
			,bdgt.AdjustedValue09
			,bdgt.AdjustedValue10
			,bdgt.AdjustedValue11
			,bdgt.AdjustedValue12
			,bdgt.BudgetPhaseID
			,cast(2 AS TINYINT) AS TimeClassID
		FROM #budget_basisIDs ids
		INNER JOIN [fp].[FactBenefitsBudget] bdgt
			ON ids.BenefitsID = bdgt.BenefitsID
		WHERE bdgt.BudgetPhaseID = 2
		UNION ALL
		SELECT
			 bdgt.BenefitsID
			,bdgt.AdjustedValue01
			,bdgt.AdjustedValue02
			,bdgt.AdjustedValue03
			,bdgt.AdjustedValue04
			,bdgt.AdjustedValue05
			,bdgt.AdjustedValue06
			,bdgt.AdjustedValue07
			,bdgt.AdjustedValue08
			,bdgt.AdjustedValue09
			,bdgt.AdjustedValue10
			,bdgt.AdjustedValue11
			,bdgt.AdjustedValue12
			,bdgt.BudgetPhaseID
			,cast(12 AS TINYINT) AS TimeClassID
		FROM #projection_basisIDs ids
		INNER JOIN [fp].[FactBenefitsProjection] bdgt
			ON ids.BenefitsID = bdgt.BenefitsID
		WHERE bdgt.BudgetPhaseID = 2
		) gl
	UNPIVOT(Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) AS f
	LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits

END;
GO


---------------------------------------------

-- fp.procRecalcBenefitsTotals_InitialValue
CREATE PROCEDURE [fp].[procRecalcBenefitsTotals_InitialValue]
 	@EntityGroupConfigID INT,
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@TimeClassID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
  	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2   2022-02-23  NT		 JAZZ-33434 Clean up by removing IS NULL JOIN and SELECT *
	 *************************************************************/
	 
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment does not contain valid data then pass all departments to avoid duplicate statements
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN 
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[FactBenefits] fb
		WHERE fb.EntityGroupConfigID = @EntityGroupConfigID
	END
 
 	DECLARE @Dollars INT = 34,
			@Ftes INT = 144,
			@DollarsPerFte INT = 171,
			@Salaries INT = 169,
			@PercentOfSalaries INT = 170
			
	DECLARE @MonthsLoaded INT	
	SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = @EntityGroupConfigID			
			
	CREATE TABLE #FactBenefits (BudgetConfigID INT, EntityID INT, DepartmentID INT, AccountID INT, UnitTypeID INT, FinancialReportingID INT,
						  OriginalValue01 DECIMAL(19,8), OriginalValue02 DECIMAL(19,8), OriginalValue03 DECIMAL(19,8), OriginalValue04 DECIMAL(19,8), OriginalValue05 DECIMAL(19,8),
						  OriginalValue06 DECIMAL(19,8), OriginalValue07 DECIMAL(19,8), OriginalValue08 DECIMAL(19,8), OriginalValue09 DECIMAL(19,8), OriginalValue10 DECIMAL(19,8),
						  OriginalValue11 DECIMAL(19,8), OriginalValue12 DECIMAL(19,8))
 
 	IF (@TimeClassID = 2)
	BEGIN
				
		-- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES
        INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04,
								   OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12)
        SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
			vol.InitialBudget01 * rate.InitialBudget01 AS OriginalValue01,
			vol.InitialBudget02 * rate.InitialBudget02 AS OriginalValue02,
			vol.InitialBudget03 * rate.InitialBudget03 AS OriginalValue03,
			vol.InitialBudget04 * rate.InitialBudget04 AS OriginalValue04,
			vol.InitialBudget05 * rate.InitialBudget05 AS OriginalValue05,
			vol.InitialBudget06 * rate.InitialBudget06 AS OriginalValue06,
			vol.InitialBudget07 * rate.InitialBudget07 AS OriginalValue07,
			vol.InitialBudget08 * rate.InitialBudget08 AS OriginalValue08,
			vol.InitialBudget09 * rate.InitialBudget09 AS OriginalValue09,
			vol.InitialBudget10 * rate.InitialBudget10 AS OriginalValue10,
			vol.InitialBudget11 * rate.InitialBudget11 AS OriginalValue11,
			vol.InitialBudget12 * rate.InitialBudget12 AS OriginalValue12		
        FROM
            (
				 SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06,
						ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12
				 FROM [fp].[FactBenefits] ben
				 INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				 WHERE UnitTypeID = @Salaries 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value
			 
			
            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06,
						ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12
				FROM [fp].[FactBenefits] ben
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @PercentOfSalaries 
					AND EntityGroupConfigID = @EntityGroupConfigID
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
        WHERE
        	  vol.FlexMethodID = 2 -- FlexAccountBySalaries
								

        -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES		
		INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04,
								   OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12)
		SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
			vol.InitialBudget01 * rate.InitialBudget01 AS OriginalValue01,
			vol.InitialBudget02 * rate.InitialBudget02 AS OriginalValue02,
			vol.InitialBudget03 * rate.InitialBudget03 AS OriginalValue03,
			vol.InitialBudget04 * rate.InitialBudget04 AS OriginalValue04,
			vol.InitialBudget05 * rate.InitialBudget05 AS OriginalValue05,
			vol.InitialBudget06 * rate.InitialBudget06 AS OriginalValue06,
			vol.InitialBudget07 * rate.InitialBudget07 AS OriginalValue07,
			vol.InitialBudget08 * rate.InitialBudget08 AS OriginalValue08,
			vol.InitialBudget09 * rate.InitialBudget09 AS OriginalValue09,
			vol.InitialBudget10 * rate.InitialBudget10 AS OriginalValue10,
			vol.InitialBudget11 * rate.InitialBudget11 AS OriginalValue11,
			vol.InitialBudget12 * rate.InitialBudget12 AS OriginalValue12	
        FROM
            (
				 SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06,
						ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12
				 FROM [fp].[FactBenefits] ben
				 INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				 WHERE UnitTypeID = @Ftes 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value

            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06,
						ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12
				FROM [fp].[FactBenefits] ben
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @DollarsPerFte 
					AND EntityGroupConfigID = @EntityGroupConfigID
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
        WHERE
        	  vol.FlexMethodID = 1 -- FlexAccountByFTEs
								
		UPDATE ben
		SET
			ben.InitialBudget01 = OriginalValue01,
			ben.InitialBudget02 = OriginalValue02,
			ben.InitialBudget03 = OriginalValue03,
			ben.InitialBudget04 = OriginalValue04,
			ben.InitialBudget05 = OriginalValue05,
			ben.InitialBudget06 = OriginalValue06,
			ben.InitialBudget07 = OriginalValue07,
			ben.InitialBudget08 = OriginalValue08,
			ben.InitialBudget09 = OriginalValue09,
			ben.InitialBudget10 = OriginalValue10,
			ben.InitialBudget11 = OriginalValue11,
			ben.InitialBudget12 = OriginalValue12
		FROM [fp].[FactBenefits] ben
			INNER JOIN #FactBenefits tmp ON 
					ben.BudgetConfigID = tmp.BudgetConfigID
				AND ben.EntityID = tmp.EntityID
				AND ben.DepartmentID = tmp.DepartmentID
				AND ben.AccountID = tmp.AccountID
				AND ben.UnitTypeID = tmp.UnitTypeID
				AND ben.FinancialReportingID = tmp.FinancialReportingID
		WHERE ben.EntityGroupConfigID = @EntityGroupConfigID
		  AND ( 
				ben.InitialBudget01 <> OriginalValue01 OR
			    ben.InitialBudget02 <> OriginalValue02 OR
			    ben.InitialBudget03 <> OriginalValue03 OR
				ben.InitialBudget04 <> OriginalValue04 OR
				ben.InitialBudget05 <> OriginalValue05 OR
				ben.InitialBudget06 <> OriginalValue06 OR
				ben.InitialBudget07 <> OriginalValue07 OR
				ben.InitialBudget08 <> OriginalValue08 OR
				ben.InitialBudget09 <> OriginalValue09 OR
				ben.InitialBudget10 <> OriginalValue10 OR
				ben.InitialBudget11 <> OriginalValue11 OR
				ben.InitialBudget12 <> OriginalValue12
		  )
	
	END ELSE BEGIN
	
		------------------------------------------------------------
		-- Projection
		------------------------------------------------------------
		
		-- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES
        INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04,
								   OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12)
        SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
			vol.InitialProjection01 * rate.InitialProjection01 AS OriginalValue01,
			vol.InitialProjection02 * rate.InitialProjection02 AS OriginalValue02,
			vol.InitialProjection03 * rate.InitialProjection03 AS OriginalValue03,
			vol.InitialProjection04 * rate.InitialProjection04 AS OriginalValue04,
			vol.InitialProjection05 * rate.InitialProjection05 AS OriginalValue05,
			vol.InitialProjection06 * rate.InitialProjection06 AS OriginalValue06,
			vol.InitialProjection07 * rate.InitialProjection07 AS OriginalValue07,
			vol.InitialProjection08 * rate.InitialProjection08 AS OriginalValue08,
			vol.InitialProjection09 * rate.InitialProjection09 AS OriginalValue09,
			vol.InitialProjection10 * rate.InitialProjection10 AS OriginalValue10,
			vol.InitialProjection11 * rate.InitialProjection11 AS OriginalValue11,
			vol.InitialProjection12 * rate.InitialProjection12 AS OriginalValue12	
        FROM
            (
				 SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06,
						ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12
				 FROM [fp].[FactBenefits] ben
				 INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				 WHERE UnitTypeID = @Salaries 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value

            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06,
						ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12
				FROM [fp].[FactBenefits] ben
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @PercentOfSalaries 
					AND EntityGroupConfigID = @EntityGroupConfigID
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
        WHERE
			  vol.FlexMethodID = 2 -- FlexAccountBySalaries
								

        -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES		
		INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04,
								   OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12)
		SELECT
            vol.BudgetConfigID,
            vol.EntityID,
            vol.DepartmentID,
            vol.AccountID,
            @Dollars as UnitTypeID,
            vol.FinancialReportingID,			
			vol.InitialProjection01 * rate.InitialProjection01 AS OriginalValue01,
			vol.InitialProjection02 * rate.InitialProjection02 AS OriginalValue02,
			vol.InitialProjection03 * rate.InitialProjection03 AS OriginalValue03,
			vol.InitialProjection04 * rate.InitialProjection04 AS OriginalValue04,
			vol.InitialProjection05 * rate.InitialProjection05 AS OriginalValue05,
			vol.InitialProjection06 * rate.InitialProjection06 AS OriginalValue06,
			vol.InitialProjection07 * rate.InitialProjection07 AS OriginalValue07,
			vol.InitialProjection08 * rate.InitialProjection08 AS OriginalValue08,
			vol.InitialProjection09 * rate.InitialProjection09 AS OriginalValue09,
			vol.InitialProjection10 * rate.InitialProjection10 AS OriginalValue10,
			vol.InitialProjection11 * rate.InitialProjection11 AS OriginalValue11,
			vol.InitialProjection12 * rate.InitialProjection12 AS OriginalValue12	
        FROM
            (
				 SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06,
						ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12
				 FROM [fp].[FactBenefits] ben
				 INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				 WHERE UnitTypeID = @Ftes 
				 	AND EntityGroupConfigID = @EntityGroupConfigID
			 ) vol  -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value

            INNER JOIN 
			(	
				SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID,
				 		ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06,
						ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12
				FROM [fp].[FactBenefits] ben
				INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID
				WHERE UnitTypeID = @DollarsPerFte 
					AND EntityGroupConfigID = @EntityGroupConfigID
			) rate 
				ON rate.EntityGroupConfigID = vol.EntityGroupConfigID 
					AND rate.EntityID = vol.EntityID 
					AND rate.DepartmentID = vol.DepartmentID 
					AND rate.AccountID = vol.AccountID 
					AND rate.FinancialReportingID = vol.FinancialReportingID
        WHERE
            vol.FlexMethodID = 1 -- FlexAccountByFTEs
								
		UPDATE ben
		SET
			ben.InitialProjection01 = CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE OriginalValue01 END,
			ben.InitialProjection02 = CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE OriginalValue02 END,
			ben.InitialProjection03 = CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE OriginalValue03 END,
			ben.InitialProjection04 = CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE OriginalValue04 END,
			ben.InitialProjection05 = CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE OriginalValue05 END,
			ben.InitialProjection06 = CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE OriginalValue06 END,
			ben.InitialProjection07 = CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE OriginalValue07 END,
			ben.InitialProjection08 = CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE OriginalValue08 END,
			ben.InitialProjection09 = CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE OriginalValue09 END,
			ben.InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE OriginalValue10 END,
			ben.InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE OriginalValue11 END,
			ben.InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE OriginalValue12 END
		FROM [fp].[FactBenefits] ben
			INNER JOIN #FactBenefits tmp ON 
					ben.BudgetConfigID = tmp.BudgetConfigID
				AND ben.EntityID = tmp.EntityID
				AND ben.DepartmentID = tmp.DepartmentID
				AND ben.AccountID = tmp.AccountID
				AND ben.UnitTypeID = tmp.UnitTypeID
				AND ben.FinancialReportingID = tmp.FinancialReportingID
		WHERE ben.EntityGroupConfigID = @EntityGroupConfigID				
		  AND (
			ben.InitialProjection01 <> CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE OriginalValue01 END OR
			ben.InitialProjection02 <> CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE OriginalValue02 END OR
			ben.InitialProjection03 <> CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE OriginalValue03 END OR
			ben.InitialProjection04 <> CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE OriginalValue04 END OR
			ben.InitialProjection05 <> CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE OriginalValue05 END OR
			ben.InitialProjection06 <> CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE OriginalValue06 END OR
			ben.InitialProjection07 <> CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE OriginalValue07 END OR
			ben.InitialProjection08 <> CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE OriginalValue08 END OR
			ben.InitialProjection09 <> CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE OriginalValue09 END OR
			ben.InitialProjection10 <> CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE OriginalValue10 END OR
			ben.InitialProjection11 <> CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE OriginalValue11 END OR
			ben.InitialProjection12 <> CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE OriginalValue12 END
		  )
	
	END
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits
		
 END
GO


---------------------------------------------

-- fp.procReimbursementAdjustmentActivityList
CREATE   PROCEDURE [fp].[procReimbursementAdjustmentActivityList]
	@budgetGUID UNIQUEIDENTIFIER,
	@start INT,
	@end INT,
	@search VARCHAR(MAX),
	@filter VARCHAR(MAX),
	@userGUID UNIQUEIDENTIFIER,
	@isDataSecured BIT,
	@dateTimeFormat VARCHAR(30),
	@userTimeZone VARCHAR(50)
AS 
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2022-04-13  MD  	 JAZZ-33206	Initial
 ** 2 	 2022-06-21  MY  	 JAZZ-36070	Unleash the Kraken (remove adjustment type limit)
 ** 3	 2023-09-21  MD  	 JAZZ-59398	Only pull back budget adjustments
 *************************************************************/
BEGIN

	DECLARE @guidEmpty UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000'
	DECLARE @pageSize INT = @end - @start;

	SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
	SET @filter = LOWER(NULLIF(@filter, ''))

	----------------------------------------------------------------------
	--Get all adjustments
	----------------------------------------------------------------------
	SELECT		AdjustmentID
				,GroupingHierarchyJSON					
	INTO	#adjustments
	FROM	fp.ReimbursementAdjustment AS slea WITH (NOLOCK)	
	WHERE	slea.BudgetConfigGUID = @budgetGUID
	AND		slea.BudgetPhaseID <> 2 --JAZZ-59398 only want to bring back budget grid and import adjustments

	CREATE CLUSTERED INDEX PK_Adjustmnets ON #adjustments (AdjustmentID)

	----------------------------------------------------------------------
	--Get import adjustments
	----------------------------------------------------------------------
	SELECT	iadj.AdjustmentID, 
			iadj.UnitTypeID
	INTO	#importAdjustments
	FROM	fp.viewReimbursementAdjustmentImport AS iadj WITH (NOLOCK)
			JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
	GROUP BY iadj.AdjustmentID,
			iadj.UnitTypeID

	CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID)

	----------------------------------------------------------------------
	--Build dto
	----------------------------------------------------------------------
		SELECT res.TotalRowsCount
		,res.AdjustmentID
		,res.BudgetConfigGUID
		,res.AdjustmentType
		,res.[Value]
		,res.AdjustmentFilterJSON
		,res.GroupingHierarchyJSON
		,res.AdjustedProperty
		,res.Comment
		,res.AuthorGUID
		,res.AuthorFullName
		,res.LastModifiedDateUtc
		,res.DateCreatedUtc
		,res.GroupingGUID
		,res.TimeClassID
		,3 as BudgetPhaseID --hardcode budget phase to 3 since not on fp.ReimbursementAdjustment
		,res.ClassificationGroupID
		,res.ClassificationCategoryID
		,res.JobCode
		,res.JobCodeCount
		,res.DepartmentCode
		,res.DepartmentCount
		,res.UnitTypeID
		,res.ImportUnitTypeIDs
		,res.IsRecordDeleted
		,res.IsCarryForward
	FROM (
			SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
				   *
		FROM (
			SELECT	ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
				, slea.AdjustmentID
				,slea.BudgetConfigGUID
				,slea.AdjustmentType
				,slea.[Value]
				,slea.AdjustmentFilterJSON
				,slea.GroupingHierarchyJSON
				,slea.AdjustedProperty
				,ISNULL(ag.Description, slea.Comment) AS Comment
				,slea.AuthorGUID
				,slea.AuthorFullName
				,slea.LastModifiedDateUtc
				,slea.DateCreatedUtc
				,slea.GroupingGUID
				,slea.TimeClassID
				,3 as BudgetPhaseID --hardcode budget phase to 3 since not on fp.ReimbursementAdjustment
				,slea.ClassificationGroupID
				,slea.ClassificationCategoryID
				,slea.UnitTypeID
				,NULL AS JobCode
				,NULL AS JobCodeCount
				,NULL AS DepartmentCode
				,NULL AS DepartmentCount
				,sai.ImportUnitTypeIDs
				,slea.IsRecordDeleted
				,slea.IsCarryForward
			FROM	fp.ReimbursementAdjustment AS slea WITH (NOLOCK)
			JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
			LEFT JOIN (
				SELECT	p.AdjustmentID, 
						ImportUnitTypeIDs =
							TRIM(STUFF(
								(SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5))
								FROM	#importAdjustments AS p2
								WHERE	p2.AdjustmentID = p.AdjustmentID
								GROUP BY p2.AdjustmentID, 
										p2.UnitTypeID
								FOR XML PATH(N''))
							, 1, 0, N''))
				FROM	#importAdjustments AS p
				GROUP BY p.AdjustmentID
			) AS sai ON sai.AdjustmentID = slea.AdjustmentID
			LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
			LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
			LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
				AND slea.ClassificationCategoryID = acc.CategoryID
			LEFT JOIN (
				SELECT	nsa.GroupingGUID
				FROM	fp.ReimbursementAdjustment as nsa WITH (NOLOCK)
				WHERE	nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types
						AND nsa.BudgetConfigGUID = @budgetGUID
				GROUP BY nsa.GroupingGUID
			) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
			WHERE	(slea.AdjustmentType <> 4 OR sai.ImportUnitTypeIDs <> '')
				AND (ra.GroupingGUID IS NULL OR slea.AdjustmentType IN (12, 13, 14))
				AND (@search IS NULL 
					OR (
							LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
							OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
							OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
							OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\'
							OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
							OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
							OR acc.[Name] LIKE @search ESCAPE '\'
							OR acg.[Name] LIKE @search ESCAPE '\'
							OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
							OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
							OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1
						)
				)
				AND (@filter IS NULL
				OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, 3) IN ( --hardcode budget phase to 3 since not on fp.ReimbursementAdjustment
					SELECT	[value]
					FROM	STRING_SPLIT(@filter, ' ')
					)
				)
			) AS res_inner
		WHERE res_inner.RowNumber = 1 )  AS res
	WHERE res.RowNumber = 1
	ORDER BY res.DateCreatedUtc DESC
	OFFSET @start ROWS
	FETCH NEXT @pageSize ROWS ONLY;	
END;
GO


---------------------------------------------

-- fp.procReimbursementChargesRateProjectionAnnualize
CREATE   PROCEDURE [fp].[procReimbursementChargesRateProjectionAnnualize]  
    @BudgetConfigID INT,
 	 @BudgetConfigGUID UNIQUEIDENTIFIER,
 	 @MonthsLoaded INT,
 	 @DefaultReimbursementProjectionMethodID INT
 AS
 /**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  BLI            Description
	 ** 1 	 2022-02-04   NT  	  JAZZ-31779	    Initial
	 ** 2 	 2023-04-03   MD  	  JAZZ-52160	    Update IDsToUpdate insert logic to include records that have no default projection method
	 *************************************************************/
 BEGIN
	DECLARE @UseDefault INT = -1
	IF @DefaultReimbursementProjectionMethodID = 1 BEGIN SET @UseDefault = 0 END

 	IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate

	CREATE TABLE #IDsToUpdate (ReimbursementChargesID INT, MonthsLoadedAverage DECIMAL(18,9))

	INSERT INTO #IDsToUpdate (ReimbursementChargesID, MonthsLoadedAverage)
	SELECT ReimbursementChargesID,
	CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetAsPercentOfCharge01 
		WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02) / 2
		WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03) / 3
		WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04) / 4
		WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05) / 5
		WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06) / 6
		WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07) / 7
		WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08) / 8
		WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09) / 9
		WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10) / 10
		WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10 + InitialProjectionNetAsPercentOfCharge11) / 11
		/* We don't allow MonthsLoaded to = 12 */ 
	END 
	FROM fp.FactReimbursementCharges chg 
	LEFT JOIN fp.ReimbursementProjectionMethod pm 
	 ON chg.PayorGroupID = pm.PayorGroupID
	WHERE chg.BudgetConfigID = @BudgetConfigID
	 AND (pm.ProjectionMethodID IN (1, @UseDefault) 
	 AND pm.BudgetConfigGUID = @BudgetConfigGUID) /* Annualized */

	 --Insert IDs whose payor groups are not explicitly defined in fp.ReimbursementProjectionMethod if the default projection method is annualized
	 IF (@UseDefault = 0)
	 BEGIN
		INSERT INTO #IDsToUpdate (ReimbursementChargesID, MonthsLoadedAverage)
		SELECT chg.ReimbursementChargesID,
		CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetAsPercentOfCharge01 
		 WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02) / 2
		 WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03) / 3
		 WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04) / 4
		 WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05) / 5
		 WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06) / 6
		 WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07) / 7
		 WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08) / 8
		 WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09) / 9
		 WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10) / 10
		 WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10 + InitialProjectionNetAsPercentOfCharge11) / 11
		 /* We don't allow MonthsLoaded to = 12 */ 
		END 
		FROM fp.FactReimbursementCharges chg 
		LEFT JOIN fp.ReimbursementProjectionMethod pm 
			ON chg.PayorGroupID = pm.PayorGroupID
			AND pm.BudgetConfigGUID = @BudgetConfigGUID
		LEFT JOIN #IDsToUpdate id on chg.ReimbursementChargesID = id.ReimbursementChargesID
		WHERE chg.BudgetConfigID = @BudgetConfigID
			AND pm.RowID is null
			AND id.ReimbursementChargesID IS NULL --Don't want to insert duplicates from first insert
	 END
	
	UPDATE
		chg
	SET
		InitialProjectionNetAsPercentOfCharge02 =
		CASE
			WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetAsPercentOfCharge02
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge03 =
		CASE
			WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetAsPercentOfCharge03
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge04 =
		CASE
			WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetAsPercentOfCharge04
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge05 =
		CASE
			WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetAsPercentOfCharge05
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge06 =
		CASE
			WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetAsPercentOfCharge06
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge07 =
		CASE
			WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetAsPercentOfCharge07
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge08 =
		CASE
			WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetAsPercentOfCharge08
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge09 =
		CASE
			WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetAsPercentOfCharge09
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge10 =
		CASE
			WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge11 =
		CASE
			WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11
			ELSE MonthsLoadedAverage
		END,
		InitialProjectionNetAsPercentOfCharge12 = MonthsLoadedAverage,
		InitialBudgetNetAsPercentOfCharge01 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge02 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge03 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge04 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge05 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge06 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge07 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge08 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge09 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge10 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge11 = MonthsLoadedAverage,     
		InitialBudgetNetAsPercentOfCharge12 = MonthsLoadedAverage
	FROM
		[fp].[FactReimbursementCharges] chg
	INNER JOIN #IDsToUpdate i ON
		chg.ReimbursementChargesID = i.ReimbursementChargesID

	UPDATE rcb    
	SET      
		AdjustedNetAsPercentOfCharge01 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge02 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge03 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge04 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge05 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge06 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge07 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge08 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge09 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge10 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge11 = MonthsLoadedAverage,     
		AdjustedNetAsPercentOfCharge12 = MonthsLoadedAverage
	FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID
	INNER JOIN [fp].[FactReimbursementChargesBudget] rcb on rc.ReimbursementChargesID = rcb.ReimbursementChargesID

	UPDATE rcp    
	SET      
		AdjustedNetAsPercentOfCharge01 =  InitialProjectionNetAsPercentOfCharge01,      
		AdjustedNetAsPercentOfCharge02 = CASE WHEN @MonthsLoaded >= 2  THEN InitialProjectionNetAsPercentOfCharge02 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge03 = CASE WHEN @MonthsLoaded >= 3  THEN InitialProjectionNetAsPercentOfCharge03 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge04 = CASE WHEN @MonthsLoaded >= 4  THEN InitialProjectionNetAsPercentOfCharge04 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge05 = CASE WHEN @MonthsLoaded >= 5  THEN InitialProjectionNetAsPercentOfCharge05 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge06 = CASE WHEN @MonthsLoaded >= 6  THEN InitialProjectionNetAsPercentOfCharge06 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge07 = CASE WHEN @MonthsLoaded >= 7  THEN InitialProjectionNetAsPercentOfCharge07 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge08 = CASE WHEN @MonthsLoaded >= 8  THEN InitialProjectionNetAsPercentOfCharge08 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge09 = CASE WHEN @MonthsLoaded >= 9  THEN InitialProjectionNetAsPercentOfCharge09 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11 ELSE MonthsLoadedAverage END,      
		AdjustedNetAsPercentOfCharge12 = MonthsLoadedAverage
	FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID
	INNER JOIN [fp].[FactReimbursementChargesProjection] rcp on rc.ReimbursementChargesID = rcp.ReimbursementChargesID

 	IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate
 	
 END
GO


---------------------------------------------

-- fp.procReimbursementChargesRateProjectionLastObserved
CREATE     PROCEDURE [fp].[procReimbursementChargesRateProjectionLastObserved]  
    @BudgetConfigID INT,
 	 @BudgetConfigGUID UNIQUEIDENTIFIER,
 	 @MonthsLoaded INT,
 	 @DefaultReimbursementProjectionMethodID INT,
	 @IsDebugFlag BIT = 0
 AS
 /**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  BLI            Description
	 ** 1 	 2022-02-07   NT  	  JAZZ-31779	    Initial
	 ** 2 	 2023-05-11   MD  	  JAZZ-52160	    Update IDsToUpdate insert logic to include records that have no default projection method
	 *************************************************************/
 BEGIN
	DECLARE @UseDefault INT = -1
	IF @DefaultReimbursementProjectionMethodID = 2 BEGIN SET @UseDefault = 0 END
	 	
	IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate
	IF OBJECT_ID('tempdb..#unpivoted') IS NOT NULL DROP TABLE #unpivoted
	IF OBJECT_ID('tempdb..#LastObservedMonth') IS NOT NULL DROP TABLE #LastObservedMonth
	
	CREATE TABLE #IDsToUpdate (
	 ReimbursementChargesID INT, 
	 LastObservedMonthValue DECIMAL(18,9)
	 )

	 --Create #unpivoted temp table to unpivot monthly Percent of Charge data to determine LastObservedMonth
	 CREATE TABLE #unpivoted (ReimbursementChargesID INT, MonthPivotColName VARCHAR(50), MonthNumber tinyint, MonthValue DECIMAL(19,8))

	 INSERT INTO #unpivoted(ReimbursementChargesID, MonthPivotColName, MonthNumber, MonthValue)
	 SELECT ReimbursementChargesID, MonthPivotColName, CAST(RIGHT(MonthPivotColName,2) AS INT) As MonthNumber, MonthValue
	 FROM  (SELECT ReimbursementChargesID,
				  InitialProjectionNetAsPercentOfCharge01,
				  InitialProjectionNetAsPercentOfCharge02,
				  InitialProjectionNetAsPercentOfCharge03,
				  InitialProjectionNetAsPercentOfCharge04,
				  InitialProjectionNetAsPercentOfCharge05,
				  InitialProjectionNetAsPercentOfCharge06,
				  InitialProjectionNetAsPercentOfCharge07,
				  InitialProjectionNetAsPercentOfCharge08,
				  InitialProjectionNetAsPercentOfCharge09,
				  InitialProjectionNetAsPercentOfCharge10,
				  InitialProjectionNetAsPercentOfCharge11,
				  InitialProjectionNetAsPercentOfCharge12
		FROM fp.FactReimbursementCharges chg
		INNER JOIN fp.ReimbursementProjectionMethod pm 
			ON chg.PayorGroupID = pm.PayorGroupID
		WHERE chg.BudgetConfigID = @BudgetConfigID
			AND pm.ProjectionMethodID IN (2, @UseDefault) /* Last Observed Month */
			AND pm.BudgetConfigGUID = @BudgetConfigGUID
		 ) pvt
	 UNPIVOT
	 (MonthValue For MonthPivotColName in (InitialProjectionNetAsPercentOfCharge01,
					InitialProjectionNetAsPercentOfCharge02,
					InitialProjectionNetAsPercentOfCharge03,
					InitialProjectionNetAsPercentOfCharge04,
					InitialProjectionNetAsPercentOfCharge05,
					InitialProjectionNetAsPercentOfCharge06,
					InitialProjectionNetAsPercentOfCharge07,
					InitialProjectionNetAsPercentOfCharge08,
					InitialProjectionNetAsPercentOfCharge09,
					InitialProjectionNetAsPercentOfCharge10,
					InitialProjectionNetAsPercentOfCharge11,
					InitialProjectionNetAsPercentOfCharge12)) As unpvt

	--Create temporary table for LastObservedMonthValue per ReimbursementChargesID
	CREATE TABLE #LastObservedMonth (ReimbursementChargesID INT, LastObservedMonth INT)

	INSERT INTO #LastObservedMonth (ReimbursementChargesID, LastObservedMonth)
	SELECT ReimbursementChargesID, MAX(MonthNumber) AS LastObservedMonth --Last Month that is non-zero
	FROM #unpivoted  
	WHERE MonthNumber <= @MonthsLoaded  --Only Months that are imported
	AND MonthValue > 0 --MonthValue is not 0
	GROUP BY ReimbursementChargesID

	--Now Insert LastObservedMonthValue based on #LastObservedMonth & DISTINCT ReimbursementChargesID from #unpivoted
	INSERT INTO #IDsToUpdate (ReimbursementChargesID, LastObservedMonthValue)
	SELECT uv.ReimbursementChargesID, ISNULL(LastObservedMonthValue, 0)
	FROM (SELECT DISTINCT ReimbursementChargesID
		  FROM #unpivoted) uv
	LEFT JOIN (SELECT lom.ReimbursementChargesID, lommv.MonthValue As LastObservedMonthValue
			   FROM #LastObservedMonth lom
				INNER JOIN #unpivoted lommv 
				 ON lommv.ReimbursementChargesID = lom.ReimbursementChargesID
				AND lommv.MonthNumber = lom.LastObservedMonth
			   ) lom
     ON uv.ReimbursementChargesID = lom.ReimbursementChargesID

	 IF(@UseDefault = 0)
	 BEGIN 
		INSERT INTO #unpivoted(ReimbursementChargesID, MonthPivotColName, MonthNumber, MonthValue)
			SELECT ReimbursementChargesID, MonthPivotColName, CAST(RIGHT(MonthPivotColName,2) AS INT) As MonthNumber, MonthValue
			FROM  (SELECT chg.ReimbursementChargesID,
						InitialProjectionNetAsPercentOfCharge01,
						InitialProjectionNetAsPercentOfCharge02,
						InitialProjectionNetAsPercentOfCharge03,
						InitialProjectionNetAsPercentOfCharge04,
						InitialProjectionNetAsPercentOfCharge05,
						InitialProjectionNetAsPercentOfCharge06,
						InitialProjectionNetAsPercentOfCharge07,
						InitialProjectionNetAsPercentOfCharge08,
						InitialProjectionNetAsPercentOfCharge09,
						InitialProjectionNetAsPercentOfCharge10,
						InitialProjectionNetAsPercentOfCharge11,
						InitialProjectionNetAsPercentOfCharge12
			FROM fp.FactReimbursementCharges chg
			LEFT JOIN fp.ReimbursementProjectionMethod pm 
				ON chg.PayorGroupID = pm.PayorGroupID
				AND pm.BudgetConfigGUID = @BudgetConfigGUID
			LEFT JOIN #unpivoted uv on chg.ReimbursementChargesID = uv.ReimbursementChargesID
			WHERE chg.BudgetConfigID = @BudgetConfigID
				AND uv.ReimbursementChargesID IS NULL
				AND pm.RowID IS NULL
				) pvt
			UNPIVOT
			(MonthValue For MonthPivotColName in (InitialProjectionNetAsPercentOfCharge01,
						InitialProjectionNetAsPercentOfCharge02,
						InitialProjectionNetAsPercentOfCharge03,
						InitialProjectionNetAsPercentOfCharge04,
						InitialProjectionNetAsPercentOfCharge05,
						InitialProjectionNetAsPercentOfCharge06,
						InitialProjectionNetAsPercentOfCharge07,
						InitialProjectionNetAsPercentOfCharge08,
						InitialProjectionNetAsPercentOfCharge09,
						InitialProjectionNetAsPercentOfCharge10,
						InitialProjectionNetAsPercentOfCharge11,
						InitialProjectionNetAsPercentOfCharge12)) As unpvt

		INSERT INTO #LastObservedMonth (ReimbursementChargesID, LastObservedMonth)
		SELECT uv.ReimbursementChargesID, MAX(MonthNumber) AS LastObservedMonth --Last Month that is non-zero
		FROM #unpivoted uv
		LEFT JOIN #LastObservedMonth lm on uv.ReimbursementChargesID = lm.ReimbursementChargesID
		WHERE MonthNumber <= @MonthsLoaded  --Only Months that are imported
			AND MonthValue > 0 --MonthValue is not 0
		GROUP BY uv.ReimbursementChargesID

		--Now Insert LastObservedMonthValue based on #LastObservedMonth & DISTINCT ReimbursementChargesID from #unpivoted
		INSERT INTO #IDsToUpdate (ReimbursementChargesID, LastObservedMonthValue)
		SELECT uv.ReimbursementChargesID, ISNULL(lom.LastObservedMonthValue, 0)
		FROM (SELECT DISTINCT ReimbursementChargesID
				FROM #unpivoted) uv
		LEFT JOIN (SELECT lom.ReimbursementChargesID, lommv.MonthValue As LastObservedMonthValue
					FROM #LastObservedMonth lom
					INNER JOIN #unpivoted lommv 
						ON lommv.ReimbursementChargesID = lom.ReimbursementChargesID
					AND lommv.MonthNumber = lom.LastObservedMonth
					) lom
		ON uv.ReimbursementChargesID = lom.ReimbursementChargesID
		LEFT JOIN #IDsToUpdate id on uv.ReimbursementChargesID = id.ReimbursementChargesID
	 END

	IF (@IsDebugFlag = 1)
	BEGIN
		PRINT 'Debug Mode ON'
		SELECT '#unpivoted', * FROM #unpivoted
		SELECT '#LastObservedMonth' FROM #LastObservedMonth
		SELECT '#IDsToUpdate', * FROM #IDsToUpdate
	END
	ELSE
	BEGIN
		UPDATE chg SET
			InitialProjectionNetAsPercentOfCharge02 =
			CASE
				WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetAsPercentOfCharge02
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge03 =
			CASE
				WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetAsPercentOfCharge03
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge04 =
			CASE
				WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetAsPercentOfCharge04
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge05 =
			CASE
				WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetAsPercentOfCharge05
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge06 =
			CASE
				WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetAsPercentOfCharge06
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge07 =
			CASE
				WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetAsPercentOfCharge07
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge08 =
			CASE
				WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetAsPercentOfCharge08
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge09 =
			CASE
				WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetAsPercentOfCharge09
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge10 =
			CASE
				WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge11 =
			CASE
				WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11
				ELSE LastObservedMonthValue
			END,
			InitialProjectionNetAsPercentOfCharge12 = LastObservedMonthValue,
			InitialBudgetNetAsPercentOfCharge01 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge02 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge03 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge04 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge05 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge06 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge07 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge08 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge09 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge10 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge11 = LastObservedMonthValue,     
			InitialBudgetNetAsPercentOfCharge12 = LastObservedMonthValue
		FROM
			[fp].[FactReimbursementCharges] chg
		INNER JOIN #IDsToUpdate i ON
			chg.ReimbursementChargesID = i.ReimbursementChargesID

		UPDATE rcb    
		SET      
			AdjustedNetAsPercentOfCharge01 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge02 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge03 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge04 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge05 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge06 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge07 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge08 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge09 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge10 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge11 = LastObservedMonthValue,     
			AdjustedNetAsPercentOfCharge12 = LastObservedMonthValue
		FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID
		INNER JOIN [fp].[FactReimbursementChargesBudget] rcb on rc.ReimbursementChargesID = rcb.ReimbursementChargesID

		UPDATE rcp    
		SET      
			AdjustedNetAsPercentOfCharge01 =  InitialProjectionNetAsPercentOfCharge01,      
			AdjustedNetAsPercentOfCharge02 = CASE WHEN @MonthsLoaded >= 2  THEN InitialProjectionNetAsPercentOfCharge02 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge03 = CASE WHEN @MonthsLoaded >= 3  THEN InitialProjectionNetAsPercentOfCharge03 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge04 = CASE WHEN @MonthsLoaded >= 4  THEN InitialProjectionNetAsPercentOfCharge04 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge05 = CASE WHEN @MonthsLoaded >= 5  THEN InitialProjectionNetAsPercentOfCharge05 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge06 = CASE WHEN @MonthsLoaded >= 6  THEN InitialProjectionNetAsPercentOfCharge06 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge07 = CASE WHEN @MonthsLoaded >= 7  THEN InitialProjectionNetAsPercentOfCharge07 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge08 = CASE WHEN @MonthsLoaded >= 8  THEN InitialProjectionNetAsPercentOfCharge08 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge09 = CASE WHEN @MonthsLoaded >= 9  THEN InitialProjectionNetAsPercentOfCharge09 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11 ELSE LastObservedMonthValue END,      
			AdjustedNetAsPercentOfCharge12 = LastObservedMonthValue
		FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID
		INNER JOIN [fp].[FactReimbursementChargesProjection] rcp on rc.ReimbursementChargesID = rcp.ReimbursementChargesID
 	 	
	END
	
 	IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate
 	IF OBJECT_ID('tempdb..#unpivoted') IS NOT NULL DROP TABLE #unpivoted
	IF OBJECT_ID('tempdb..#LastObservedMonth') IS NOT NULL DROP TABLE #LastObservedMonth

 END
GO


---------------------------------------------

-- fp.procReimbursementEncounterRateProjectionAnnualize
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			  Description
 ** 1 	 2022-02-03  BK  	 JAZZ-31778	  Initial
 ** 2 	 2023-04-03  MD  	 JAZZ-52160	  Update IDsToUpdate insert logic to include records that have no default projection method
*************************************************************/	 
CREATE   PROCEDURE [fp].[procReimbursementEncounterRateProjectionAnnualize]
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@BudgetConfigID INT,
	@MonthsLoaded TINYINT,
	@DefaultProjectionMethodID INT
AS
BEGIN

IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate

CREATE TABLE #IDsToUpdate (ReimbursementEncounterID INT, MonthsLoadedAverage DECIMAL(18,9))

DECLARE @UseDefault INT = -1
IF @DefaultProjectionMethodID = 1 BEGIN SET @UseDefault = 0 END

INSERT INTO #IDsToUpdate (ReimbursementEncounterID, MonthsLoadedAverage)
SELECT ReimbursementEncounterID,
	CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetPerEncounter01 
	 WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02) / 2
	 WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03) / 3
	 WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04) / 4
	 WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05) / 5
	 WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06) / 6
	 WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07) / 7
	 WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08) / 8
	 WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09) / 9
	 WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10) / 10
	 WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10 + InitialProjectionNetPerEncounter11) / 11
	 /* We don't allow MonthsLoaded to = 12 */ 
	END 
FROM fp.FactReimbursementEncounter enc 
LEFT JOIN fp.ReimbursementProjectionMethod pm 
	ON enc.PayorGroupID = pm.PayorGroupID
	AND pm.BudgetConfigGUID = @BudgetConfigGUID
WHERE enc.BudgetConfigID = @BudgetConfigID
	AND pm.ProjectionMethodID IN (1, @UseDefault) /* Annualized */

--Insert IDs whose payor groups are not explicitly defined in fp.ReimbursementProjectionMethod if the default projection method is annualized
IF (@UseDefault = 0)
BEGIN
	INSERT INTO #IDsToUpdate (ReimbursementEncounterID, MonthsLoadedAverage)
SELECT enc.ReimbursementEncounterID,
	CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetPerEncounter01 
	 WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02) / 2
	 WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03) / 3
	 WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04) / 4
	 WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05) / 5
	 WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06) / 6
	 WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07) / 7
	 WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08) / 8
	 WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09) / 9
	 WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10) / 10
	 WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10 + InitialProjectionNetPerEncounter11) / 11
	 /* We don't allow MonthsLoaded to = 12 */ 
	END 
FROM fp.FactReimbursementEncounter enc 
LEFT JOIN fp.ReimbursementProjectionMethod pm 
	 ON enc.PayorGroupID = pm.PayorGroupID
	 AND pm.BudgetConfigGUID = @BudgetConfigGUID
LEFT JOIN #IDsToUpdate id on enc.ReimbursementEncounterID = id.ReimbursementEncounterID
WHERE 
	enc.BudgetConfigID = @BudgetConfigID
	AND pm.RowID is null
	AND id.ReimbursementEncounterID IS NULL --Don't want to insert duplicates from first insert
END

UPDATE re    
SET      
    InitialProjectionNetPerEncounter02 = CASE WHEN @MonthsLoaded >= 2  THEN InitialProjectionNetPerEncounter02 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter03 = CASE WHEN @MonthsLoaded >= 3  THEN InitialProjectionNetPerEncounter03 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter04 = CASE WHEN @MonthsLoaded >= 4  THEN InitialProjectionNetPerEncounter04 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter05 = CASE WHEN @MonthsLoaded >= 5  THEN InitialProjectionNetPerEncounter05 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter06 = CASE WHEN @MonthsLoaded >= 6  THEN InitialProjectionNetPerEncounter06 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter07 = CASE WHEN @MonthsLoaded >= 7  THEN InitialProjectionNetPerEncounter07 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter08 = CASE WHEN @MonthsLoaded >= 8  THEN InitialProjectionNetPerEncounter08 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter09 = CASE WHEN @MonthsLoaded >= 9  THEN InitialProjectionNetPerEncounter09 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE MonthsLoadedAverage END,      
    InitialProjectionNetPerEncounter12 = MonthsLoadedAverage,
	InitialBudgetNetPerEncounter01 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter02 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter03 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter04 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter05 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter06 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter07 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter08 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter09 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter10 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter11 = MonthsLoadedAverage,     
	InitialBudgetNetPerEncounter12 = MonthsLoadedAverage
FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID
   
UPDATE reb    
SET      
	AdjustedNetPerEncounterValue01 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue02 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue03 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue04 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue05 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue06 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue07 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue08 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue09 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue10 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue11 = MonthsLoadedAverage,     
	AdjustedNetPerEncounterValue12 = MonthsLoadedAverage
FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID
	INNER JOIN fp.FactReimbursementEncounterBudget reb on re.ReimbursementEncounterID = reb.ReimbursementEncounterID

UPDATE rep    
SET      
    AdjustedNetPerEncounterValue01 =  InitialProjectionNetPerEncounter01,      
    AdjustedNetPerEncounterValue02 = CASE WHEN @MonthsLoaded >= 2  THEN InitialProjectionNetPerEncounter02 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue03 = CASE WHEN @MonthsLoaded >= 3  THEN InitialProjectionNetPerEncounter03 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue04 = CASE WHEN @MonthsLoaded >= 4  THEN InitialProjectionNetPerEncounter04 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue05 = CASE WHEN @MonthsLoaded >= 5  THEN InitialProjectionNetPerEncounter05 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue06 = CASE WHEN @MonthsLoaded >= 6  THEN InitialProjectionNetPerEncounter06 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue07 = CASE WHEN @MonthsLoaded >= 7  THEN InitialProjectionNetPerEncounter07 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue08 = CASE WHEN @MonthsLoaded >= 8  THEN InitialProjectionNetPerEncounter08 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue09 = CASE WHEN @MonthsLoaded >= 9  THEN InitialProjectionNetPerEncounter09 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE MonthsLoadedAverage END,      
    AdjustedNetPerEncounterValue12 = MonthsLoadedAverage
FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID
	INNER JOIN fp.FactReimbursementEncounterProjection rep on re.ReimbursementEncounterID = rep.ReimbursementEncounterID
END
GO


---------------------------------------------

-- fp.procReimbursementEncounterRateProjectionLastObserved
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			  Description
 ** 1 	 2022-02-03  BK  	 JAZZ-31778	  Initial
 ** 2 	 2023-05-11  MD  	 JAZZ-52160	  Update IDsToUpdate insert logic to include records that have no default projection method
*************************************************************/	 
CREATE   PROCEDURE [fp].[procReimbursementEncounterRateProjectionLastObserved]
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@BudgetConfigID INT,
	@MonthsLoaded TINYINT,
	@DefaultProjectionMethodID INT
AS
BEGIN

IF OBJECT_ID('tempdb..#UnpivotedValues') IS NOT NULL DROP TABLE #UnpivotedValues
IF OBJECT_ID('tempdb..#LastMonth') IS NOT NULL DROP TABLE #LastMonth
IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate

DECLARE @UseDefault INT = -1
IF @DefaultProjectionMethodID = 2 BEGIN SET @UseDefault = 0 END

CREATE TABLE #UnpivotedValues (ReimbursementEncounterID INT, MonthValue VARCHAR(35), MonthID INT, PerEncounterValue DECIMAL(18,9))
CREATE TABLE #LastMonth (ReimbursementEncounterID INT, MonthValue VARCHAR(35))
CREATE TABLE #IDsToUpdate (ReimbursementEncounterID INT, LastObservedValue DECIMAL(18,9))

INSERT INTO #UnpivotedValues (ReimbursementEncounterID, MonthValue, MonthID, PerEncounterValue)
SELECT ReimbursementEncounterID, MonthValue, CAST(RIGHT(MonthValue,2) as INT), PerEncounterValue
FROM 
(SELECT ReimbursementEncounterID, PayorGroupID, InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12 
		FROM fp.FactReimbursementEncounter WHERE BudgetConfigID = @BudgetConfigID) e
   UNPIVOT 
   (PerEncounterValue FOR MonthValue IN (InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12) ) AS enc
  
INNER JOIN fp.ReimbursementProjectionMethod pm on enc.PayorGroupID = pm.PayorGroupID
WHERE ProjectionMethodID IN (2, @UseDefault) /* Last Observed Month */
	AND BudgetConfigGUID = @BudgetConfigGUID 

  
INSERT INTO #LastMonth (ReimbursementEncounterID, MonthValue)
SELECT ReimbursementEncounterID, MAX(MonthValue) 
FROM #UnpivotedValues WHERE PerEncounterValue > 0 AND MonthID <= @MonthsLoaded
GROUP BY ReimbursementEncounterID

INSERT INTO #IDsToUpdate (ReimbursementEncounterID, LastObservedValue)
SELECT uv.ReimbursementEncounterID, ISNULL(PerEncounterValue, 0) 
FROM (SELECT DISTINCT ReimbursementEncounterID  FROM #UnpivotedValues) uv LEFT JOIN
(SELECT uv.* FROM #UnpivotedValues uv INNER JOIN #LastMonth lm ON uv.ReimbursementEncounterID = lm.ReimbursementEncounterID AND uv.MonthValue = lm.MonthValue) lastObserved
ON uv.ReimbursementEncounterID = lastObserved.ReimbursementEncounterID

--Insert IDs whose payor groups are not explicitly defined in fp.ReimbursementProjectionMethod if the default projection method is annualized
IF (@UseDefault = 0)
BEGIN
	INSERT INTO #UnpivotedValues (ReimbursementEncounterID, MonthValue, MonthID, PerEncounterValue)
	SELECT enc.ReimbursementEncounterID, enc.MonthValue, CAST(RIGHT(enc.MonthValue,2) as INT), enc.PerEncounterValue
	FROM 
	(SELECT ReimbursementEncounterID, BudgetConfigID, PayorGroupID, InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12 
			FROM fp.FactReimbursementEncounter WHERE BudgetConfigID = @BudgetConfigID) e
	   UNPIVOT 
	   (PerEncounterValue FOR MonthValue IN (InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12) ) 
	AS enc  
	LEFT JOIN fp.ReimbursementProjectionMethod pm 
		ON enc.PayorGroupID = pm.PayorGroupID
		AND pm.BudgetConfigGUID = @BudgetConfigGUID
	LEFT JOIN #UnpivotedValues uv on enc.ReimbursementEncounterID = uv.ReimbursementEncounterID
	WHERE enc.BudgetConfigID = @BudgetConfigID 
		AND uv.ReimbursementEncounterID IS NULL --Don't want to insert duplicates from first insert
		AND pm.RowID IS NULL
  
	INSERT INTO #LastMonth (ReimbursementEncounterID, MonthValue)
	SELECT uv.ReimbursementEncounterID, MAX(uv.MonthValue) 
	FROM #UnpivotedValues uv
	LEFT JOIN #LastMonth lm on uv.ReimbursementEncounterID = lm.ReimbursementEncounterID
	WHERE PerEncounterValue > 0 AND MonthID <= @MonthsLoaded	
	GROUP BY uv.ReimbursementEncounterID

	INSERT INTO #IDsToUpdate (ReimbursementEncounterID, LastObservedValue)
	SELECT uv.ReimbursementEncounterID, ISNULL(PerEncounterValue, 0) 
	FROM (SELECT DISTINCT ReimbursementEncounterID  FROM #UnpivotedValues) uv 
	LEFT JOIN
	(SELECT uv.* FROM #UnpivotedValues uv INNER JOIN #LastMonth lm ON uv.ReimbursementEncounterID = lm.ReimbursementEncounterID AND uv.MonthValue = lm.MonthValue) lastObserved
	ON uv.ReimbursementEncounterID = lastObserved.ReimbursementEncounterID
	LEFT JOIN #IDsToUpdate id on uv.ReimbursementEncounterID = id.ReimbursementEncounterID
END

UPDATE re    
SET      
    InitialProjectionNetPerEncounter02 = CASE WHEN @MonthsLoaded >= 2  THEN InitialProjectionNetPerEncounter02 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter03 = CASE WHEN @MonthsLoaded >= 3  THEN InitialProjectionNetPerEncounter03 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter04 = CASE WHEN @MonthsLoaded >= 4  THEN InitialProjectionNetPerEncounter04 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter05 = CASE WHEN @MonthsLoaded >= 5  THEN InitialProjectionNetPerEncounter05 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter06 = CASE WHEN @MonthsLoaded >= 6  THEN InitialProjectionNetPerEncounter06 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter07 = CASE WHEN @MonthsLoaded >= 7  THEN InitialProjectionNetPerEncounter07 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter08 = CASE WHEN @MonthsLoaded >= 8  THEN InitialProjectionNetPerEncounter08 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter09 = CASE WHEN @MonthsLoaded >= 9  THEN InitialProjectionNetPerEncounter09 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE LastObservedValue END,      
    InitialProjectionNetPerEncounter12 = LastObservedValue,
	InitialBudgetNetPerEncounter01 = LastObservedValue,     
	InitialBudgetNetPerEncounter02 = LastObservedValue,     
	InitialBudgetNetPerEncounter03 = LastObservedValue,     
	InitialBudgetNetPerEncounter04 = LastObservedValue,     
	InitialBudgetNetPerEncounter05 = LastObservedValue,     
	InitialBudgetNetPerEncounter06 = LastObservedValue,     
	InitialBudgetNetPerEncounter07 = LastObservedValue,     
	InitialBudgetNetPerEncounter08 = LastObservedValue,     
	InitialBudgetNetPerEncounter09 = LastObservedValue,     
	InitialBudgetNetPerEncounter10 = LastObservedValue,     
	InitialBudgetNetPerEncounter11 = LastObservedValue,     
	InitialBudgetNetPerEncounter12 = LastObservedValue
FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID
   
UPDATE reb    
SET      
	AdjustedNetPerEncounterValue01 = LastObservedValue,     
	AdjustedNetPerEncounterValue02 = LastObservedValue,     
	AdjustedNetPerEncounterValue03 = LastObservedValue,     
	AdjustedNetPerEncounterValue04 = LastObservedValue,     
	AdjustedNetPerEncounterValue05 = LastObservedValue,     
	AdjustedNetPerEncounterValue06 = LastObservedValue,     
	AdjustedNetPerEncounterValue07 = LastObservedValue,     
	AdjustedNetPerEncounterValue08 = LastObservedValue,     
	AdjustedNetPerEncounterValue09 = LastObservedValue,     
	AdjustedNetPerEncounterValue10 = LastObservedValue,     
	AdjustedNetPerEncounterValue11 = LastObservedValue,     
	AdjustedNetPerEncounterValue12 = LastObservedValue
FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID
	INNER JOIN fp.FactReimbursementEncounterBudget reb on re.ReimbursementEncounterID = reb.ReimbursementEncounterID

UPDATE rep    
SET      
    AdjustedNetPerEncounterValue01 =  InitialProjectionNetPerEncounter01,      
    AdjustedNetPerEncounterValue02 = CASE WHEN @MonthsLoaded >= 2  THEN InitialProjectionNetPerEncounter02 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue03 = CASE WHEN @MonthsLoaded >= 3  THEN InitialProjectionNetPerEncounter03 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue04 = CASE WHEN @MonthsLoaded >= 4  THEN InitialProjectionNetPerEncounter04 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue05 = CASE WHEN @MonthsLoaded >= 5  THEN InitialProjectionNetPerEncounter05 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue06 = CASE WHEN @MonthsLoaded >= 6  THEN InitialProjectionNetPerEncounter06 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue07 = CASE WHEN @MonthsLoaded >= 7  THEN InitialProjectionNetPerEncounter07 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue08 = CASE WHEN @MonthsLoaded >= 8  THEN InitialProjectionNetPerEncounter08 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue09 = CASE WHEN @MonthsLoaded >= 9  THEN InitialProjectionNetPerEncounter09 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE LastObservedValue END,      
    AdjustedNetPerEncounterValue12 = LastObservedValue
FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID
	INNER JOIN fp.FactReimbursementEncounterProjection rep on re.ReimbursementEncounterID = rep.ReimbursementEncounterID
END
GO


---------------------------------------------

-- fp.procReimbursementGLToGLCrosswalk
CREATE   PROCEDURE [fp].[procReimbursementGLToGLCrosswalk]
	@BudgetConfigID INT,
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@EntityConfigID INT,	
	@MonthsLoaded INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS 
BEGIN

	/**************************************************************
	** Change History
	
	** CID  Date 		Author  WI 			Description
	** 1	2023-07-31  AO 		JAZZ-57673  Initial
	*************************************************************/

	IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances
	IF OBJECT_ID('tempdb..#tmpReimbursementGL') IS NOT NULL DROP TABLE #tmpReimbursementGL
	IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc
	IF OBJECT_ID('tempdb..#uniquePayorGroups') IS NOT NULL DROP TABLE #uniquePayorGroups
	IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert

	CREATE TABLE #tmpReimbursementGL (
		BudgetConfigID INT,
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		TargetAdjusted01 DECIMAL (19,8),
		TargetAdjusted02 DECIMAL (19,8),
		TargetAdjusted03 DECIMAL (19,8),
		TargetAdjusted04 DECIMAL (19,8),
		TargetAdjusted05 DECIMAL (19,8),
		TargetAdjusted06 DECIMAL (19,8),
		TargetAdjusted07 DECIMAL (19,8),
		TargetAdjusted08 DECIMAL (19,8),
		TargetAdjusted09 DECIMAL (19,8),
		TargetAdjusted10 DECIMAL (19,8),
		TargetAdjusted11 DECIMAL (19,8),
		TargetAdjusted12 DECIMAL (19,8),

		BudgetAdjusted01 DECIMAL (19,8),
		BudgetAdjusted02 DECIMAL (19,8),
		BudgetAdjusted03 DECIMAL (19,8),
		BudgetAdjusted04 DECIMAL (19,8),
		BudgetAdjusted05 DECIMAL (19,8),
		BudgetAdjusted06 DECIMAL (19,8),
		BudgetAdjusted07 DECIMAL (19,8),
		BudgetAdjusted08 DECIMAL (19,8),
		BudgetAdjusted09 DECIMAL (19,8),
		BudgetAdjusted10 DECIMAL (19,8),
		BudgetAdjusted11 DECIMAL (19,8),
		BudgetAdjusted12 DECIMAL (19,8),

		ProjectionAdjusted01 DECIMAL (19,8),
		ProjectionAdjusted02 DECIMAL (19,8),
		ProjectionAdjusted03 DECIMAL (19,8),
		ProjectionAdjusted04 DECIMAL (19,8),
		ProjectionAdjusted05 DECIMAL (19,8),
		ProjectionAdjusted06 DECIMAL (19,8),
		ProjectionAdjusted07 DECIMAL (19,8),
		ProjectionAdjusted08 DECIMAL (19,8),
		ProjectionAdjusted09 DECIMAL (19,8),
		ProjectionAdjusted10 DECIMAL (19,8),
		ProjectionAdjusted11 DECIMAL (19,8),
		ProjectionAdjusted12 DECIMAL (19,8),

		TargetAdjustedNetReimbursement01 DECIMAL (19,8),
		TargetAdjustedNetReimbursement02 DECIMAL (19,8),
		TargetAdjustedNetReimbursement03 DECIMAL (19,8),
		TargetAdjustedNetReimbursement04 DECIMAL (19,8),
		TargetAdjustedNetReimbursement05 DECIMAL (19,8),
		TargetAdjustedNetReimbursement06 DECIMAL (19,8),
		TargetAdjustedNetReimbursement07 DECIMAL (19,8),
		TargetAdjustedNetReimbursement08 DECIMAL (19,8),
		TargetAdjustedNetReimbursement09 DECIMAL (19,8),
		TargetAdjustedNetReimbursement10 DECIMAL (19,8),
		TargetAdjustedNetReimbursement11 DECIMAL (19,8),
		TargetAdjustedNetReimbursement12 DECIMAL (19,8),

		BudgetAdjustedNetReimbursement01 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement02 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement03 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement04 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement05 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement06 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement07 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement08 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement09 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement10 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement11 DECIMAL (19,8),
		BudgetAdjustedNetReimbursement12 DECIMAL (19,8),

		ProjectionAdjustedNetReimbursement01 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement02 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement03 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement04 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement05 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement06 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement07 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement08 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement09 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement10 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement11 DECIMAL (19,8),
		ProjectionAdjustedNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpConAllowanceCalc (
		BudgetConfigID INT,
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		TargetConAllowance01 DECIMAL (19,8),
		TargetConAllowance02 DECIMAL (19,8),
		TargetConAllowance03 DECIMAL (19,8),
		TargetConAllowance04 DECIMAL (19,8),
		TargetConAllowance05 DECIMAL (19,8),
		TargetConAllowance06 DECIMAL (19,8),
		TargetConAllowance07 DECIMAL (19,8),
		TargetConAllowance08 DECIMAL (19,8),
		TargetConAllowance09 DECIMAL (19,8),
		TargetConAllowance10 DECIMAL (19,8),
		TargetConAllowance11 DECIMAL (19,8),
		TargetConAllowance12 DECIMAL (19,8),

		BudgetConAllowance01 DECIMAL (19,8),
		BudgetConAllowance02 DECIMAL (19,8),
		BudgetConAllowance03 DECIMAL (19,8),
		BudgetConAllowance04 DECIMAL (19,8),
		BudgetConAllowance05 DECIMAL (19,8),
		BudgetConAllowance06 DECIMAL (19,8),
		BudgetConAllowance07 DECIMAL (19,8),
		BudgetConAllowance08 DECIMAL (19,8),
		BudgetConAllowance09 DECIMAL (19,8),
		BudgetConAllowance10 DECIMAL (19,8),
		BudgetConAllowance11 DECIMAL (19,8),
		BudgetConAllowance12 DECIMAL (19,8),

		ProjectionConAllowance01 DECIMAL (19,8),
		ProjectionConAllowance02 DECIMAL (19,8),
		ProjectionConAllowance03 DECIMAL (19,8),
		ProjectionConAllowance04 DECIMAL (19,8),
		ProjectionConAllowance05 DECIMAL (19,8),
		ProjectionConAllowance06 DECIMAL (19,8),
		ProjectionConAllowance07 DECIMAL (19,8),
		ProjectionConAllowance08 DECIMAL (19,8),
		ProjectionConAllowance09 DECIMAL (19,8),
		ProjectionConAllowance10 DECIMAL (19,8),
		ProjectionConAllowance11 DECIMAL (19,8),
		ProjectionConAllowance12 DECIMAL (19,8)
	)

	--------------------------------------------------------------
	--Get reimbursement contractual allowances config for given budget config
	--------------------------------------------------------------
	SELECT
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID,
		sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent,
		sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent
	INTO #contractualAllowances
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID
	INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID

	SELECT
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID
	INTO #uniquePayorGroups
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID
	INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID

	--------------------------------------------------------------
	--Get reimbursement data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementGL (PayorGroupID, EntityID, PatientClassID, 
		TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06,
		TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12,
		BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03,BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06,
		BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12,
		ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06,
		ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12,
		TargetAdjustedNetReimbursement01, TargetAdjustedNetReimbursement02, TargetAdjustedNetReimbursement03, TargetAdjustedNetReimbursement04,
		TargetAdjustedNetReimbursement05, TargetAdjustedNetReimbursement06, TargetAdjustedNetReimbursement07, TargetAdjustedNetReimbursement08,
		TargetAdjustedNetReimbursement09, TargetAdjustedNetReimbursement10, TargetAdjustedNetReimbursement11, TargetAdjustedNetReimbursement12,
		BudgetAdjustedNetReimbursement01, BudgetAdjustedNetReimbursement02, BudgetAdjustedNetReimbursement03, BudgetAdjustedNetReimbursement04,
		BudgetAdjustedNetReimbursement05, BudgetAdjustedNetReimbursement06, BudgetAdjustedNetReimbursement07, BudgetAdjustedNetReimbursement08,
		BudgetAdjustedNetReimbursement09, BudgetAdjustedNetReimbursement10, BudgetAdjustedNetReimbursement11, BudgetAdjustedNetReimbursement12,
		ProjectionAdjustedNetReimbursement01, ProjectionAdjustedNetReimbursement02, ProjectionAdjustedNetReimbursement03, ProjectionAdjustedNetReimbursement04,
		ProjectionAdjustedNetReimbursement05, ProjectionAdjustedNetReimbursement06, ProjectionAdjustedNetReimbursement07, ProjectionAdjustedNetReimbursement08,
		ProjectionAdjustedNetReimbursement09, ProjectionAdjustedNetReimbursement10, ProjectionAdjustedNetReimbursement11, ProjectionAdjustedNetReimbursement12)

	SELECT 
		upg.PayorGroupID,
		upg.EntityID,
		upg.PatientClassID,
		SUM(TargetAdjusted01),
		SUM(TargetAdjusted02),
		SUM(TargetAdjusted03),
		SUM(TargetAdjusted04),
		SUM(TargetAdjusted05),
		SUM(TargetAdjusted06),
		SUM(TargetAdjusted07),
		SUM(TargetAdjusted08),
		SUM(TargetAdjusted09),
		SUM(TargetAdjusted10),
		SUM(TargetAdjusted11),
		SUM(TargetAdjusted12),

		SUM(BudgetAdjusted01),
		SUM(BudgetAdjusted02),
		SUM(BudgetAdjusted03),
		SUM(BudgetAdjusted04),
		SUM(BudgetAdjusted05),
		SUM(BudgetAdjusted06),
		SUM(BudgetAdjusted07),
		SUM(BudgetAdjusted08),
		SUM(BudgetAdjusted09),
		SUM(BudgetAdjusted10),
		SUM(BudgetAdjusted11),
		SUM(BudgetAdjusted12),

		SUM(ProjectionAdjusted01),
		SUM(ProjectionAdjusted02),
		SUM(ProjectionAdjusted03),
		SUM(ProjectionAdjusted04),
		SUM(ProjectionAdjusted05),
		SUM(ProjectionAdjusted06),
		SUM(ProjectionAdjusted07),
		SUM(ProjectionAdjusted08),
		SUM(ProjectionAdjusted09),
		SUM(ProjectionAdjusted10),
		SUM(ProjectionAdjusted11),
		SUM(ProjectionAdjusted12),

		SUM(TargetAdjustedNetReimbursement01),
		SUM(TargetAdjustedNetReimbursement02),
		SUM(TargetAdjustedNetReimbursement03),
		SUM(TargetAdjustedNetReimbursement04),
		SUM(TargetAdjustedNetReimbursement05),
		SUM(TargetAdjustedNetReimbursement06),
		SUM(TargetAdjustedNetReimbursement07),
		SUM(TargetAdjustedNetReimbursement08),
		SUM(TargetAdjustedNetReimbursement09),
		SUM(TargetAdjustedNetReimbursement10),
		SUM(TargetAdjustedNetReimbursement11),
		SUM(TargetAdjustedNetReimbursement12),

		SUM(BudgetAdjustedNetReimbursement01),
		SUM(BudgetAdjustedNetReimbursement02),
		SUM(BudgetAdjustedNetReimbursement03),
		SUM(BudgetAdjustedNetReimbursement04),
		SUM(BudgetAdjustedNetReimbursement05),
		SUM(BudgetAdjustedNetReimbursement06),
		SUM(BudgetAdjustedNetReimbursement07),
		SUM(BudgetAdjustedNetReimbursement08),
		SUM(BudgetAdjustedNetReimbursement09),
		SUM(BudgetAdjustedNetReimbursement10),
		SUM(BudgetAdjustedNetReimbursement11),
		SUM(BudgetAdjustedNetReimbursement12),

		SUM(ProjectionAdjustedNetReimbursement01),
		SUM(ProjectionAdjustedNetReimbursement02),
		SUM(ProjectionAdjustedNetReimbursement03),
		SUM(ProjectionAdjustedNetReimbursement04),
		SUM(ProjectionAdjustedNetReimbursement05),
		SUM(ProjectionAdjustedNetReimbursement06),
		SUM(ProjectionAdjustedNetReimbursement07),
		SUM(ProjectionAdjustedNetReimbursement08),
		SUM(ProjectionAdjustedNetReimbursement09),
		SUM(ProjectionAdjustedNetReimbursement10),
		SUM(ProjectionAdjustedNetReimbursement11),
		SUM(ProjectionAdjustedNetReimbursement12)
	FROM fp.ReimbursementGeneralLedger rgl
	INNER JOIN #uniquePayorGroups upg
		ON rgl.PayorGroupID = upg.PayorGroupID
		AND rgl.EntityID = upg.EntityID
		AND rgl.PatientClassID = upg.PatientClassID
	WHERE
		rgl.BudgetConfigID = @BudgetConfigID
		AND rgl.EntityGroupConfigID = @EntityConfigID
	GROUP BY 
		upg.PayorGroupID,
		upg.EntityID,
		upg.PatientClassID

	--------------------------------------------------------------
	--Do allocation calculation
	--DeductionsXX = RevenueXX - NetReimbursementXX
	--------------------------------------------------------------
	INSERT INTO #tmpConAllowanceCalc(BudgetConfigID, PayorGroupID, EntityID, PatientClassID,
		TargetConAllowance01, TargetConAllowance02, TargetConAllowance03, TargetConAllowance04,
		TargetConAllowance05, TargetConAllowance06, TargetConAllowance07, TargetConAllowance08,
		TargetConAllowance09, TargetConAllowance10, TargetConAllowance11, TargetConAllowance12,
		BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04,
		BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08,
		BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12,
		ProjectionConAllowance01, ProjectionConAllowance02, ProjectionConAllowance03, ProjectionConAllowance04,
		ProjectionConAllowance05, ProjectionConAllowance06, ProjectionConAllowance07, ProjectionConAllowance08,
		ProjectionConAllowance09, ProjectionConAllowance10, ProjectionConAllowance11, ProjectionConAllowance12)
	SELECT 
		tr.BudgetConfigID,
		tr.PayorGroupID,
		tr.EntityID,
		tr.PatientClassID,
		ISNULL(tr.TargetAdjusted01,0) - ISNULL(tr.TargetAdjustedNetReimbursement01,0) AS TargetConAllowance01,
		ISNULL(tr.TargetAdjusted02,0) - ISNULL(tr.TargetAdjustedNetReimbursement02,0) AS TargetConAllowance02,
		ISNULL(tr.TargetAdjusted03,0) - ISNULL(tr.TargetAdjustedNetReimbursement03,0) AS TargetConAllowance03,
		ISNULL(tr.TargetAdjusted04,0) - ISNULL(tr.TargetAdjustedNetReimbursement04,0) AS TargetConAllowance04,
		ISNULL(tr.TargetAdjusted05,0) - ISNULL(tr.TargetAdjustedNetReimbursement05,0) AS TargetConAllowance05,
		ISNULL(tr.TargetAdjusted06,0) - ISNULL(tr.TargetAdjustedNetReimbursement06,0) AS TargetConAllowance06,
		ISNULL(tr.TargetAdjusted07,0) - ISNULL(tr.TargetAdjustedNetReimbursement07,0) AS TargetConAllowance07,
		ISNULL(tr.TargetAdjusted08,0) - ISNULL(tr.TargetAdjustedNetReimbursement08,0) AS TargetConAllowance08,
		ISNULL(tr.TargetAdjusted09,0) - ISNULL(tr.TargetAdjustedNetReimbursement09,0) AS TargetConAllowance09,
		ISNULL(tr.TargetAdjusted10,0) - ISNULL(tr.TargetAdjustedNetReimbursement10,0) AS TargetConAllowance10,
		ISNULL(tr.TargetAdjusted11,0) - ISNULL(tr.TargetAdjustedNetReimbursement11,0) AS TargetConAllowance11,
		ISNULL(tr.TargetAdjusted12,0) - ISNULL(tr.TargetAdjustedNetReimbursement12,0) AS TargetConAllowance12,

		ISNULL(tr.BudgetAdjusted01,0) - ISNULL(tr.BudgetAdjustedNetReimbursement01,0) AS BudgetConAllowance01,
		ISNULL(tr.BudgetAdjusted02,0) - ISNULL(tr.BudgetAdjustedNetReimbursement02,0) AS BudgetConAllowance02,
		ISNULL(tr.BudgetAdjusted03,0) - ISNULL(tr.BudgetAdjustedNetReimbursement03,0) AS BudgetConAllowance03,
		ISNULL(tr.BudgetAdjusted04,0) - ISNULL(tr.BudgetAdjustedNetReimbursement04,0) AS BudgetConAllowance04,
		ISNULL(tr.BudgetAdjusted05,0) - ISNULL(tr.BudgetAdjustedNetReimbursement05,0) AS BudgetConAllowance05,
		ISNULL(tr.BudgetAdjusted06,0) - ISNULL(tr.BudgetAdjustedNetReimbursement06,0) AS BudgetConAllowance06,
		ISNULL(tr.BudgetAdjusted07,0) - ISNULL(tr.BudgetAdjustedNetReimbursement07,0) AS BudgetConAllowance07,
		ISNULL(tr.BudgetAdjusted08,0) - ISNULL(tr.BudgetAdjustedNetReimbursement08,0) AS BudgetConAllowance08,
		ISNULL(tr.BudgetAdjusted09,0) - ISNULL(tr.BudgetAdjustedNetReimbursement09,0) AS BudgetConAllowance09,
		ISNULL(tr.BudgetAdjusted10,0) - ISNULL(tr.BudgetAdjustedNetReimbursement10,0) AS BudgetConAllowance10,
		ISNULL(tr.BudgetAdjusted11,0) - ISNULL(tr.BudgetAdjustedNetReimbursement11,0) AS BudgetConAllowance11,
		ISNULL(tr.BudgetAdjusted12,0) - ISNULL(tr.BudgetAdjustedNetReimbursement12,0) AS BudgetConAllowance12,

		ISNULL(tr.ProjectionAdjusted01,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement01,0) AS ProjectionConAllowance01,
		ISNULL(tr.ProjectionAdjusted02,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement02,0) AS ProjectionConAllowance02,
		ISNULL(tr.ProjectionAdjusted03,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement03,0) AS ProjectionConAllowance03,
		ISNULL(tr.ProjectionAdjusted04,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement04,0) AS ProjectionConAllowance04,
		ISNULL(tr.ProjectionAdjusted05,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement05,0) AS ProjectionConAllowance05,
		ISNULL(tr.ProjectionAdjusted06,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement06,0) AS ProjectionConAllowance06,
		ISNULL(tr.ProjectionAdjusted07,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement07,0) AS ProjectionConAllowance07,
		ISNULL(tr.ProjectionAdjusted08,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement08,0) AS ProjectionConAllowance08,
		ISNULL(tr.ProjectionAdjusted09,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement09,0) AS ProjectionConAllowance09,
		ISNULL(tr.ProjectionAdjusted10,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement10,0) AS ProjectionConAllowance10,
		ISNULL(tr.ProjectionAdjusted11,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement11,0) AS ProjectionConAllowance11,
		ISNULL(tr.ProjectionAdjusted12,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement12,0) AS ProjectionConAllowance12
	FROM #tmpReimbursementGL tr

	--------------------------------------------------------------
	--Insert into temp table
	--Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL
	--------------------------------------------------------------
	SELECT
		ca.BudgetAllocationPercent,
		ca.ProjectionAllocationPercent,
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted01 END) AS TargetAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted02 END) AS TargetAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted03 END) AS TargetAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted04 END) AS TargetAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted05 END) AS TargetAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted06 END) AS TargetAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted07 END) AS TargetAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted08 END) AS TargetAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted09 END) AS TargetAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted10 END) AS TargetAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted11 END) AS TargetAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted12 END) AS TargetAllocatedAmount12,

		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted01 END) AS BudgetAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted02 END) AS BudgetAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted03 END) AS BudgetAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted04 END) AS BudgetAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted05 END) AS BudgetAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted06 END) AS BudgetAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted07 END) AS BudgetAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted08 END) AS BudgetAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted09 END) AS BudgetAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted10 END) AS BudgetAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted11 END) AS BudgetAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted12 END) AS BudgetAllocatedAmount12,

		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE calc.ProjectionConAllowance01 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE calc.ProjectionConAllowance02 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE calc.ProjectionConAllowance03 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END 																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE calc.ProjectionConAllowance04 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE calc.ProjectionConAllowance05 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE calc.ProjectionConAllowance06 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE calc.ProjectionConAllowance07 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE calc.ProjectionConAllowance08 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE calc.ProjectionConAllowance09 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE calc.ProjectionConAllowance10 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE calc.ProjectionConAllowance11 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE calc.ProjectionConAllowance12 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount12
	INTO #tempInsert
	FROM fp.GeneralLedger gl
	INNER JOIN #contractualAllowances ca 
		ON ca.DepartmentID = gl.DepartmentID
		AND ca.AccountID = gl.AccountID
	INNER JOIN #tmpConAllowanceCalc calc
		ON ca.PayorGroupID = calc.PayorGroupID
		AND ca.EntityID = calc.EntityID
		AND ca.PatientClassID = calc.PatientClassID
	WHERE gl.APEModelSectionID = 4
		AND gl.BudgetConfigID = @BudgetConfigID
		AND gl.EntityGroupConfigID = @EntityConfigID
	GROUP BY 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		ca.BudgetAllocationPercent,
		ca.ProjectionAllocationPercent

	--------------------------------------------------------------
	--Update 
	--------------------------------------------------------------
	IF (@IsDebug = 1)
	BEGIN
		SELECT * FROM #tempInsert
	END ELSE BEGIN

		--------------------------------------------------------------
		--Update Target/Budget where BudgetAllocationPercent <> 0 
		--------------------------------------------------------------
		UPDATE gl
		SET
			TargetLockFlag = 1,
			TargetLockType = 3,
			TargetAdjusted01 = ti.TargetAllocatedAmount01,
			TargetAdjusted02 = ti.TargetAllocatedAmount02,
			TargetAdjusted03 = ti.TargetAllocatedAmount03,
			TargetAdjusted04 = ti.TargetAllocatedAmount04,
			TargetAdjusted05 = ti.TargetAllocatedAmount05,
			TargetAdjusted06 = ti.TargetAllocatedAmount06,
			TargetAdjusted07 = ti.TargetAllocatedAmount07,
			TargetAdjusted08 = ti.TargetAllocatedAmount08,
			TargetAdjusted09 = ti.TargetAllocatedAmount09,
			TargetAdjusted10 = ti.TargetAllocatedAmount10,
			TargetAdjusted11 = ti.TargetAllocatedAmount11,
			TargetAdjusted12 = ti.TargetAllocatedAmount12,

			BudgetLockFlag = 1,
			BudgetLockType = 3,
			BudgetAdjusted01 = ti.BudgetAllocatedAmount01,
			BudgetAdjusted02 = ti.BudgetAllocatedAmount02,
			BudgetAdjusted03 = ti.BudgetAllocatedAmount03,
			BudgetAdjusted04 = ti.BudgetAllocatedAmount04,
			BudgetAdjusted05 = ti.BudgetAllocatedAmount05,
			BudgetAdjusted06 = ti.BudgetAllocatedAmount06,
			BudgetAdjusted07 = ti.BudgetAllocatedAmount07,
			BudgetAdjusted08 = ti.BudgetAllocatedAmount08,
			BudgetAdjusted09 = ti.BudgetAllocatedAmount09,
			BudgetAdjusted10 = ti.BudgetAllocatedAmount10,
			BudgetAdjusted11 = ti.BudgetAllocatedAmount11,
			BudgetAdjusted12 = ti.BudgetAllocatedAmount12
		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID
			AND gl.VariabilityID = ti.VariabilityID
		WHERE ti.BudgetAllocationPercent <> 0 
			AND gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID

		--------------------------------------------------------------
		--Update Projection where ProjectionAllocationPercent <> 0 
		--------------------------------------------------------------
		UPDATE gl
		SET
			ProjectionLockFlag = 1,
			ProjectionLockType = 3,
			ProjectionAdjusted01 = ti.ProjectionAllocatedAmount01,
			ProjectionAdjusted02 = ti.ProjectionAllocatedAmount02,
			ProjectionAdjusted03 = ti.ProjectionAllocatedAmount03,
			ProjectionAdjusted04 = ti.ProjectionAllocatedAmount04,
			ProjectionAdjusted05 = ti.ProjectionAllocatedAmount05,
			ProjectionAdjusted06 = ti.ProjectionAllocatedAmount06,
			ProjectionAdjusted07 = ti.ProjectionAllocatedAmount07,
			ProjectionAdjusted08 = ti.ProjectionAllocatedAmount08,
			ProjectionAdjusted09 = ti.ProjectionAllocatedAmount09,
			ProjectionAdjusted10 = ti.ProjectionAllocatedAmount10,
			ProjectionAdjusted11 = ti.ProjectionAllocatedAmount11,
			ProjectionAdjusted12 = ti.ProjectionAllocatedAmount12
		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID
			AND gl.VariabilityID = ti.VariabilityID
		WHERE ti.ProjectionAllocationPercent <> 0 
			AND gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID
	END	
END
GO


---------------------------------------------

-- fp.procReimbursementGLToGLCrosswalk_Initial
CREATE     PROCEDURE [fp].[procReimbursementGLToGLCrosswalk_Initial]
	@BudgetConfigID INT,
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@EntityConfigID INT,	
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
	
AS 
BEGIN

	/**************************************************************
	** Change History	
	** CID Date 	   Author	WI 		   Description
	** 1   2023-08-07  AO 		JAZZ-57673 Initial
	*************************************************************/

	IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances
	IF OBJECT_ID('tempdb..#tmpReimbursementGL') IS NOT NULL DROP TABLE #tmpReimbursementGL
	IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc
	IF OBJECT_ID('tempdb..#uniquePayorGroups') IS NOT NULL DROP TABLE #uniquePayorGroups	
	IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert	

	CREATE TABLE #tmpReimbursementGL (
		BudgetConfigID INT,
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,

		InitialBudget01 DECIMAL (19,8),
		InitialBudget02 DECIMAL (19,8),
		InitialBudget03 DECIMAL (19,8),
		InitialBudget04 DECIMAL (19,8),
		InitialBudget05 DECIMAL (19,8),
		InitialBudget06 DECIMAL (19,8),
		InitialBudget07 DECIMAL (19,8),
		InitialBudget08 DECIMAL (19,8),
		InitialBudget09 DECIMAL (19,8),
		InitialBudget10 DECIMAL (19,8),
		InitialBudget11 DECIMAL (19,8),
		InitialBudget12 DECIMAL (19,8),

		InitialProjection01 DECIMAL (19,8),
		InitialProjection02 DECIMAL (19,8),
		InitialProjection03 DECIMAL (19,8),
		InitialProjection04 DECIMAL (19,8),
		InitialProjection05 DECIMAL (19,8),
		InitialProjection06 DECIMAL (19,8),
		InitialProjection07 DECIMAL (19,8),
		InitialProjection08 DECIMAL (19,8),
		InitialProjection09 DECIMAL (19,8),
		InitialProjection10 DECIMAL (19,8),
		InitialProjection11 DECIMAL (19,8),
		InitialProjection12 DECIMAL (19,8),

		InitialBudgetNetReimbursement01 DECIMAL (19,8),
		InitialBudgetNetReimbursement02 DECIMAL (19,8),
		InitialBudgetNetReimbursement03 DECIMAL (19,8),
		InitialBudgetNetReimbursement04 DECIMAL (19,8),
		InitialBudgetNetReimbursement05 DECIMAL (19,8),
		InitialBudgetNetReimbursement06 DECIMAL (19,8),
		InitialBudgetNetReimbursement07 DECIMAL (19,8),
		InitialBudgetNetReimbursement08 DECIMAL (19,8),
		InitialBudgetNetReimbursement09 DECIMAL (19,8),
		InitialBudgetNetReimbursement10 DECIMAL (19,8),
		InitialBudgetNetReimbursement11 DECIMAL (19,8),
		InitialBudgetNetReimbursement12 DECIMAL (19,8),

		InitialProjectionNetReimbursement01 DECIMAL (19,8),
		InitialProjectionNetReimbursement02 DECIMAL (19,8),
		InitialProjectionNetReimbursement03 DECIMAL (19,8),
		InitialProjectionNetReimbursement04 DECIMAL (19,8),
		InitialProjectionNetReimbursement05 DECIMAL (19,8),
		InitialProjectionNetReimbursement06 DECIMAL (19,8),
		InitialProjectionNetReimbursement07 DECIMAL (19,8),
		InitialProjectionNetReimbursement08 DECIMAL (19,8),
		InitialProjectionNetReimbursement09 DECIMAL (19,8),
		InitialProjectionNetReimbursement10 DECIMAL (19,8),
		InitialProjectionNetReimbursement11 DECIMAL (19,8),
		InitialProjectionNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpConAllowanceCalc (
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetConAllowance01 DECIMAL (19,8),
		BudgetConAllowance02 DECIMAL (19,8),
		BudgetConAllowance03 DECIMAL (19,8),
		BudgetConAllowance04 DECIMAL (19,8),
		BudgetConAllowance05 DECIMAL (19,8),
		BudgetConAllowance06 DECIMAL (19,8),
		BudgetConAllowance07 DECIMAL (19,8),
		BudgetConAllowance08 DECIMAL (19,8),
		BudgetConAllowance09 DECIMAL (19,8),
		BudgetConAllowance10 DECIMAL (19,8),
		BudgetConAllowance11 DECIMAL (19,8),
		BudgetConAllowance12 DECIMAL (19,8),

		ProjectionConAllowance01 DECIMAL (19,8),
		ProjectionConAllowance02 DECIMAL (19,8),
		ProjectionConAllowance03 DECIMAL (19,8),
		ProjectionConAllowance04 DECIMAL (19,8),
		ProjectionConAllowance05 DECIMAL (19,8),
		ProjectionConAllowance06 DECIMAL (19,8),
		ProjectionConAllowance07 DECIMAL (19,8),
		ProjectionConAllowance08 DECIMAL (19,8),
		ProjectionConAllowance09 DECIMAL (19,8),
		ProjectionConAllowance10 DECIMAL (19,8),
		ProjectionConAllowance11 DECIMAL (19,8),
		ProjectionConAllowance12 DECIMAL (19,8)
	)

	--------------------------------------------------------------
	--Get reimbursement contractual allowances config for given budget config
	--------------------------------------------------------------
	SELECT
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID,
		sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent,
		sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent
	INTO #contractualAllowances
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID
	INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID

	SELECT
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID
	INTO #uniquePayorGroups
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID
	INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID

	--------------------------------------------------------------
	--Get reimbursement charge data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementGL (PayorGroupID, EntityID, PatientClassID, 
		InitialBudget01, InitialBudget02, InitialBudget03,InitialBudget04, InitialBudget05, InitialBudget06,
		InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
		InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06,
		InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
		InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04,
		InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08,
		InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12,
		InitialProjectionNetReimbursement01, InitialProjectionNetReimbursement02, InitialProjectionNetReimbursement03, InitialProjectionNetReimbursement04,
		InitialProjectionNetReimbursement05, InitialProjectionNetReimbursement06, InitialProjectionNetReimbursement07, InitialProjectionNetReimbursement08,
		InitialProjectionNetReimbursement09, InitialProjectionNetReimbursement10, InitialProjectionNetReimbursement11, InitialProjectionNetReimbursement12)

	SELECT 
		upg.PayorGroupID,
		upg.EntityID,
		upg.PatientClassID,

		SUM(InitialBudget01),
		SUM(InitialBudget02),
		SUM(InitialBudget03),
		SUM(InitialBudget04),
		SUM(InitialBudget05),
		SUM(InitialBudget06),
		SUM(InitialBudget07),
		SUM(InitialBudget08),
		SUM(InitialBudget09),
		SUM(InitialBudget10),
		SUM(InitialBudget11),
		SUM(InitialBudget12),

		SUM(InitialProjection01),
		SUM(InitialProjection02),
		SUM(InitialProjection03),
		SUM(InitialProjection04),
		SUM(InitialProjection05),
		SUM(InitialProjection06),
		SUM(InitialProjection07),
		SUM(InitialProjection08),
		SUM(InitialProjection09),
		SUM(InitialProjection10),
		SUM(InitialProjection11),
		SUM(InitialProjection12),

		SUM(InitialBudgetNetReimbursement01),
		SUM(InitialBudgetNetReimbursement02),
		SUM(InitialBudgetNetReimbursement03),
		SUM(InitialBudgetNetReimbursement04),
		SUM(InitialBudgetNetReimbursement05),
		SUM(InitialBudgetNetReimbursement06),
		SUM(InitialBudgetNetReimbursement07),
		SUM(InitialBudgetNetReimbursement08),
		SUM(InitialBudgetNetReimbursement09),
		SUM(InitialBudgetNetReimbursement10),
		SUM(InitialBudgetNetReimbursement11),
		SUM(InitialBudgetNetReimbursement12),

		SUM(InitialProjectionNetReimbursement01),
		SUM(InitialProjectionNetReimbursement02),
		SUM(InitialProjectionNetReimbursement03),
		SUM(InitialProjectionNetReimbursement04),
		SUM(InitialProjectionNetReimbursement05),
		SUM(InitialProjectionNetReimbursement06),
		SUM(InitialProjectionNetReimbursement07),
		SUM(InitialProjectionNetReimbursement08),
		SUM(InitialProjectionNetReimbursement09),
		SUM(InitialProjectionNetReimbursement10),
		SUM(InitialProjectionNetReimbursement11),
		SUM(InitialProjectionNetReimbursement12)
	FROM fp.ReimbursementGeneralLedger rgl
	INNER JOIN #uniquePayorGroups upg
		ON rgl.PayorGroupID = upg.PayorGroupID
		AND rgl.EntityID = upg.EntityID
		AND rgl.PatientClassID = upg.PatientClassID
	WHERE rgl.BudgetConfigID = @BudgetConfigID
		AND rgl.EntityGroupConfigID = @EntityConfigID
	GROUP BY 
		upg.PayorGroupID,
		upg.EntityID,
		upg.PatientClassID

	--------------------------------------------------------------
	--Do allocation calculation
	--DeductionsXX = RevenueXX - NetReimbursementXX
	--------------------------------------------------------------
	INSERT INTO #tmpConAllowanceCalc(PayorGroupID, EntityID, PatientClassID,
		BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04,
		BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08,
		BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12,
		ProjectionConAllowance01, ProjectionConAllowance02, ProjectionConAllowance03, ProjectionConAllowance04,
		ProjectionConAllowance05, ProjectionConAllowance06, ProjectionConAllowance07, ProjectionConAllowance08,
		ProjectionConAllowance09, ProjectionConAllowance10, ProjectionConAllowance11, ProjectionConAllowance12)
	SELECT 
		tr.PayorGroupID,
		tr.EntityID,
		tr.PatientClassID,

		ISNULL(tr.InitialBudget01,0) - ISNULL(tr.InitialBudgetNetReimbursement01,0) AS BudgetConAllowance01,
		ISNULL(tr.InitialBudget02,0) - ISNULL(tr.InitialBudgetNetReimbursement02,0) AS BudgetConAllowance02,
		ISNULL(tr.InitialBudget03,0) - ISNULL(tr.InitialBudgetNetReimbursement03,0) AS BudgetConAllowance03,
		ISNULL(tr.InitialBudget04,0) - ISNULL(tr.InitialBudgetNetReimbursement04,0) AS BudgetConAllowance04,
		ISNULL(tr.InitialBudget05,0) - ISNULL(tr.InitialBudgetNetReimbursement05,0) AS BudgetConAllowance05,
		ISNULL(tr.InitialBudget06,0) - ISNULL(tr.InitialBudgetNetReimbursement06,0) AS BudgetConAllowance06,
		ISNULL(tr.InitialBudget07,0) - ISNULL(tr.InitialBudgetNetReimbursement07,0) AS BudgetConAllowance07,
		ISNULL(tr.InitialBudget08,0) - ISNULL(tr.InitialBudgetNetReimbursement08,0) AS BudgetConAllowance08,
		ISNULL(tr.InitialBudget09,0) - ISNULL(tr.InitialBudgetNetReimbursement09,0) AS BudgetConAllowance09,
		ISNULL(tr.InitialBudget10,0) - ISNULL(tr.InitialBudgetNetReimbursement10,0) AS BudgetConAllowance10,
		ISNULL(tr.InitialBudget11,0) - ISNULL(tr.InitialBudgetNetReimbursement11,0) AS BudgetConAllowance11,
		ISNULL(tr.InitialBudget12,0) - ISNULL(tr.InitialBudgetNetReimbursement12,0) AS BudgetConAllowance12,

		ISNULL(tr.InitialProjection01,0) - ISNULL(tr.InitialProjectionNetReimbursement01,0) AS ProjectionConAllowance01,
		ISNULL(tr.InitialProjection02,0) - ISNULL(tr.InitialProjectionNetReimbursement02,0) AS ProjectionConAllowance02,
		ISNULL(tr.InitialProjection03,0) - ISNULL(tr.InitialProjectionNetReimbursement03,0) AS ProjectionConAllowance03,
		ISNULL(tr.InitialProjection04,0) - ISNULL(tr.InitialProjectionNetReimbursement04,0) AS ProjectionConAllowance04,
		ISNULL(tr.InitialProjection05,0) - ISNULL(tr.InitialProjectionNetReimbursement05,0) AS ProjectionConAllowance05,
		ISNULL(tr.InitialProjection06,0) - ISNULL(tr.InitialProjectionNetReimbursement06,0) AS ProjectionConAllowance06,
		ISNULL(tr.InitialProjection07,0) - ISNULL(tr.InitialProjectionNetReimbursement07,0) AS ProjectionConAllowance07,
		ISNULL(tr.InitialProjection08,0) - ISNULL(tr.InitialProjectionNetReimbursement08,0) AS ProjectionConAllowance08,
		ISNULL(tr.InitialProjection09,0) - ISNULL(tr.InitialProjectionNetReimbursement09,0) AS ProjectionConAllowance09,
		ISNULL(tr.InitialProjection10,0) - ISNULL(tr.InitialProjectionNetReimbursement10,0) AS ProjectionConAllowance10,
		ISNULL(tr.InitialProjection11,0) - ISNULL(tr.InitialProjectionNetReimbursement11,0) AS ProjectionConAllowance11,
		ISNULL(tr.InitialProjection12,0) - ISNULL(tr.InitialProjectionNetReimbursement12,0) AS ProjectionConAllowance12
	FROM #tmpReimbursementGL tr

	--------------------------------------------------------------
	--Insert into temp table
	--Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL
	--------------------------------------------------------------
	SELECT
		ca.BudgetAllocationPercent,
		ca.ProjectionAllocationPercent,
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.InitialBudget01 END) AS BudgetAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.InitialBudget02 END) AS BudgetAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.InitialBudget03 END) AS BudgetAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.InitialBudget04 END) AS BudgetAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.InitialBudget05 END) AS BudgetAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.InitialBudget06 END) AS BudgetAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.InitialBudget07 END) AS BudgetAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.InitialBudget08 END) AS BudgetAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.InitialBudget09 END) AS BudgetAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.InitialBudget10 END) AS BudgetAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.InitialBudget11 END) AS BudgetAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.InitialBudget12 END) AS BudgetAllocatedAmount12,

		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.InitialProjection01 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.InitialProjection01 ELSE calc.ProjectionConAllowance01 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.InitialProjection02 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.InitialProjection02 ELSE calc.ProjectionConAllowance02 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.InitialProjection03 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.InitialProjection03 ELSE calc.ProjectionConAllowance03 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.InitialProjection04 ELSE 0 END 																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.InitialProjection04 ELSE calc.ProjectionConAllowance04 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.InitialProjection05 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.InitialProjection05 ELSE calc.ProjectionConAllowance05 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.InitialProjection06 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.InitialProjection06 ELSE calc.ProjectionConAllowance06 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.InitialProjection07 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.InitialProjection07 ELSE calc.ProjectionConAllowance07 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.InitialProjection08 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.InitialProjection08 ELSE calc.ProjectionConAllowance08 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.InitialProjection09 ELSE 0 END																				
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.InitialProjection09 ELSE calc.ProjectionConAllowance09 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE calc.ProjectionConAllowance10 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE calc.ProjectionConAllowance11 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE 0 END
				 WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE calc.ProjectionConAllowance12 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount12
	INTO #tempInsert
	FROM fp.GeneralLedger gl
	INNER JOIN #contractualAllowances ca 
		ON ca.DepartmentID = gl.DepartmentID
		AND ca.AccountID = gl.AccountID
	INNER JOIN #tmpConAllowanceCalc calc
		ON ca.PayorGroupID = calc.PayorGroupID
		AND ca.EntityID = calc.EntityID
		AND ca.PatientClassID = calc.PatientClassID
	WHERE gl.APEModelSectionID = 4
		AND gl.BudgetConfigID = @BudgetConfigID
		AND gl.EntityGroupConfigID = @EntityConfigID
	GROUP BY 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		ca.BudgetAllocationPercent,
		ca.ProjectionAllocationPercent


	--------------------------------------------------------------
	--Update initials
	--------------------------------------------------------------
	IF (@IsDebug = 1)
	BEGIN
		SELECT * FROM #tempInsert		
	END ELSE BEGIN

		--------------------------------------------------------------
		--Update Budget where BudgetAllocationPercent <> 0 
		--------------------------------------------------------------
		UPDATE gl 
		SET
			InitialBudget01 = ti.BudgetAllocatedAmount01,
			InitialBudget02 = ti.BudgetAllocatedAmount02,
			InitialBudget03 = ti.BudgetAllocatedAmount03,
			InitialBudget04 = ti.BudgetAllocatedAmount04,
			InitialBudget05 = ti.BudgetAllocatedAmount05,
			InitialBudget06 = ti.BudgetAllocatedAmount06,
			InitialBudget07 = ti.BudgetAllocatedAmount07,
			InitialBudget08 = ti.BudgetAllocatedAmount08,
			InitialBudget09 = ti.BudgetAllocatedAmount09,
			InitialBudget10 = ti.BudgetAllocatedAmount10,
			InitialBudget11 = ti.BudgetAllocatedAmount11,
			InitialBudget12 = ti.BudgetAllocatedAmount12,

			SampledBudget01 = ti.BudgetAllocatedAmount01,
			SampledBudget02 = ti.BudgetAllocatedAmount02,
			SampledBudget03 = ti.BudgetAllocatedAmount03,
			SampledBudget04 = ti.BudgetAllocatedAmount04,
			SampledBudget05 = ti.BudgetAllocatedAmount05,
			SampledBudget06 = ti.BudgetAllocatedAmount06,
			SampledBudget07 = ti.BudgetAllocatedAmount07,
			SampledBudget08 = ti.BudgetAllocatedAmount08,
			SampledBudget09 = ti.BudgetAllocatedAmount09,
			SampledBudget10 = ti.BudgetAllocatedAmount10,
			SampledBudget11 = ti.BudgetAllocatedAmount11,
			SampledBudget12 = ti.BudgetAllocatedAmount12

		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID		
			AND gl.VariabilityID = ti.VariabilityID
		WHERE ti.BudgetAllocationPercent <> 0 
			AND gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID

		--------------------------------------------------------------
		--Update Projection where ProjectionAllocationPercent <> 0 
		--------------------------------------------------------------
		UPDATE gl 
		SET
			InitialProjection01 = ti.ProjectionAllocatedAmount01,
			InitialProjection02 = ti.ProjectionAllocatedAmount02,
			InitialProjection03 = ti.ProjectionAllocatedAmount03,
			InitialProjection04 = ti.ProjectionAllocatedAmount04,
			InitialProjection05 = ti.ProjectionAllocatedAmount05,
			InitialProjection06 = ti.ProjectionAllocatedAmount06,
			InitialProjection07 = ti.ProjectionAllocatedAmount07,
			InitialProjection08 = ti.ProjectionAllocatedAmount08,
			InitialProjection09 = ti.ProjectionAllocatedAmount09,
			InitialProjection10 = ti.ProjectionAllocatedAmount10,
			InitialProjection11 = ti.ProjectionAllocatedAmount11,
			InitialProjection12 = ti.ProjectionAllocatedAmount12,

			SampledProjection01 = ti.ProjectionAllocatedAmount01,
			SampledProjection02 = ti.ProjectionAllocatedAmount02,
			SampledProjection03 = ti.ProjectionAllocatedAmount03,
			SampledProjection04 = ti.ProjectionAllocatedAmount04,
			SampledProjection05 = ti.ProjectionAllocatedAmount05,
			SampledProjection06 = ti.ProjectionAllocatedAmount06,
			SampledProjection07 = ti.ProjectionAllocatedAmount07,
			SampledProjection08 = ti.ProjectionAllocatedAmount08,
			SampledProjection09 = ti.ProjectionAllocatedAmount09,
			SampledProjection10 = ti.ProjectionAllocatedAmount10,
			SampledProjection11 = ti.ProjectionAllocatedAmount11,
			SampledProjection12 = ti.ProjectionAllocatedAmount12

		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID		
			AND gl.VariabilityID = ti.VariabilityID
		WHERE ti.ProjectionAllocationPercent <> 0 
			AND gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID
	END	
END
GO


---------------------------------------------

-- fp.procReimbursementGeneralLedgerAdjustmentActivityList
CREATE PROCEDURE [fp].[procReimbursementGeneralLedgerAdjustmentActivityList]
	@budgetGUID UNIQUEIDENTIFIER,
	@start INT,
	@end INT,
	@search VARCHAR(MAX),
	@filter VARCHAR(MAX),
	@userGUID UNIQUEIDENTIFIER,
	@isDataSecured BIT,
	@dateTimeFormat VARCHAR(30),
	@userTimeZone VARCHAR(50)
AS
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI			Description
 ** 1 	 2023-07-19  VZ  	 JAZZ-56779	Initial
 ** 2	 2023-09-10	 AO		 JAZZ-59350 Updated filtering by timeClass	
 ** 3	 2023-12-4	 AO		 JAZZ-62691 Added security
 *************************************************************/
BEGIN

	
		
	CREATE TABLE #departmentsSecurity (
		DepartmentID INT NULL,
		EntityID INT NULL
	)	

	CREATE TABLE #securedAdjustments (
		AdjustmentID INT NULL
	)

	SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
	SET @filter = LOWER(NULLIF(@filter, ''))

	----------------------------------------------------------------------
	--Get all adjustments
	----------------------------------------------------------------------

	Select AdjustmentID, GroupingHierarchyJSON, JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
	INTO #adjustments
	FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK)
	WHERE rgla.BudgetConfigGUID = @budgetGUID
	IF @isDataSecured = 1
	BEGIN
		INSERT INTO #departmentsSecurity
		EXEC fp.DepartmentsSecurity_SEL 
			@userGUID = @userGUID,
			@pageName = 'Reimbursement'

		CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

		SELECT	adj.AdjustmentID,
				ahe.ID AS EntityID
		INTO	#adjustmentGroupingHierarchyEntities
		FROM	#adjustments AS adj
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
		GROUP BY adj.AdjustmentID	
				,ahe.ID
		
		INSERT INTO	#securedAdjustments
		SELECT	res.AdjustmentID
		FROM	(
			SELECT	slea.AdjustmentID		
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
			GROUP BY slea.AdjustmentID

			UNION ALL

			SELECT	aghe.AdjustmentID		
			FROM	#adjustmentGroupingHierarchyEntities AS aghe
					JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
			GROUP BY aghe.AdjustmentID

			UNION ALL

			SELECT	adj.AdjustmentID
			FROM	#adjustments AS adj
					JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentID = adj.AdjustmentID
			WHERE   adj.EntityID IS NULL
					AND aghe.EntityID IS NULL
			GROUP BY adj.AdjustmentID
		) AS res

	END
	ELSE 
		BEGIN

			INSERT INTO #securedAdjustments
			SELECT	AdjustmentID
			FROM	#adjustments

		END

	CREATE CLUSTERED INDEX PK_Adjustment ON #securedAdjustments (AdjustmentID)

	----------------------------------------------------------------------
	--Get import adjustments
	----------------------------------------------------------------------

	SELECT iadj.AdjustmentID
	INTO #importAdjustments
	FROM fp.ReimbursementGeneralLedgerAdjustmentImport AS iadj WITH (NOLOCK)
		JOIN #securedAdjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
		LEFT JOIN #departmentsSecurity AS ds ON ds.EntityID = iadj.EntityID
		WHERE ds.EntityID IS NOT NULL
			OR @isDataSecured = 0

	CREATE CLUSTERED INDEX PK_ImportAdjustmen ON #importAdjustments (AdjustmentID)

	----------------------------------------------------------------------
	--Build dto
	----------------------------------------------------------------------

	SELECT * 
	FROM (
		SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, *
		FROM (
			SELECT 
				ROW_NUMBER() OVER (PARTITION BY rgla.AdjustmentID ORDER BY rgla.DateCreatedUtc DESC) AS RowNumber,
				rgla.AdjustmentID,
				rgla.BudgetConfigGUID,
				rgla.Value,
				rgla.AdjustmentFilterJSON,
				rgla.GroupingHierarchyJSON,
				rgla.AdjustedProperty,
				ISNULL(ag.Description, rgla.Comment) AS Comment,
				rgla.AuthorGUID,
				rgla.AuthorFullName,
				rgla.LastModifiedDateUtc,
				rgla.DateCreatedUtc,
				rgla.GroupingGUID,
				rgla.TimeClassID,
				rgla.BudgetPhaseID,
				rgla.ClassificationGroupID,
				rgla.ClassificationCategoryID,
				NULL AS JobCode,
				NULL AS JobCodeCount,
				NULL AS DepartmentCode,
				NULL As DepartmentCount,
				rgla.IsRecordDeleted,
				rgla.IsCarryForward,
				rgla.AdjustmentType
			FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK)
			JOIN #securedAdjustments AS sleas ON sleas.AdjustmentID = rgla.AdjustmentID
			LEFT JOIN (select AdjustmentID FROM #importAdjustments GROUP BY AdjustmentID) AS sai ON sai.AdjustmentID = rgla.AdjustmentID
			LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = rgla.GroupingGUID
			LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = rgla.ClassificationGroupID
			LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID and rgla.ClassificationCategoryID = acc.CategoryID
			LEFT JOIN (
						SELECT nsa.GroupingGUID
						FROM fp.ReimbursementGeneralLedgerAdjustment AS nsa WITH (NOLOCK)
						WHERE nsa.AdjustmentType IN (12, 13, 14) AND nsa.budgetConfigGUID = @budgetGUID
						GROUP BY nsa.GroupingGUID
					) as ra ON ra.GroupingGUID = rgla.GroupingGUID
			WHERE (ra.GroupingGUID IS NULL OR rgla.AdjustmentType IN (12, 13, 14)) AND (@search IS NULL
						OR (
							LOWER(fp.GetAdjustmentType(rgla.AdjustmentType)) LIKE @search ESCAPE '\'
							OR LOWER(fp.GetAdjustmentValue(rgla.Value, rgla.AdjustmentType)) LIKE @search ESCAPE '\'
							OR LOWER(rgla.AuthorFullName) LIKE @search ESCAPE '\'
							OR LOWER(ISNULL(ag.Description, rgla.Comment)) LIKE @search ESCAPE '\'
							OR fp.funcCompareAdjustmentDateTime(rgla.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
							OR fp.funcCompareAdjustmentDateTime(rgla.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
							OR acc.[Name] LIKE @search ESCAPE '\'
							OR acg.[Name] LIKE @search ESCAPE '\'
							OR fp.SearchHierarchyLevel(rgla.AdjustmentFilterJSON, @search) = 1
 						))
				
				AND (@filter IS NULL
					OR fp.GetAdjustmentTimeClassString(rgla.AdjustmentType, rgla.TimeclassID, rgla.BudgetPhaseID) IN (
						SELECT [value] 
						FROM STRING_SPLIT(@filter, ' ')
					)
				)
		) AS res_inner
		WHERE res_inner.RowNumber = 1) AS res
	WHERE res.RowNumber = 1
	ORDER BY res.DateCreatedUtc DESC
END;
GO


---------------------------------------------

-- fp.procReimbursementGeneralLedgerCopyNewItems
CREATE   PROCEDURE [fp].[procReimbursementGeneralLedgerCopyNewItems]
	@SourceBudgetConfigID INT,
	@SourceEntityGroupConfigID INT,
	@BudgetConfigID INT,
	@EntityGroupConfigID INT
AS 
BEGIN

	
INSERT INTO [fp].[ReimbursementGeneralLedger] (BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, AddDate,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
InitialBudgetNetAsPercentOfCharge01, InitialBudgetNetAsPercentOfCharge02, InitialBudgetNetAsPercentOfCharge03, InitialBudgetNetAsPercentOfCharge04, InitialBudgetNetAsPercentOfCharge05, InitialBudgetNetAsPercentOfCharge06, InitialBudgetNetAsPercentOfCharge07, InitialBudgetNetAsPercentOfCharge08, InitialBudgetNetAsPercentOfCharge09, InitialBudgetNetAsPercentOfCharge10, InitialBudgetNetAsPercentOfCharge11, InitialBudgetNetAsPercentOfCharge12,
InitialProjectionNetAsPercentOfCharge01, InitialProjectionNetAsPercentOfCharge02, InitialProjectionNetAsPercentOfCharge03, InitialProjectionNetAsPercentOfCharge04, InitialProjectionNetAsPercentOfCharge05, InitialProjectionNetAsPercentOfCharge06, InitialProjectionNetAsPercentOfCharge07, InitialProjectionNetAsPercentOfCharge08, InitialProjectionNetAsPercentOfCharge09, InitialProjectionNetAsPercentOfCharge10, InitialProjectionNetAsPercentOfCharge11, InitialProjectionNetAsPercentOfCharge12,
IsNew)
SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, AddDate,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
InitialBudgetNetAsPercentOfCharge01, InitialBudgetNetAsPercentOfCharge02, InitialBudgetNetAsPercentOfCharge03, InitialBudgetNetAsPercentOfCharge04, InitialBudgetNetAsPercentOfCharge05, InitialBudgetNetAsPercentOfCharge06, InitialBudgetNetAsPercentOfCharge07, InitialBudgetNetAsPercentOfCharge08, InitialBudgetNetAsPercentOfCharge09, InitialBudgetNetAsPercentOfCharge10, InitialBudgetNetAsPercentOfCharge11, InitialBudgetNetAsPercentOfCharge12,
InitialProjectionNetAsPercentOfCharge01, InitialProjectionNetAsPercentOfCharge02, InitialProjectionNetAsPercentOfCharge03, InitialProjectionNetAsPercentOfCharge04, InitialProjectionNetAsPercentOfCharge05, InitialProjectionNetAsPercentOfCharge06, InitialProjectionNetAsPercentOfCharge07, InitialProjectionNetAsPercentOfCharge08, InitialProjectionNetAsPercentOfCharge09, InitialProjectionNetAsPercentOfCharge10, InitialProjectionNetAsPercentOfCharge11, InitialProjectionNetAsPercentOfCharge12,
IsNew
FROM [fp].[ReimbursementGeneralLedger] 
WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1
END
GO


---------------------------------------------

-- fp.procReimbursementToGLCrosswalk_Budget
CREATE   PROCEDURE [fp].[procReimbursementToGLCrosswalk_Budget]
	@BudgetConfigID INT,
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@EntityConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS 
BEGIN

	/**************************************************************
	** Change History
	
	** CID  Date 		Author  WI 			Description
	** 1	2022-06-21  MD 		JAZZ-37249  Initial
	** 2	2022-08-16  MD 		JAZZ-42139  Update to make work with new dimensionality
	** 3	2023-08-14  MD 		JAZZ-58776  Update for GL restructure
	*************************************************************/

	IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances
	IF OBJECT_ID('tempdb..#tmpReimbursementCharge') IS NOT NULL DROP TABLE #tmpReimbursementCharge
	IF OBJECT_ID('tempdb..#tmpReimbursementEncounter') IS NOT NULL DROP TABLE #tmpReimbursementEncounter
	IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc
	IF OBJECT_ID('tempdb..#uniquePayorGroups') IS NOT NULL DROP TABLE #uniquePayorGroups
	IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert

	CREATE TABLE #tmpReimbursementCharge (
		BudgetConfigID INT,
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetPhaseID TINYINT,
		BudgetChargeDollars01 DECIMAL (19,8),
		BudgetChargeDollars02 DECIMAL (19,8),
		BudgetChargeDollars03 DECIMAL (19,8),
		BudgetChargeDollars04 DECIMAL (19,8),
		BudgetChargeDollars05 DECIMAL (19,8),
		BudgetChargeDollars06 DECIMAL (19,8),
		BudgetChargeDollars07 DECIMAL (19,8),
		BudgetChargeDollars08 DECIMAL (19,8),
		BudgetChargeDollars09 DECIMAL (19,8),
		BudgetChargeDollars10 DECIMAL (19,8),
		BudgetChargeDollars11 DECIMAL (19,8),
		BudgetChargeDollars12 DECIMAL (19,8),
		BudgetNetReimbursement01 DECIMAL (19,8),
		BudgetNetReimbursement02 DECIMAL (19,8),
		BudgetNetReimbursement03 DECIMAL (19,8),
		BudgetNetReimbursement04 DECIMAL (19,8),
		BudgetNetReimbursement05 DECIMAL (19,8),
		BudgetNetReimbursement06 DECIMAL (19,8),
		BudgetNetReimbursement07 DECIMAL (19,8),
		BudgetNetReimbursement08 DECIMAL (19,8),
		BudgetNetReimbursement09 DECIMAL (19,8),
		BudgetNetReimbursement10 DECIMAL (19,8),
		BudgetNetReimbursement11 DECIMAL (19,8),
		BudgetNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpReimbursementEncounter (
		BudgetConfigID INT,
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetPhaseID TINYINT,
		BudgetNetReimbursement01 DECIMAL (19,8),
		BudgetNetReimbursement02 DECIMAL (19,8),
		BudgetNetReimbursement03 DECIMAL (19,8),
		BudgetNetReimbursement04 DECIMAL (19,8),
		BudgetNetReimbursement05 DECIMAL (19,8),
		BudgetNetReimbursement06 DECIMAL (19,8),
		BudgetNetReimbursement07 DECIMAL (19,8),
		BudgetNetReimbursement08 DECIMAL (19,8),
		BudgetNetReimbursement09 DECIMAL (19,8),
		BudgetNetReimbursement10 DECIMAL (19,8),
		BudgetNetReimbursement11 DECIMAL (19,8),
		BudgetNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpConAllowanceCalc (
		BudgetConfigID INT,
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetPhaseID TINYINT,
		BudgetConAllowance01 DECIMAL (19,8),
		BudgetConAllowance02 DECIMAL (19,8),
		BudgetConAllowance03 DECIMAL (19,8),
		BudgetConAllowance04 DECIMAL (19,8),
		BudgetConAllowance05 DECIMAL (19,8),
		BudgetConAllowance06 DECIMAL (19,8),
		BudgetConAllowance07 DECIMAL (19,8),
		BudgetConAllowance08 DECIMAL (19,8),
		BudgetConAllowance09 DECIMAL (19,8),
		BudgetConAllowance10 DECIMAL (19,8),
		BudgetConAllowance11 DECIMAL (19,8),
		BudgetConAllowance12 DECIMAL (19,8)
	)

	--------------------------------------------------------------
	--Get reimbursement contractual allowances config for given budget config
	--------------------------------------------------------------
	SELECT
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID,
		sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent,
		sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent
	INTO #contractualAllowances
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID

	SELECT
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID
	INTO #uniquePayorGroups
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID

	--------------------------------------------------------------
	--Get reimbursement encounter data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementEncounter (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID,
		BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04,
		BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08,
		BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12
	)
	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		freb.BudgetPhaseID,
		sum(freb.AdjustedNetReimbursementValue01),
		sum(freb.AdjustedNetReimbursementValue02),
		sum(freb.AdjustedNetReimbursementValue03),
		sum(freb.AdjustedNetReimbursementValue04),
		sum(freb.AdjustedNetReimbursementValue05),
		sum(freb.AdjustedNetReimbursementValue06),
		sum(freb.AdjustedNetReimbursementValue07),
		sum(freb.AdjustedNetReimbursementValue08),
		sum(freb.AdjustedNetReimbursementValue09),
		sum(freb.AdjustedNetReimbursementValue10),
		sum(freb.AdjustedNetReimbursementValue11),
		sum(freb.AdjustedNetReimbursementValue12)
	FROM fp.FactReimbursementEncounter fre
	INNER JOIN #uniquePayorGroups ca
		ON  fre.PayorGroupID = ca.PayorGroupID
		AND  fre.EntityID = ca.EntityID
		AND  fre.PatientClassID = ca.PatientClassID
	INNER JOIN fp.FactReimbursementEncounterBudget freb
		ON fre.ReimbursementEncounterID = freb.ReimbursementEncounterID
	WHERE
		fre.BudgetConfigID = @BudgetConfigID
		AND fre.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID > 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		freb.BudgetPhaseID

	UNION ALL

	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		0 as PatientClassID,
		freb.BudgetPhaseID,
		sum(freb.AdjustedNetReimbursementValue01),
		sum(freb.AdjustedNetReimbursementValue02),
		sum(freb.AdjustedNetReimbursementValue03),
		sum(freb.AdjustedNetReimbursementValue04),
		sum(freb.AdjustedNetReimbursementValue05),
		sum(freb.AdjustedNetReimbursementValue06),
		sum(freb.AdjustedNetReimbursementValue07),
		sum(freb.AdjustedNetReimbursementValue08),
		sum(freb.AdjustedNetReimbursementValue09),
		sum(freb.AdjustedNetReimbursementValue10),
		sum(freb.AdjustedNetReimbursementValue11),
		sum(freb.AdjustedNetReimbursementValue12)
	FROM fp.FactReimbursementEncounter fre
	INNER JOIN #uniquePayorGroups ca
		ON  fre.PayorGroupID = ca.PayorGroupID
		AND  fre.EntityID = ca.EntityID
	INNER JOIN fp.FactReimbursementEncounterBudget freb
		ON fre.ReimbursementEncounterID = freb.ReimbursementEncounterID
	WHERE
		fre.BudgetConfigID = @BudgetConfigID
		AND fre.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID = 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		freb.BudgetPhaseID

	--------------------------------------------------------------
	--Get reimbursement charge data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementCharge (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID,
		BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04,
		BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08,
		BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12,
		BudgetChargeDollars01, BudgetChargeDollars02, BudgetChargeDollars03, BudgetChargeDollars04,
		BudgetChargeDollars05, BudgetChargeDollars06, BudgetChargeDollars07, BudgetChargeDollars08,
		BudgetChargeDollars09, BudgetChargeDollars10, BudgetChargeDollars11, BudgetChargeDollars12)

	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		frcb.BudgetPhaseID,
		sum(frcb.AdjustedNetReimbursementValue01),
		sum(frcb.AdjustedNetReimbursementValue02),
		sum(frcb.AdjustedNetReimbursementValue03),
		sum(frcb.AdjustedNetReimbursementValue04),
		sum(frcb.AdjustedNetReimbursementValue05),
		sum(frcb.AdjustedNetReimbursementValue06),
		sum(frcb.AdjustedNetReimbursementValue07),
		sum(frcb.AdjustedNetReimbursementValue08),
		sum(frcb.AdjustedNetReimbursementValue09),
		sum(frcb.AdjustedNetReimbursementValue10),
		sum(frcb.AdjustedNetReimbursementValue11),
		sum(frcb.AdjustedNetReimbursementValue12),
		sum(frcb.AdjustedChargeDollars01),
		sum(frcb.AdjustedChargeDollars02),
		sum(frcb.AdjustedChargeDollars03),
		sum(frcb.AdjustedChargeDollars04),
		sum(frcb.AdjustedChargeDollars05),
		sum(frcb.AdjustedChargeDollars06),
		sum(frcb.AdjustedChargeDollars07),
		sum(frcb.AdjustedChargeDollars08),
		sum(frcb.AdjustedChargeDollars09),
		sum(frcb.AdjustedChargeDollars10),
		sum(frcb.AdjustedChargeDollars11),
		sum(frcb.AdjustedChargeDollars12)
	FROM fp.FactReimbursementCharges frc
	INNER JOIN #uniquePayorGroups ca
		ON frc.PayorGroupID = ca.PayorGroupID
		AND frc.EntityID = ca.EntityID
		AND frc.PatientClassID = ca.PatientClassID
	INNER JOIN fp.FactReimbursementChargesBudget frcb
		ON frc.ReimbursementChargesID = frcb.ReimbursementChargesID
	WHERE
		frc.BudgetConfigID = @BudgetConfigID
		AND frc.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID > 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		frcb.BudgetPhaseID

	UNION ALL

	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		0 AS PatientClassID,
		frcb.BudgetPhaseID,
		sum(frcb.AdjustedNetReimbursementValue01),
		sum(frcb.AdjustedNetReimbursementValue02),
		sum(frcb.AdjustedNetReimbursementValue03),
		sum(frcb.AdjustedNetReimbursementValue04),
		sum(frcb.AdjustedNetReimbursementValue05),
		sum(frcb.AdjustedNetReimbursementValue06),
		sum(frcb.AdjustedNetReimbursementValue07),
		sum(frcb.AdjustedNetReimbursementValue08),
		sum(frcb.AdjustedNetReimbursementValue09),
		sum(frcb.AdjustedNetReimbursementValue10),
		sum(frcb.AdjustedNetReimbursementValue11),
		sum(frcb.AdjustedNetReimbursementValue12),
		sum(frcb.AdjustedChargeDollars01),
		sum(frcb.AdjustedChargeDollars02),
		sum(frcb.AdjustedChargeDollars03),
		sum(frcb.AdjustedChargeDollars04),
		sum(frcb.AdjustedChargeDollars05),
		sum(frcb.AdjustedChargeDollars06),
		sum(frcb.AdjustedChargeDollars07),
		sum(frcb.AdjustedChargeDollars08),
		sum(frcb.AdjustedChargeDollars09),
		sum(frcb.AdjustedChargeDollars10),
		sum(frcb.AdjustedChargeDollars11),
		sum(frcb.AdjustedChargeDollars12)
	FROM fp.FactReimbursementCharges frc
	INNER JOIN #uniquePayorGroups ca
		ON frc.PayorGroupID = ca.PayorGroupID
		AND frc.EntityID = ca.EntityID
	INNER JOIN fp.FactReimbursementChargesBudget frcb
		ON frc.ReimbursementChargesID = frcb.ReimbursementChargesID
	WHERE
		frc.BudgetConfigID = @BudgetConfigID
		AND frc.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID = 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		frcb.BudgetPhaseID

	--------------------------------------------------------------
	--Do allocation calculation
	--ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX
	--------------------------------------------------------------
	INSERT INTO #tmpConAllowanceCalc(BudgetConfigID, PayorGroupID, EntityID, PatientClassID, BudgetPhaseID,
		BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04,
		BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08,
		BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12)
	SELECT 
		tc.BudgetConfigID,
		tc.PayorGroupID,
		tc.EntityID,
		tc.PatientClassID,
		tc.BudgetPhaseID,
		ISNULL(tc.BudgetChargeDollars01,0) - ISNULL(tc.BudgetNetReimbursement01,0) - ISNULL(te.BudgetNetReimbursement01,0) AS BudgetConAllowance01,
		ISNULL(tc.BudgetChargeDollars02,0) - ISNULL(tc.BudgetNetReimbursement02,0) - ISNULL(te.BudgetNetReimbursement02,0) AS BudgetConAllowance02,
		ISNULL(tc.BudgetChargeDollars03,0) - ISNULL(tc.BudgetNetReimbursement03,0) - ISNULL(te.BudgetNetReimbursement03,0) AS BudgetConAllowance03,
		ISNULL(tc.BudgetChargeDollars04,0) - ISNULL(tc.BudgetNetReimbursement04,0) - ISNULL(te.BudgetNetReimbursement04,0) AS BudgetConAllowance04,
		ISNULL(tc.BudgetChargeDollars05,0) - ISNULL(tc.BudgetNetReimbursement05,0) - ISNULL(te.BudgetNetReimbursement05,0) AS BudgetConAllowance05,
		ISNULL(tc.BudgetChargeDollars06,0) - ISNULL(tc.BudgetNetReimbursement06,0) - ISNULL(te.BudgetNetReimbursement06,0) AS BudgetConAllowance06,
		ISNULL(tc.BudgetChargeDollars07,0) - ISNULL(tc.BudgetNetReimbursement07,0) - ISNULL(te.BudgetNetReimbursement07,0) AS BudgetConAllowance07,
		ISNULL(tc.BudgetChargeDollars08,0) - ISNULL(tc.BudgetNetReimbursement08,0) - ISNULL(te.BudgetNetReimbursement08,0) AS BudgetConAllowance08,
		ISNULL(tc.BudgetChargeDollars09,0) - ISNULL(tc.BudgetNetReimbursement09,0) - ISNULL(te.BudgetNetReimbursement09,0) AS BudgetConAllowance09,
		ISNULL(tc.BudgetChargeDollars10,0) - ISNULL(tc.BudgetNetReimbursement10,0) - ISNULL(te.BudgetNetReimbursement10,0) AS BudgetConAllowance10,
		ISNULL(tc.BudgetChargeDollars11,0) - ISNULL(tc.BudgetNetReimbursement11,0) - ISNULL(te.BudgetNetReimbursement11,0) AS BudgetConAllowance11,
		ISNULL(tc.BudgetChargeDollars12,0) - ISNULL(tc.BudgetNetReimbursement12,0) - ISNULL(te.BudgetNetReimbursement12,0) AS BudgetConAllowance12
	FROM #tmpReimbursementCharge tc
	FULL JOIN #tmpReimbursementEncounter te
		ON tc.PayorGroupID = te.PayorGroupID
		AND tc.EntityID = te.EntityID
		AND tc.PatientClassID = te.PatientClassID
		AND tc.BudgetPhaseID = te.BudgetPhaseID

	--------------------------------------------------------------
	--Insert into temp table
	--Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL
	--------------------------------------------------------------
	SELECT
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted01 END) AS TargetAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted02 END) AS TargetAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted03 END) AS TargetAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted04 END) AS TargetAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted05 END) AS TargetAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted06 END) AS TargetAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted07 END) AS TargetAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted08 END) AS TargetAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted09 END) AS TargetAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted10 END) AS TargetAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted11 END) AS TargetAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted12 END) AS TargetAllocatedAmount12,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted01 END) AS BudgetAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted02 END) AS BudgetAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted03 END) AS BudgetAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted04 END) AS BudgetAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted05 END) AS BudgetAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted06 END) AS BudgetAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted07 END) AS BudgetAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted08 END) AS BudgetAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted09 END) AS BudgetAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted10 END) AS BudgetAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted11 END) AS BudgetAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted12 END) AS BudgetAllocatedAmount12
	INTO #tempInsert
	FROM fp.GeneralLedger gl
	INNER JOIN #contractualAllowances ca 
		ON ca.DepartmentID = gl.DepartmentID
		AND ca.AccountID = gl.AccountID
	INNER JOIN #tmpConAllowanceCalc calc
		ON ca.PayorGroupID = calc.PayorGroupID
		AND ca.EntityID = calc.EntityID
		AND ca.PatientClassID = calc.PatientClassID
	INNER JOIN #tmpConAllowanceCalc calc2
		ON ca.PayorGroupID = calc2.PayorGroupID
		AND ca.EntityID = calc2.EntityID
		AND ca.PatientClassID = calc2.PatientClassID
	WHERE 
		gl.APEModelSectionID = 4
		AND gl.BudgetConfigID = @BudgetConfigID
		AND gl.EntityGroupConfigID = @EntityConfigID
		AND ca.BudgetAllocationPercent <> 0
		AND calc.BudgetPhaseID = 2
		AND calc2.BudgetPhaseID = 3
	GROUP BY 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID

	--------------------------------------------------------------
	--Update budget
	--------------------------------------------------------------
	IF (@IsDebug = 1)
	BEGIN
		SELECT * FROM #tempInsert
	END ELSE BEGIN
		UPDATE gl
		SET
			BudgetLockFlag = 1,
			BudgetLockType = 3,
			TargetLockFlag = 1,
			TargetLockType = 3,
			BudgetAdjusted01 = ti.BudgetAllocatedAmount01,
			BudgetAdjusted02 = ti.BudgetAllocatedAmount02,
			BudgetAdjusted03 = ti.BudgetAllocatedAmount03,
			BudgetAdjusted04 = ti.BudgetAllocatedAmount04,
			BudgetAdjusted05 = ti.BudgetAllocatedAmount05,
			BudgetAdjusted06 = ti.BudgetAllocatedAmount06,
			BudgetAdjusted07 = ti.BudgetAllocatedAmount07,
			BudgetAdjusted08 = ti.BudgetAllocatedAmount08,
			BudgetAdjusted09 = ti.BudgetAllocatedAmount09,
			BudgetAdjusted10 = ti.BudgetAllocatedAmount10,
			BudgetAdjusted11 = ti.BudgetAllocatedAmount11,
			BudgetAdjusted12 = ti.BudgetAllocatedAmount12,
			TargetAdjusted01 = ti.TargetAllocatedAmount01,
			TargetAdjusted02 = ti.TargetAllocatedAmount02,
			TargetAdjusted03 = ti.TargetAllocatedAmount03,
			TargetAdjusted04 = ti.TargetAllocatedAmount04,
			TargetAdjusted05 = ti.TargetAllocatedAmount05,
			TargetAdjusted06 = ti.TargetAllocatedAmount06,
			TargetAdjusted07 = ti.TargetAllocatedAmount07,
			TargetAdjusted08 = ti.TargetAllocatedAmount08,
			TargetAdjusted09 = ti.TargetAllocatedAmount09,
			TargetAdjusted10 = ti.TargetAllocatedAmount10,
			TargetAdjusted11 = ti.TargetAllocatedAmount11,
			TargetAdjusted12 = ti.TargetAllocatedAmount12
		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID
			AND gl.VariabilityID = ti.VariabilityID
		WHERE 
			gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID
	END	
END
GO


---------------------------------------------

-- fp.procReimbursementToGLCrosswalk_Initial
CREATE   PROCEDURE [fp].[procReimbursementToGLCrosswalk_Initial]
	@BudgetConfigID INT,
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@EntityConfigID INT,	
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0	
AS 
BEGIN

	/**************************************************************
	** Change History	
	** CID Date 	   Author	WI 		   Description
	** 1   2022-06-21  MD 		JAZZ-37249 Initial
	** 2   2022-10-12  MD 		JAZZ-42139 Updating the allocation method of contractuals for reimbursement
	** 3   2023-08-14  MD 		JAZZ-58776 Update for GL restructure
	*************************************************************/

	IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances
	IF OBJECT_ID('tempdb..#tmpReimbursementCharge') IS NOT NULL DROP TABLE #tmpReimbursementCharge
	IF OBJECT_ID('tempdb..#tmpReimbursementEncounter') IS NOT NULL DROP TABLE #tmpReimbursementEncounter
	IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc
	IF OBJECT_ID('tempdb..#uniqueDimensionality') IS NOT NULL DROP TABLE #uniqueDimensionality	
	IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert	

	CREATE TABLE #tmpReimbursementCharge (
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetChargeDollars01 DECIMAL (19,8),
		BudgetChargeDollars02 DECIMAL (19,8),
		BudgetChargeDollars03 DECIMAL (19,8),
		BudgetChargeDollars04 DECIMAL (19,8),
		BudgetChargeDollars05 DECIMAL (19,8),
		BudgetChargeDollars06 DECIMAL (19,8),
		BudgetChargeDollars07 DECIMAL (19,8),
		BudgetChargeDollars08 DECIMAL (19,8),
		BudgetChargeDollars09 DECIMAL (19,8),
		BudgetChargeDollars10 DECIMAL (19,8),
		BudgetChargeDollars11 DECIMAL (19,8),
		BudgetChargeDollars12 DECIMAL (19,8),
		BudgetNetReimbursement01 DECIMAL (19,8),
		BudgetNetReimbursement02 DECIMAL (19,8),
		BudgetNetReimbursement03 DECIMAL (19,8),
		BudgetNetReimbursement04 DECIMAL (19,8),
		BudgetNetReimbursement05 DECIMAL (19,8),
		BudgetNetReimbursement06 DECIMAL (19,8),
		BudgetNetReimbursement07 DECIMAL (19,8),
		BudgetNetReimbursement08 DECIMAL (19,8),
		BudgetNetReimbursement09 DECIMAL (19,8),
		BudgetNetReimbursement10 DECIMAL (19,8),
		BudgetNetReimbursement11 DECIMAL (19,8),
		BudgetNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpReimbursementEncounter (
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetNetReimbursement01 DECIMAL (19,8),
		BudgetNetReimbursement02 DECIMAL (19,8),
		BudgetNetReimbursement03 DECIMAL (19,8),
		BudgetNetReimbursement04 DECIMAL (19,8),
		BudgetNetReimbursement05 DECIMAL (19,8),
		BudgetNetReimbursement06 DECIMAL (19,8),
		BudgetNetReimbursement07 DECIMAL (19,8),
		BudgetNetReimbursement08 DECIMAL (19,8),
		BudgetNetReimbursement09 DECIMAL (19,8),
		BudgetNetReimbursement10 DECIMAL (19,8),
		BudgetNetReimbursement11 DECIMAL (19,8),
		BudgetNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpConAllowanceCalc (
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetConAllowance01 DECIMAL (19,8),
		BudgetConAllowance02 DECIMAL (19,8),
		BudgetConAllowance03 DECIMAL (19,8),
		BudgetConAllowance04 DECIMAL (19,8),
		BudgetConAllowance05 DECIMAL (19,8),
		BudgetConAllowance06 DECIMAL (19,8),
		BudgetConAllowance07 DECIMAL (19,8),
		BudgetConAllowance08 DECIMAL (19,8),
		BudgetConAllowance09 DECIMAL (19,8),
		BudgetConAllowance10 DECIMAL (19,8),
		BudgetConAllowance11 DECIMAL (19,8),
		BudgetConAllowance12 DECIMAL (19,8)
	)

	--------------------------------------------------------------
	--Get reimbursement contractual allowances config for given budget config
	--------------------------------------------------------------
	SELECT
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID,
		sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent,
		sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent
	INTO #contractualAllowances
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID

	SELECT
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID
	INTO #uniqueDimensionality
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID

	--------------------------------------------------------------
	--Get reimbursement encounter data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementEncounter (PayorGroupID, EntityID, PatientClassID,
		BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04,
		BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08,
		BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12
	)
	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		sum(fre.InitialBudgetNetReimbursement01),
		sum(fre.InitialBudgetNetReimbursement02),
		sum(fre.InitialBudgetNetReimbursement03),
		sum(fre.InitialBudgetNetReimbursement04),
		sum(fre.InitialBudgetNetReimbursement05),
		sum(fre.InitialBudgetNetReimbursement06),
		sum(fre.InitialBudgetNetReimbursement07),
		sum(fre.InitialBudgetNetReimbursement08),
		sum(fre.InitialBudgetNetReimbursement09),
		sum(fre.InitialBudgetNetReimbursement10),
		sum(fre.InitialBudgetNetReimbursement11),
		sum(fre.InitialBudgetNetReimbursement12)
	FROM fp.FactReimbursementEncounter fre
	INNER JOIN #uniqueDimensionality ca
		ON  fre.PayorGroupID = ca.PayorGroupID
		AND fre.EntityID = ca.EntityID
		AND fre.PatientClassID = ca.PatientClassID
	WHERE
		fre.BudgetConfigID = @BudgetConfigID
		AND fre.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID > 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID

	UNION ALL
	
	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		0 AS PatientClassID,
		sum(fre.InitialBudgetNetReimbursement01),
		sum(fre.InitialBudgetNetReimbursement02),
		sum(fre.InitialBudgetNetReimbursement03),
		sum(fre.InitialBudgetNetReimbursement04),
		sum(fre.InitialBudgetNetReimbursement05),
		sum(fre.InitialBudgetNetReimbursement06),
		sum(fre.InitialBudgetNetReimbursement07),
		sum(fre.InitialBudgetNetReimbursement08),
		sum(fre.InitialBudgetNetReimbursement09),
		sum(fre.InitialBudgetNetReimbursement10),
		sum(fre.InitialBudgetNetReimbursement11),
		sum(fre.InitialBudgetNetReimbursement12)
	FROM fp.FactReimbursementEncounter fre
	INNER JOIN #uniqueDimensionality ca
		ON  fre.PayorGroupID = ca.PayorGroupID
		AND fre.EntityID = ca.EntityID
	WHERE
		fre.BudgetConfigID = @BudgetConfigID
		AND fre.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID = 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID

	--------------------------------------------------------------
	--Get reimbursement charge data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementCharge (PayorGroupID, EntityID, PatientClassID,
		BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04,
		BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08,
		BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12,
		BudgetChargeDollars01, BudgetChargeDollars02, BudgetChargeDollars03, BudgetChargeDollars04,
		BudgetChargeDollars05, BudgetChargeDollars06, BudgetChargeDollars07, BudgetChargeDollars08,
		BudgetChargeDollars09, BudgetChargeDollars10, BudgetChargeDollars11, BudgetChargeDollars12)
	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		sum(frc.InitialBudgetNetReimbursement01),
		sum(frc.InitialBudgetNetReimbursement02),
		sum(frc.InitialBudgetNetReimbursement03),
		sum(frc.InitialBudgetNetReimbursement04),
		sum(frc.InitialBudgetNetReimbursement05),
		sum(frc.InitialBudgetNetReimbursement06),
		sum(frc.InitialBudgetNetReimbursement07),
		sum(frc.InitialBudgetNetReimbursement08),
		sum(frc.InitialBudgetNetReimbursement09),
		sum(frc.InitialBudgetNetReimbursement10),
		sum(frc.InitialBudgetNetReimbursement11),
		sum(frc.InitialBudgetNetReimbursement12),
		sum(frc.InitialBudgetChargeDollars01),
		sum(frc.InitialBudgetChargeDollars02),
		sum(frc.InitialBudgetChargeDollars03),
		sum(frc.InitialBudgetChargeDollars04),
		sum(frc.InitialBudgetChargeDollars05),
		sum(frc.InitialBudgetChargeDollars06),
		sum(frc.InitialBudgetChargeDollars07),
		sum(frc.InitialBudgetChargeDollars08),
		sum(frc.InitialBudgetChargeDollars09),
		sum(frc.InitialBudgetChargeDollars10),
		sum(frc.InitialBudgetChargeDollars11),
		sum(frc.InitialBudgetChargeDollars12)
	FROM fp.FactReimbursementCharges frc
	INNER JOIN #uniqueDimensionality ca
		ON frc.PayorGroupID = ca.PayorGroupID
		AND frc.EntityID = ca.EntityID
		AND frc.PatientClassID = ca.PatientClassID
	WHERE
		frc.BudgetConfigID = @BudgetConfigID
		AND frc.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID > 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID

	UNION ALL 

	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		0 as PatientClassID,
		sum(frc.InitialBudgetNetReimbursement01),
		sum(frc.InitialBudgetNetReimbursement02),
		sum(frc.InitialBudgetNetReimbursement03),
		sum(frc.InitialBudgetNetReimbursement04),
		sum(frc.InitialBudgetNetReimbursement05),
		sum(frc.InitialBudgetNetReimbursement06),
		sum(frc.InitialBudgetNetReimbursement07),
		sum(frc.InitialBudgetNetReimbursement08),
		sum(frc.InitialBudgetNetReimbursement09),
		sum(frc.InitialBudgetNetReimbursement10),
		sum(frc.InitialBudgetNetReimbursement11),
		sum(frc.InitialBudgetNetReimbursement12),
		sum(frc.InitialBudgetChargeDollars01),
		sum(frc.InitialBudgetChargeDollars02),
		sum(frc.InitialBudgetChargeDollars03),
		sum(frc.InitialBudgetChargeDollars04),
		sum(frc.InitialBudgetChargeDollars05),
		sum(frc.InitialBudgetChargeDollars06),
		sum(frc.InitialBudgetChargeDollars07),
		sum(frc.InitialBudgetChargeDollars08),
		sum(frc.InitialBudgetChargeDollars09),
		sum(frc.InitialBudgetChargeDollars10),
		sum(frc.InitialBudgetChargeDollars11),
		sum(frc.InitialBudgetChargeDollars12)
	FROM fp.FactReimbursementCharges frc
	INNER JOIN #uniqueDimensionality ca
		ON frc.PayorGroupID = ca.PayorGroupID
		AND frc.EntityID = ca.EntityID
	WHERE
		frc.BudgetConfigID = @BudgetConfigID
		AND frc.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID = 0
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID

	--------------------------------------------------------------
	--Do allocation calculation
	--ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX
	--------------------------------------------------------------
	INSERT INTO #tmpConAllowanceCalc(PayorGroupID, EntityID, PatientClassID,
		BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04,
		BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08,
		BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12)
	SELECT 
		tc.PayorGroupID,
		tc.EntityID, 
		tc.PatientClassID,
		ISNULL(tc.BudgetChargeDollars01,0) - ISNULL(tc.BudgetNetReimbursement01,0) - ISNULL(te.BudgetNetReimbursement01,0) AS BudgetConAllowance01,
		ISNULL(tc.BudgetChargeDollars02,0) - ISNULL(tc.BudgetNetReimbursement02,0) - ISNULL(te.BudgetNetReimbursement02,0) AS BudgetConAllowance02,
		ISNULL(tc.BudgetChargeDollars03,0) - ISNULL(tc.BudgetNetReimbursement03,0) - ISNULL(te.BudgetNetReimbursement03,0) AS BudgetConAllowance03,
		ISNULL(tc.BudgetChargeDollars04,0) - ISNULL(tc.BudgetNetReimbursement04,0) - ISNULL(te.BudgetNetReimbursement04,0) AS BudgetConAllowance04,
		ISNULL(tc.BudgetChargeDollars05,0) - ISNULL(tc.BudgetNetReimbursement05,0) - ISNULL(te.BudgetNetReimbursement05,0) AS BudgetConAllowance05,
		ISNULL(tc.BudgetChargeDollars06,0) - ISNULL(tc.BudgetNetReimbursement06,0) - ISNULL(te.BudgetNetReimbursement06,0) AS BudgetConAllowance06,
		ISNULL(tc.BudgetChargeDollars07,0) - ISNULL(tc.BudgetNetReimbursement07,0) - ISNULL(te.BudgetNetReimbursement07,0) AS BudgetConAllowance07,
		ISNULL(tc.BudgetChargeDollars08,0) - ISNULL(tc.BudgetNetReimbursement08,0) - ISNULL(te.BudgetNetReimbursement08,0) AS BudgetConAllowance08,
		ISNULL(tc.BudgetChargeDollars09,0) - ISNULL(tc.BudgetNetReimbursement09,0) - ISNULL(te.BudgetNetReimbursement09,0) AS BudgetConAllowance09,
		ISNULL(tc.BudgetChargeDollars10,0) - ISNULL(tc.BudgetNetReimbursement10,0) - ISNULL(te.BudgetNetReimbursement10,0) AS BudgetConAllowance10,
		ISNULL(tc.BudgetChargeDollars11,0) - ISNULL(tc.BudgetNetReimbursement11,0) - ISNULL(te.BudgetNetReimbursement11,0) AS BudgetConAllowance11,
		ISNULL(tc.BudgetChargeDollars12,0) - ISNULL(tc.BudgetNetReimbursement12,0) - ISNULL(te.BudgetNetReimbursement12,0) AS BudgetConAllowance12
	FROM #tmpReimbursementCharge tc
	FULL JOIN #tmpReimbursementEncounter te
		ON tc.PayorGroupID = te.PayorGroupID
		AND tc.EntityID = te.EntityID
		AND tc.PatientClassID = te.PatientClassID

	--------------------------------------------------------------
	--Insert into temp table
	--Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL
	--------------------------------------------------------------
	SELECT
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount01,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount02,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount03,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount04,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount05,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount06,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount07,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount08,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount09,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount10,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount11,
		SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount12
	INTO #tempInsert
	FROM fp.GeneralLedger gl
	INNER JOIN #contractualAllowances ca 
		ON ca.DepartmentID = gl.DepartmentID
		AND ca.AccountID = gl.AccountID
	INNER JOIN #tmpConAllowanceCalc calc
		ON ca.PayorGroupID = calc.PayorGroupID
		AND ca.EntityID = calc.EntityID
		AND ca.PatientClassID = calc.PatientClassID
	WHERE 
		gl.BudgetConfigID = @BudgetConfigID
		AND gl.EntityGroupConfigID = @EntityConfigID
	GROUP BY 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID

	--------------------------------------------------------------
	--Update initials
	--------------------------------------------------------------
	IF (@IsDebug = 1)
	BEGIN
		SELECT * FROM #tempInsert		
	END ELSE BEGIN
		UPDATE gl 
		SET
			SampledBudget01 = ti.BudgetAllocatedAmount01,
			SampledBudget02 = ti.BudgetAllocatedAmount02,
			SampledBudget03 = ti.BudgetAllocatedAmount03,
			SampledBudget04 = ti.BudgetAllocatedAmount04,
			SampledBudget05 = ti.BudgetAllocatedAmount05,
			SampledBudget06 = ti.BudgetAllocatedAmount06,
			SampledBudget07 = ti.BudgetAllocatedAmount07,
			SampledBudget08 = ti.BudgetAllocatedAmount08,
			SampledBudget09 = ti.BudgetAllocatedAmount09,
			SampledBudget10 = ti.BudgetAllocatedAmount10,
			SampledBudget11 = ti.BudgetAllocatedAmount11,
			SampledBudget12 = ti.BudgetAllocatedAmount12,
			InitialBudget01 = ti.BudgetAllocatedAmount01,
			InitialBudget02 = ti.BudgetAllocatedAmount02,
			InitialBudget03 = ti.BudgetAllocatedAmount03,
			InitialBudget04 = ti.BudgetAllocatedAmount04,
			InitialBudget05 = ti.BudgetAllocatedAmount05,
			InitialBudget06 = ti.BudgetAllocatedAmount06,
			InitialBudget07 = ti.BudgetAllocatedAmount07,
			InitialBudget08 = ti.BudgetAllocatedAmount08,
			InitialBudget09 = ti.BudgetAllocatedAmount09,
			InitialBudget10 = ti.BudgetAllocatedAmount10,
			InitialBudget11 = ti.BudgetAllocatedAmount11,
			InitialBudget12 = ti.BudgetAllocatedAmount12
		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID		
			AND gl.VariabilityID = ti.VariabilityID
		WHERE 
			gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID
	END	
END
GO


---------------------------------------------

-- fp.procReimbursementToGLCrosswalk_Projection
CREATE   PROCEDURE [fp].[procReimbursementToGLCrosswalk_Projection]
	@BudgetConfigID INT,
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@EntityConfigID INT,	
	@MonthsLoaded INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS 
BEGIN

	/**************************************************************
	** Change History
	
	** CID	Date 		Author  WI 			Description
	** 1	2022-06-21  MD 		JAZZ-37249  Initial
	** 2 	2022-08-16  MD 		JAZZ-42139  Update to handle new dimensionality
	** 3	2023-08-14  MD 		JAZZ-58776  Update for GL restructure
	*************************************************************/

	IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances
	IF OBJECT_ID('tempdb..#tmpReimbursementCharge') IS NOT NULL DROP TABLE #tmpReimbursementCharge
	IF OBJECT_ID('tempdb..#tmpReimbursementEncounter') IS NOT NULL DROP TABLE #tmpReimbursementEncounter
	IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc
	IF OBJECT_ID('tempdb..#uniqueDimensionality') IS NOT NULL DROP TABLE #uniqueDimensionality
	IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert


	CREATE TABLE #tmpReimbursementCharge (
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetPhaseID TINYINT,
		ProjectionChargeDollars01 DECIMAL (19,8),
		ProjectionChargeDollars02 DECIMAL (19,8),
		ProjectionChargeDollars03 DECIMAL (19,8),
		ProjectionChargeDollars04 DECIMAL (19,8),
		ProjectionChargeDollars05 DECIMAL (19,8),
		ProjectionChargeDollars06 DECIMAL (19,8),
		ProjectionChargeDollars07 DECIMAL (19,8),
		ProjectionChargeDollars08 DECIMAL (19,8),
		ProjectionChargeDollars09 DECIMAL (19,8),
		ProjectionChargeDollars10 DECIMAL (19,8),
		ProjectionChargeDollars11 DECIMAL (19,8),
		ProjectionChargeDollars12 DECIMAL (19,8),
		ProjectionNetReimbursement01 DECIMAL (19,8),
		ProjectionNetReimbursement02 DECIMAL (19,8),
		ProjectionNetReimbursement03 DECIMAL (19,8),
		ProjectionNetReimbursement04 DECIMAL (19,8),
		ProjectionNetReimbursement05 DECIMAL (19,8),
		ProjectionNetReimbursement06 DECIMAL (19,8),
		ProjectionNetReimbursement07 DECIMAL (19,8),
		ProjectionNetReimbursement08 DECIMAL (19,8),
		ProjectionNetReimbursement09 DECIMAL (19,8),
		ProjectionNetReimbursement10 DECIMAL (19,8),
		ProjectionNetReimbursement11 DECIMAL (19,8),
		ProjectionNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpReimbursementEncounter (
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetPhaseID TINYINT,
		ProjectionNetReimbursement01 DECIMAL (19,8),
		ProjectionNetReimbursement02 DECIMAL (19,8),
		ProjectionNetReimbursement03 DECIMAL (19,8),
		ProjectionNetReimbursement04 DECIMAL (19,8),
		ProjectionNetReimbursement05 DECIMAL (19,8),
		ProjectionNetReimbursement06 DECIMAL (19,8),
		ProjectionNetReimbursement07 DECIMAL (19,8),
		ProjectionNetReimbursement08 DECIMAL (19,8),
		ProjectionNetReimbursement09 DECIMAL (19,8),
		ProjectionNetReimbursement10 DECIMAL (19,8),
		ProjectionNetReimbursement11 DECIMAL (19,8),
		ProjectionNetReimbursement12 DECIMAL (19,8)
	)

	CREATE TABLE #tmpConAllowanceCalc (
		PayorGroupID INT,
		EntityID INT,
		PatientClassID INT,
		BudgetPhaseID TINYINT,
		ProjectionConAllowance01 DECIMAL (19,8),
		ProjectionConAllowance02 DECIMAL (19,8),
		ProjectionConAllowance03 DECIMAL (19,8),
		ProjectionConAllowance04 DECIMAL (19,8),
		ProjectionConAllowance05 DECIMAL (19,8),
		ProjectionConAllowance06 DECIMAL (19,8),
		ProjectionConAllowance07 DECIMAL (19,8),
		ProjectionConAllowance08 DECIMAL (19,8),
		ProjectionConAllowance09 DECIMAL (19,8),
		ProjectionConAllowance10 DECIMAL (19,8),
		ProjectionConAllowance11 DECIMAL (19,8),
		ProjectionConAllowance12 DECIMAL (19,8)
	)

	--------------------------------------------------------------
	--Get reimbursement contractual allowances config for given budget config
	--------------------------------------------------------------
	SELECT
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID,
		sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent,
		sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent
	INTO #contractualAllowances
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.BudgetConfigGUID,
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID,
		data.DepartmentID, 
		data.AccountID

	SELECT
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID
	INTO #uniqueDimensionality
	FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data
	INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID
	WHERE
		data.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY 
		data.PayorGroupID,
		data.EntityID,
		data.PatientClassID

	--------------------------------------------------------------
	--Get reimbursement encounter data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementEncounter (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID,
		ProjectionNetReimbursement01, ProjectionNetReimbursement02, ProjectionNetReimbursement03, ProjectionNetReimbursement04,
		ProjectionNetReimbursement05, ProjectionNetReimbursement06, ProjectionNetReimbursement07, ProjectionNetReimbursement08,
		ProjectionNetReimbursement09, ProjectionNetReimbursement10, ProjectionNetReimbursement11, ProjectionNetReimbursement12
	)
	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		frep.BudgetPhaseID,
		sum(frep.AdjustedNetReimbursementValue01),
		sum(frep.AdjustedNetReimbursementValue02),
		sum(frep.AdjustedNetReimbursementValue03),
		sum(frep.AdjustedNetReimbursementValue04),
		sum(frep.AdjustedNetReimbursementValue05),
		sum(frep.AdjustedNetReimbursementValue06),
		sum(frep.AdjustedNetReimbursementValue07),
		sum(frep.AdjustedNetReimbursementValue08),
		sum(frep.AdjustedNetReimbursementValue09),
		sum(frep.AdjustedNetReimbursementValue10),
		sum(frep.AdjustedNetReimbursementValue11),
		sum(frep.AdjustedNetReimbursementValue12)
	FROM fp.FactReimbursementEncounter fre
	INNER JOIN #uniqueDimensionality ca
		ON  fre.PayorGroupID = ca.PayorGroupID
		AND fre.EntityID = ca.EntityID
		AND fre.PatientClassID = ca.PatientClassID
	INNER JOIN fp.FactReimbursementEncounterProjection frep
		ON fre.ReimbursementEncounterID = frep.ReimbursementEncounterID
	WHERE
		fre.BudgetConfigID = @BudgetConfigID
		AND fre.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID > 0
		AND frep.BudgetPhaseID = 3
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		frep.BudgetPhaseID

	UNION ALL

	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		0 AS PatientClassID,
		frep.BudgetPhaseID,
		sum(frep.AdjustedNetReimbursementValue01),
		sum(frep.AdjustedNetReimbursementValue02),
		sum(frep.AdjustedNetReimbursementValue03),
		sum(frep.AdjustedNetReimbursementValue04),
		sum(frep.AdjustedNetReimbursementValue05),
		sum(frep.AdjustedNetReimbursementValue06),
		sum(frep.AdjustedNetReimbursementValue07),
		sum(frep.AdjustedNetReimbursementValue08),
		sum(frep.AdjustedNetReimbursementValue09),
		sum(frep.AdjustedNetReimbursementValue10),
		sum(frep.AdjustedNetReimbursementValue11),
		sum(frep.AdjustedNetReimbursementValue12)
	FROM fp.FactReimbursementEncounter fre
	INNER JOIN #uniqueDimensionality ca
		ON  fre.PayorGroupID = ca.PayorGroupID
		AND fre.EntityID = ca.EntityID
	INNER JOIN fp.FactReimbursementEncounterProjection frep
		ON fre.ReimbursementEncounterID = frep.ReimbursementEncounterID
	WHERE
		fre.BudgetConfigID = @BudgetConfigID
		AND fre.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID = 0
		AND frep.BudgetPhaseID = 3
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		frep.BudgetPhaseID

	--------------------------------------------------------------
	--Get reimbursement charge data using CA dimensionality to group
	--------------------------------------------------------------
	INSERT INTO #tmpReimbursementCharge (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID,
		ProjectionNetReimbursement01, ProjectionNetReimbursement02, ProjectionNetReimbursement03, ProjectionNetReimbursement04,
		ProjectionNetReimbursement05, ProjectionNetReimbursement06, ProjectionNetReimbursement07, ProjectionNetReimbursement08,
		ProjectionNetReimbursement09, ProjectionNetReimbursement10, ProjectionNetReimbursement11, ProjectionNetReimbursement12,
		ProjectionChargeDollars01, ProjectionChargeDollars02, ProjectionChargeDollars03, ProjectionChargeDollars04,
		ProjectionChargeDollars05, ProjectionChargeDollars06, ProjectionChargeDollars07, ProjectionChargeDollars08,
		ProjectionChargeDollars09, ProjectionChargeDollars10, ProjectionChargeDollars11, ProjectionChargeDollars12)

	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		frcp.BudgetPhaseID,
		sum(frcp.AdjustedNetReimbursementValue01),
		sum(frcp.AdjustedNetReimbursementValue02),
		sum(frcp.AdjustedNetReimbursementValue03),
		sum(frcp.AdjustedNetReimbursementValue04),
		sum(frcp.AdjustedNetReimbursementValue05),
		sum(frcp.AdjustedNetReimbursementValue06),
		sum(frcp.AdjustedNetReimbursementValue07),
		sum(frcp.AdjustedNetReimbursementValue08),
		sum(frcp.AdjustedNetReimbursementValue09),
		sum(frcp.AdjustedNetReimbursementValue10),
		sum(frcp.AdjustedNetReimbursementValue11),
		sum(frcp.AdjustedNetReimbursementValue12),
		sum(frcp.AdjustedChargeDollars01),
		sum(frcp.AdjustedChargeDollars02),
		sum(frcp.AdjustedChargeDollars03),
		sum(frcp.AdjustedChargeDollars04),
		sum(frcp.AdjustedChargeDollars05),
		sum(frcp.AdjustedChargeDollars06),
		sum(frcp.AdjustedChargeDollars07),
		sum(frcp.AdjustedChargeDollars08),
		sum(frcp.AdjustedChargeDollars09),
		sum(frcp.AdjustedChargeDollars10),
		sum(frcp.AdjustedChargeDollars11),
		sum(frcp.AdjustedChargeDollars12)
	FROM fp.FactReimbursementCharges frc
	INNER JOIN #uniqueDimensionality ca
		ON frc.PayorGroupID = ca.PayorGroupID
		AND frc.EntityID = ca.EntityID
		AND frc.PatientClassID = ca.PatientClassID
	INNER JOIN fp.FactReimbursementChargesProjection frcp
		ON frc.ReimbursementChargesID = frcp.ReimbursementChargesID
	WHERE
		frc.BudgetConfigID = @BudgetConfigID
		AND frc.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID > 0
		AND frcp.BudgetPhaseID = 3
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		ca.PatientClassID,
		frcp.BudgetPhaseID

	UNION ALL

	SELECT 
		ca.PayorGroupID,
		ca.EntityID,
		0 AS PatientClassID,
		frcp.BudgetPhaseID,
		sum(frcp.AdjustedNetReimbursementValue01),
		sum(frcp.AdjustedNetReimbursementValue02),
		sum(frcp.AdjustedNetReimbursementValue03),
		sum(frcp.AdjustedNetReimbursementValue04),
		sum(frcp.AdjustedNetReimbursementValue05),
		sum(frcp.AdjustedNetReimbursementValue06),
		sum(frcp.AdjustedNetReimbursementValue07),
		sum(frcp.AdjustedNetReimbursementValue08),
		sum(frcp.AdjustedNetReimbursementValue09),
		sum(frcp.AdjustedNetReimbursementValue10),
		sum(frcp.AdjustedNetReimbursementValue11),
		sum(frcp.AdjustedNetReimbursementValue12),
		sum(frcp.AdjustedChargeDollars01),
		sum(frcp.AdjustedChargeDollars02),
		sum(frcp.AdjustedChargeDollars03),
		sum(frcp.AdjustedChargeDollars04),
		sum(frcp.AdjustedChargeDollars05),
		sum(frcp.AdjustedChargeDollars06),
		sum(frcp.AdjustedChargeDollars07),
		sum(frcp.AdjustedChargeDollars08),
		sum(frcp.AdjustedChargeDollars09),
		sum(frcp.AdjustedChargeDollars10),
		sum(frcp.AdjustedChargeDollars11),
		sum(frcp.AdjustedChargeDollars12)
	FROM fp.FactReimbursementCharges frc
	INNER JOIN #uniqueDimensionality ca
		ON frc.PayorGroupID = ca.PayorGroupID
		AND frc.EntityID = ca.EntityID
	INNER JOIN fp.FactReimbursementChargesProjection frcp
		ON frc.ReimbursementChargesID = frcp.ReimbursementChargesID
	WHERE
		frc.BudgetConfigID = @BudgetConfigID
		AND frc.EntityGroupConfigID = @EntityConfigID
		AND ca.PatientClassID = 0
		AND frcp.BudgetPhaseID = 3
	GROUP BY 
		ca.PayorGroupID,
		ca.EntityID,
		frcp.BudgetPhaseID

	--------------------------------------------------------------
	--Do allocation calculation
	--ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX
	--------------------------------------------------------------
	INSERT INTO #tmpConAllowanceCalc(PayorGroupID, EntityID, PatientClassID,
		ProjectionConAllowance01, ProjectionConAllowance02, ProjectionConAllowance03, ProjectionConAllowance04,
		ProjectionConAllowance05, ProjectionConAllowance06, ProjectionConAllowance07, ProjectionConAllowance08,
		ProjectionConAllowance09, ProjectionConAllowance10, ProjectionConAllowance11, ProjectionConAllowance12)
	SELECT 
		tc.PayorGroupID,
		tc.EntityID,
		tc.PatientClassID,
		ISNULL(tc.ProjectionChargeDollars01,0) - ISNULL(tc.ProjectionNetReimbursement01,0) - ISNULL(te.ProjectionNetReimbursement01,0) AS ProjectionConAllowance01,
		ISNULL(tc.ProjectionChargeDollars02,0) - ISNULL(tc.ProjectionNetReimbursement02,0) - ISNULL(te.ProjectionNetReimbursement02,0) AS ProjectionConAllowance02,
		ISNULL(tc.ProjectionChargeDollars03,0) - ISNULL(tc.ProjectionNetReimbursement03,0) - ISNULL(te.ProjectionNetReimbursement03,0) AS ProjectionConAllowance03,
		ISNULL(tc.ProjectionChargeDollars04,0) - ISNULL(tc.ProjectionNetReimbursement04,0) - ISNULL(te.ProjectionNetReimbursement04,0) AS ProjectionConAllowance04,
		ISNULL(tc.ProjectionChargeDollars05,0) - ISNULL(tc.ProjectionNetReimbursement05,0) - ISNULL(te.ProjectionNetReimbursement05,0) AS ProjectionConAllowance05,
		ISNULL(tc.ProjectionChargeDollars06,0) - ISNULL(tc.ProjectionNetReimbursement06,0) - ISNULL(te.ProjectionNetReimbursement06,0) AS ProjectionConAllowance06,
		ISNULL(tc.ProjectionChargeDollars07,0) - ISNULL(tc.ProjectionNetReimbursement07,0) - ISNULL(te.ProjectionNetReimbursement07,0) AS ProjectionConAllowance07,
		ISNULL(tc.ProjectionChargeDollars08,0) - ISNULL(tc.ProjectionNetReimbursement08,0) - ISNULL(te.ProjectionNetReimbursement08,0) AS ProjectionConAllowance08,
		ISNULL(tc.ProjectionChargeDollars09,0) - ISNULL(tc.ProjectionNetReimbursement09,0) - ISNULL(te.ProjectionNetReimbursement09,0) AS ProjectionConAllowance09,
		ISNULL(tc.ProjectionChargeDollars10,0) - ISNULL(tc.ProjectionNetReimbursement10,0) - ISNULL(te.ProjectionNetReimbursement10,0) AS ProjectionConAllowance10,
		ISNULL(tc.ProjectionChargeDollars11,0) - ISNULL(tc.ProjectionNetReimbursement11,0) - ISNULL(te.ProjectionNetReimbursement11,0) AS ProjectionConAllowance11,
		ISNULL(tc.ProjectionChargeDollars12,0) - ISNULL(tc.ProjectionNetReimbursement12,0) - ISNULL(te.ProjectionNetReimbursement12,0) AS ProjectionConAllowance12
	FROM #tmpReimbursementCharge tc
	FULL JOIN #tmpReimbursementEncounter te
		ON tc.PayorGroupID = te.PayorGroupID
		AND tc.EntityID = te.EntityID
		AND tc.PatientClassID = te.PatientClassID

	--------------------------------------------------------------
	--Insert into temp table
	--Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL
	--------------------------------------------------------------
	SELECT 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		SUM(CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 
		ELSE calc.ProjectionConAllowance01 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance01,
		SUM(CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 
		ELSE calc.ProjectionConAllowance02 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance02,
		SUM(CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 
		ELSE calc.ProjectionConAllowance03 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance03,
		SUM(CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 
		ELSE calc.ProjectionConAllowance04 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance04,
		SUM(CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 
		ELSE calc.ProjectionConAllowance05 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance05,
		SUM(CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 
		ELSE calc.ProjectionConAllowance06 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance06,
		SUM(CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 
		ELSE calc.ProjectionConAllowance07 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance07,
		SUM(CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 
		ELSE calc.ProjectionConAllowance08 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance08,
		SUM(CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 
		ELSE calc.ProjectionConAllowance09 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance09,
		SUM(CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 
		ELSE calc.ProjectionConAllowance10 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance10,
		SUM(CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 
		ELSE calc.ProjectionConAllowance11 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance11,
		SUM(CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 
		ELSE calc.ProjectionConAllowance12 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance12
	INTO #tempInsert
	FROM fp.GeneralLedger gl
	INNER JOIN #contractualAllowances ca 
		ON ca.DepartmentID = gl.DepartmentID
		AND ca.AccountID = gl.AccountID
	INNER JOIN #tmpConAllowanceCalc calc
		ON ca.PayorGroupID = calc.PayorGroupID
		AND ca.EntityID = calc.EntityID
		AND ca.PatientClassID = calc.PatientClassID
	WHERE 
		gl.APEModelSectionID = 4
		AND gl.BudgetConfigID = @BudgetConfigID
		AND gl.EntityGroupConfigID = @EntityConfigID
		AND ca.ProjectionAllocationPercent <> 0
		AND gl.VariabilityID = 2
	GROUP BY 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID
	UNION ALL
	SELECT 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID,
		SUM(CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END) AS ProjectionAllowance01,
		SUM(CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END) AS ProjectionAllowance02,
		SUM(CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END) AS ProjectionAllowance03,
		SUM(CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END) AS ProjectionAllowance04,
		SUM(CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END) AS ProjectionAllowance05,
		SUM(CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END) AS ProjectionAllowance06,
		SUM(CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END) AS ProjectionAllowance07,
		SUM(CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END) AS ProjectionAllowance08,
		SUM(CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END) AS ProjectionAllowance09,
		SUM(CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END) AS ProjectionAllowance10,
		SUM(CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END) AS ProjectionAllowance11,
		SUM(CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END) AS ProjectionAllowance12
	FROM fp.GeneralLedger gl
	INNER JOIN #contractualAllowances ca 
		ON ca.DepartmentID = gl.DepartmentID
		AND ca.AccountID = gl.AccountID
	INNER JOIN #tmpConAllowanceCalc calc
		ON ca.PayorGroupID = calc.PayorGroupID
		AND ca.EntityID = calc.EntityID
		AND ca.PatientClassID = calc.PatientClassID
	WHERE 
		gl.APEModelSectionID = 4
		AND gl.BudgetConfigID = @BudgetConfigID
		AND gl.EntityGroupConfigID = @EntityConfigID
		AND ca.ProjectionAllocationPercent <> 0
		AND gl.VariabilityID = 1
	GROUP BY 
		gl.DepartmentID,
		gl.AccountID,
		gl.VariabilityID

	--------------------------------------------------------------
	--Update projection table
	--------------------------------------------------------------
	IF (@IsDebug = 1)
	BEGIN
		SELECT * FROM #tempInsert		
	END ELSE BEGIN
		UPDATE gl
		SET
			ProjectionLockFlag = 1,
			ProjectionLockType = 3,
			ProjectionAdjusted01 = ti.ProjectionAllowance01,
			ProjectionAdjusted02 = ti.ProjectionAllowance02,
			ProjectionAdjusted03 = ti.ProjectionAllowance03,
			ProjectionAdjusted04 = ti.ProjectionAllowance04,
			ProjectionAdjusted05 = ti.ProjectionAllowance05,
			ProjectionAdjusted06 = ti.ProjectionAllowance06,
			ProjectionAdjusted07 = ti.ProjectionAllowance07,
			ProjectionAdjusted08 = ti.ProjectionAllowance08,
			ProjectionAdjusted09 = ti.ProjectionAllowance09,
			ProjectionAdjusted10 = ti.ProjectionAllowance10,
			ProjectionAdjusted11 = ti.ProjectionAllowance11,
			ProjectionAdjusted12 = ti.ProjectionAllowance12
		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID		
			AND gl.VariabilityID = ti.VariabilityID
		WHERE 
			gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID
			AND gl.VariabilityID = 2

		UPDATE gl
		SET
			ProjectionLockFlag = 1,
			ProjectionLockType = 3,
			ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END,
			ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END,
			ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END,
			ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END,
			ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END,
			ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END,
			ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END,
			ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END,
			ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END,
			ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END,
			ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END,
			ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END
		FROM fp.GeneralLedger gl
		INNER JOIN #tempInsert ti
			ON gl.DepartmentID = ti.DepartmentID
			AND gl.AccountID = ti.AccountID		
			AND gl.VariabilityID = ti.VariabilityID
		WHERE 
			gl.APEModelSectionID = 4
			AND gl.BudgetConfigID = @BudgetConfigID
			AND gl.EntityGroupConfigID = @EntityConfigID
			AND gl.VariabilityID = 1
	END	
END
GO


---------------------------------------------

-- fp.procRemoveCategoryForSetting
CREATE   PROCEDURE [fp].[procRemoveCategoryForSetting] 
	@CategoryName NVARCHAR(100),
	@SettingName NVARCHAR(100)
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI            Description
	** 1    10-18-2022   MY        Felt Like it  Initial Creation
	*************************************************************/

	DECLARE @CategoryID INT = (SELECT CategoryID FROM fp.DimCategory WHERE Category = @CategoryName)
	
	DECLARE @SystemSettingID INT = (SELECT SystemSettingID FROM fp.SystemSetting WHERE Name = @SettingName)
	IF (@SystemSettingID IS NOT NULL)
	BEGIN
		DELETE FROM fp.SettingCategory WHERE CategoryID = @CategoryID AND SystemSettingID = @SystemSettingID
	END
	
	SET @SystemSettingID = (SELECT SettingID FROM fp.BudgetConfigDefaultSetting WHERE Name = @SettingName)	
	IF (@SystemSettingID IS NOT NULL)
	BEGIN
		DELETE FROM fp.SettingCategory WHERE CategoryID = @CategoryID AND BudgetConfigDefaultSettingID = @SystemSettingID
	END
END
GO


---------------------------------------------

-- fp.procRemoveDataByStatisticsModel
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			Description
** 1		2024-01-17		mdeboer	   JAZZ-64957	Initial
***************************************************************/
CREATE PROC fp.procRemoveDataByStatisticsModel
	@BudgetConfigID INT,
	@EntityGroupConfigID INT
AS 
BEGIN
	DECLARE @StatsModelType SMALLINT
	SELECT @StatsModelType = StatisticsModel FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID

	IF OBJECT_ID('tempdb..#IDs') IS NOT NULL DROP TABLE #IDs
	CREATE TABLE #IDs (ID INT)

	--StatModelType = 0 -> SLE_CV_ACCT
	--Delete SLE data if stat model type <> 0
	IF(@StatsModelType <> 0) 
	BEGIN
		INSERT INTO #IDs (ID)
		SELECT
			sle.ServiceLineEncounterID		
		FROM fp.ServiceLineEncounter sle
		WHERE 
			sle.BudgetConfigID = @BudgetConfigID
			AND sle.EntityGroupConfigID = @EntityGroupConfigID

		DELETE sle
		FROM fp.ServiceLineEncounter sle
		JOIN #IDs id on sle.ServiceLineEncounterID = id.ID
	END

	TRUNCATE TABLE #IDs

	--StatModelType = 1 -> CV_ACCT
	--Delete CV data if stat model type = 2
	IF(@StatsModelType = 2) 
	BEGIN
		INSERT INTO #IDs (ID)
		SELECT
			cv.ChargeVolumeID		
		FROM fp.ChargeVolume cv
		WHERE 
			cv.BudgetConfigID = @BudgetConfigID
			AND cv.EntityGroupConfigID = @EntityGroupConfigID

		DELETE cv
		FROM fp.ChargeVolume cv
		JOIN #IDs id on cv.ChargeVolumeID = id.ID
	END
END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_Benefits
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1    2024-10-15   NH        JAZZ-74988  Adjustment history report 
 *************************************************************/

CREATE   PROCEDURE fp.procReportAdjustmentHistory_Benefits (
    @BudgetConfigID INT
)
AS
BEGIN
 
EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'

CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

CREATE TABLE #adjustments (
    AdjustmentID INT
)

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 7
DECLARE @PlanSectionID INT = 5

----------------------------------------------------------------------
--Get all adjustments
----------------------------------------------------------------------
INSERT INTO #adjustments
SELECT adj.AdjustmentID
FROM fp.BenefitsAdjustment adj WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON adj.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE adj.BudgetConfigGUID = @BudgetGUID
      AND (
           (adj.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND adj.AdjustmentType IN (0, 2, 3))  -- filter roll up adjustments
            OR adj.AdjustmentType IN (1, 4, 10, 11, 12, 13, 14)
           ) 
      AND (adj.LastModifiedDateUtc <> frah.LastModifiedDateUtc 
          OR frah.LastModifiedDateUtc is NULL)

CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------

SELECT AdjustmentID,
       COUNT(DISTINCT DepartmentID) AS DepartmentCount,
       MAX(DepartmentID) AS DepartmentID, 
       TimeClassID,
       UnitTypeID,
       COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount,
       MAX(FiscalMonthID) AS FiscalMonthID,
       COUNT(*) AS RecordsCount,
       SUM(RecordValue) AS TotalValue
       INTO #importAdjustments 
       FROM  (SELECT iadj.AdjustmentID,
                     TimeClassID,
                     UnitTypeID,
                     DepartmentID,
                     CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13
                          ELSE MAX(FiscalMonthID)
                     END AS FiscalMonthID,
                     SUM(Value) AS RecordValue
                     FROM fp.BenefitsAdjustmentImport AS iadj WITH (NOLOCK)
                     JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
                     GROUP BY iadj.AdjustmentID,
                              TimeClassID,
                              DepartmentID,
                              EntityID,
                              AccountID,
                              FinancialReportingID,
                              UnitTypeID) AS ImportRecord
       GROUP BY AdjustmentID,
                TimeClassID, 
                UnitTypeID

CREATE CLUSTERED    INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID)

INSERT INTO #SRC(
    BudgetConfigID,
    SectionID,
    AdjustmentID,
    AdjustmentType,
    Months,
    AdjustmentValue,
    AdjustedLevel,
    UnitTypeID,
    TimeClassID,
    LastModifiedDateUtc,
    DateCreatedUtc,
    Comment,
    AuthorFullName,
    ClassificationGroupID,
    ClassificationCategoryID,
    IsErrored,
    IsRecordDeleted)
    SELECT @BudgetConfigID,
           @SectionID,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.Value,
           res.AdjustedLevel,
           res.UnitTypeID,
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           ISNULL(res.Comment, ''),
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           res.IsErrored,
           res.IsRecordDeleted
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
               *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY adj.AdjustmentID ORDER BY adj.DateCreatedUtc DESC) AS RowNumber,
                   adj.AdjustmentID,
                   adj.BudgetConfigGUID,
                   adj.AdjustmentType,
                   fp.GetAdjustmentReportValue(adj.Value, adj.AdjustmentType) AS Value,
                   [fp].[GetAdjustmentPath](adj.AdjustmentFilterJSON, adj.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   adj.Comment,
                   adj.AuthorFullName,
                   adj.LastModifiedDateUtc,
                   adj.DateCreatedUtc,
                   adj.TimeClassID,
                   adj.BudgetPhaseID,
                   adj.ClassificationGroupID,
                   adj.ClassificationCategoryID,
                   adj.UnitTypeID,
                   adj.IsRecordDeleted,
                   adj.IsErrored
            FROM   fp.BenefitsAdjustment AS adj WITH (NOLOCK)
                   JOIN #adjustments AS adjs ON adjs.AdjustmentID = adj.AdjustmentID
                   LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE  adj.AdjustmentType IN (0, 2, 1, 3, 10, 11, 12, 13, 14)
                   AND (adj.GroupingGUID = '00000000-0000-0000-0000-000000000000'
                        OR adj.AdjustmentType IN (12, 13, 14))
           UNION ALL

            SELECT ROW_NUMBER() OVER (PARTITION BY adj.AdjustmentID ORDER BY adj.DateCreatedUtc DESC) AS RowNumber,
                   adj.AdjustmentID,
                   adj.BudgetConfigGUID,
                   adj.AdjustmentType,
                   CASE WHEN iadj.RecordsCount = 1 AND iadj.UnitTypeID IN (144, 170, 171) THEN '1 record affected' 
                        WHEN iadj.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, adj.AdjustmentType)
                        ELSE CAST(iadj.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN iadj.DepartmentCount = 1 THEN d.Name
                        ELSE CAST(iadj.DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   CASE WHEN iadj.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple')
                        ELSE 'Multiple'
                   END AS Months,
                   ISNULL(ag.Description, adj.Comment) AS Comment,
                   adj.AuthorFullName,
                   adj.LastModifiedDateUtc,
                   adj.DateCreatedUtc,
                   iadj.TimeClassID,
                   adj.BudgetPhaseID,
                   adj.ClassificationGroupID,
                   adj.ClassificationCategoryID,
                   iadj.UnitTypeID,
                   adj.IsRecordDeleted,
                   adj.IsErrored
            FROM   fp.BenefitsAdjustment AS adj WITH (NOLOCK)
                   JOIN #importAdjustments AS iadj ON iadj.AdjustmentID = adj.AdjustmentID
                   JOIN fw.DimDepartment AS d WITH (NOLOCK) ON iadj.DepartmentID = d.DepartmentID
                   LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = adj.GroupingGUID
                   LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on iadj.FiscalMonthID = dfm.FiscalMonthID
            WHERE  adj.AdjustmentType = 4
                        
            ) AS res_inner
        WHERE res_inner.RowNumber = 1 ) AS res
    WHERE res.RowNumber = 1
    ORDER BY res.DateCreatedUtc DESC

----------------------------------------------------------------------
-- Insert data to reportTable
----------------------------------------------------------------------

;WITH TGT AS 
(
    SELECT BudgetConfigID,
           SectionID,
           AdjustmentID,
           AdjustmentType,
           Months,
           AdjustmentValue,
           AdjustedLevel,
           UnitTypeID,
           TimeClassID,
           LastModifiedDateUtc,
           DateCreatedUtc,
           Comment,
           AuthorFullName,
           ClassificationGroupID,
           ClassificationCategoryID,
           IsErrored,
           IsRecordDeleted
    FROM fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID 
          AND fr.SectionID = @SectionID
)
    MERGE TGT as target
    USING #src AS source
        ON (
            target.BudgetConfigID   = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID    = source.SectionID
            AND target.TimeClassID  = source.TimeClassID
            AND target.UnitTypeID   = source.UnitTypeID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc       = source.LastModifiedDateUtc,
                 target.AdjustmentValue          = source.AdjustmentValue,
                 target.IsErrored                = source.IsErrored,
                 target.IsRecordDeleted          = source.IsRecordDeleted,
                 target.ClassificationGroupID    = source.ClassificationGroupID,
                 target.ClassificationCategoryID = source.ClassificationCategoryID,
                 target.Comment                  = source.Comment
                                                 
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                BudgetConfigID,
                SectionID,
                AdjustmentID,
                AdjustmentType,
                Months,
                AdjustmentValue,
                AdjustedLevel,
                UnitTypeID,
                TimeClassID,
                LastModifiedDateUtc,
                DateCreatedUtc,
                Comment,
                AuthorFullName,
                ClassificationGroupID,
                ClassificationCategoryID,
                IsErrored,
                IsRecordDeleted
            )
            VALUES (
                source.BudgetConfigID,
                source.SectionID,
                source.AdjustmentID,  
                source.AdjustmentType,  
                source.Months, 
                source.AdjustmentValue,
                source.AdjustedLevel,
                source.UnitTypeID,   
                source.TimeClassID,
                source.LastModifiedDateUtc, 
                source.DateCreatedUtc,
                source.Comment,
                source.AuthorFullName,
                source.ClassificationGroupID,
                source.ClassificationCategoryID,
                source.IsErrored,
                source.IsRecordDeleted
            );  

END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_ChargeVolume
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1       2024-10-15   NH        JAZZ-74988  Adjustment history report 
 *************************************************************/
CREATE   PROCEDURE fp.procReportAdjustmentHistory_ChargeVolume (
    @BudgetConfigID INT
)
AS
BEGIN

EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'

CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

CREATE TABLE #adjustments (
    AdjustmentID INT
)

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 2
DECLARE @PlanSectionID INT = 2

----------------------------------------------------------------------
--Get all adjustments
----------------------------------------------------------------------
INSERT INTO #adjustments
SELECT dcva.AdjustmentID
FROM fp.DepartmentChargeVolumeAdjustment dcva WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON dcva.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE dcva.BudgetConfigGUID = @budgetGUID
      AND (
           (dcva.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND dcva.AdjustmentType IN (0, 2, 3))   -- filter roll up adjustments
            OR dcva.AdjustmentType IN (1, 4, 12, 13, 14)
           )
      AND (dcva.LastModifiedDateUtc <> frah.LastModifiedDateUtc 
           OR frah.LastModifiedDateUtc is NULL)

CREATE CLUSTERED INDEX PK_SecuredAdjustments ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------
SELECT AdjustmentID,
       COUNT(DISTINCT DepartmentID) AS DepartmentCount,
       MAX(DepartmentID) AS DepartmentID, 
       TimeClassID,
       COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount,
       MAX(FiscalMonthID) AS FiscalMonthID,
       COUNT(*) AS RecordsCount,
       SUM(RecordValue) AS TotalValue
       INTO #importAdjustments 
       FROM  (SELECT iadj.AdjustmentID,
                     TimeClassID,
                     DepartmentID,
                     CASE WHEN COUNT(DISTINCT FiscalMonthID)> 1 THEN 13
                          ELSE MAX(FiscalMonthID)
                     END AS FiscalMonthID,
                     SUM(Value) AS RecordValue
                     FROM fp.DepartmentChargeAdjustmentImport AS iadj WITH (NOLOCK)
                     JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
                     GROUP BY iadj.AdjustmentID,
                              TimeClassID,
                              DepartmentID,
                              ServiceLineID,
                              PatientClassID,
                              AgeCohortID,
                              MedicalSurgicalID,
                              ChargeCodeID,
                              ServiceEntityID,
                              MSDRGID,
                              UBRevCodeID,
                              PrimaryCPTID,
                              ServiceProviderID,
                              --ServiceProviderSpecialtyID,
                              PerformingProviderID,
                              --PerformingProviderSpecialtyID,
                              BillingCPTID
                              --EntityID
                              ) AS ImportRecord
       GROUP BY AdjustmentID,
                TimeClassID

CREATE CLUSTERED INDEX PK_ImportAdjustments ON #importAdjustments (AdjustmentID)    

INSERT INTO #SRC
    (BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted)
    SELECT @BudgetConfigID,
           @SectionID,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.[Value],
           res.AdjustedLevel,
           res.UnitTypeID,
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           ISNULL(res.Comment, ''),
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           res.IsErrored,
           res.IsRecordDeleted
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
               *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY dcva.AdjustmentID ORDER BY dcva.DateCreatedUtc DESC) AS RowNumber,
                   dcva.AdjustmentID,
                   dcva.AdjustmentType,
                   fp.GetAdjustmentReportValue(dcva.Value, dcva.AdjustmentType) AS Value,
                   fp.GetAdjustmentPath(dcva.AdjustmentFilterJSON, dcva.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   dcva.Comment,
                   dcva.AuthorFullName,
                   dcva.LastModifiedDateUtc,
                   dcva.DateCreatedUtc,
                   dcva.TimeClassID,
                   CAST(2 AS TINYINT) AS BudgetPhaseID,
                   dcva.ClassificationGroupID,
                   dcva.ClassificationCategoryID,
                   CAST(145 AS TINYINT) AS UnitTypeID,
                   dcva.IsRecordDeleted,
                   dcva.IsErrored
            FROM  fp.DepartmentChargeVolumeAdjustment AS dcva WITH (NOLOCK)
                  JOIN #adjustments AS adj ON adj.AdjustmentID = dcva.AdjustmentID
                  LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE  dcva.AdjustmentType <> 4 
            
            UNION ALL 
            
            -- Import Adjustments
            SELECT ROW_NUMBER() OVER (PARTITION BY dcva.AdjustmentID ORDER BY dcva.DateCreatedUtc DESC) AS RowNumber,
                   dcva.AdjustmentID,
                   dcva.AdjustmentType,
                   CASE WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, dcva.AdjustmentType)
                        ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN sai.DepartmentCount = 1 THEN d.Name
                        ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple')
                        ELSE 'Multiple'
                   END AS Months,
                   ISNULL(ag.Description, dcva.Comment) AS Comment,
                   dcva.AuthorFullName,
                   dcva.LastModifiedDateUtc,
                   dcva.DateCreatedUtc,
                   sai.TimeClassID,
                   CAST(2 AS TINYINT),
                   dcva.ClassificationGroupID,
                   dcva.ClassificationCategoryID,
                   CAST(145 AS TINYINT) AS UnitTypeID,
                   dcva.IsRecordDeleted,
                   dcva.IsErrored
            FROM   fp.DepartmentChargeVolumeAdjustment AS dcva WITH (NOLOCK)   
                   JOIN #importAdjustments AS sai ON sai.AdjustmentID = dcva.AdjustmentID
                   JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID 
                   LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = dcva.GroupingGUID
                   LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID
            WHERE  dcva.AdjustmentType = 4             

            ) AS res_inner
        WHERE res_inner.RowNumber = 1 ) AS res
    ORDER BY res.DateCreatedUtc DESC     

----------------------------------------------------------------------
-- Insert data to reportTable
----------------------------------------------------------------------
;WITH TGT AS 
(
    SELECT BudgetConfigID,
           SectionID,
           AdjustmentID,
           AdjustmentType,
           Months,
           AdjustmentValue,
           AdjustedLevel,
           UnitTypeID,
           TimeClassID,
           LastModifiedDateUtc,
           DateCreatedUtc,
           Comment,
           AuthorFullName,
           ClassificationGroupID,
           ClassificationCategoryID,
           IsErrored,
           IsRecordDeleted
    FROM  fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID
          AND fr.SectionID = @SectionID
)
    MERGE TGT AS target
    USING #src AS source
        ON (
            target.BudgetConfigID   = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID    = source.SectionID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                target.AdjustmentValue          = source.AdjustmentValue,
                target.IsErrored                = source.IsErrored,
                target.IsRecordDeleted          = source.IsRecordDeleted,
                target.ClassificationGroupID    = source.ClassificationGroupID,
                target.ClassificationCategoryID = source.ClassificationCategoryID,
                target.Comment                  = source.Comment
                                                 
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                BudgetConfigID,
                SectionID,
                AdjustmentID,
                AdjustmentType,
                Months,
                AdjustmentValue,
                AdjustedLevel,
                UnitTypeID,
                TimeClassID,
                LastModifiedDateUtc,
                DateCreatedUtc, 
                Comment,
                AuthorFullName,
                ClassificationGroupID,
                ClassificationCategoryID,
                IsErrored,
                IsRecordDeleted
            )
            VALUES (
                source.BudgetConfigID,
                source.SectionID, 
                source.AdjustmentID,  
                source.AdjustmentType,  
                source.Months, 
                source.AdjustmentValue,
                source.AdjustedLevel,
                source.UnitTypeID,   
                source.TimeClassID,
                source.LastModifiedDateUtc, 
                source.DateCreatedUtc,
                source.Comment,
                source.AuthorFullName,
                source.ClassificationGroupID,
                source.ClassificationCategoryID,
                source.IsErrored,
                source.IsRecordDeleted
            );

END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_GeneralLedger
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1       2024-10-15   NH        JAZZ-74988  Adjustment history report 
 *************************************************************/
CREATE   PROCEDURE fp.procReportAdjustmentHistory_GeneralLedger (
    @BudgetConfigID INT
) 
AS
BEGIN

EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'

CREATE TABLE #adjustments (
    AdjustmentID INT
)

CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT,
    IsSetValue               BIT
)

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 8
DECLARE @PlanSectionID INT = 6

----------------------------------------------------------------------
--Get all adjustments
----------------------------------------------------------------------
INSERT INTO #adjustments
SELECT gla.AdjustmentID
FROM fp.GeneralLedgerAdjustment gla WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON gla.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE gla.BudgetConfigGUID = @budgetGUID
      AND (
            (gla.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND gla.AdjustmentType IN (0, 2, 3))  -- filter roll up adjustments
             OR gla.AdjustmentType IN (1, 4, 8, 10, 11, 12, 13, 14, 16, 18, 19)
           )
      AND (gla.LastModifiedDateUtc <> frah.LastModifiedDateUtc 
           OR frah.LastModifiedDateUtc is NULL)

CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------
SELECT AdjustmentID,
       COUNT(DISTINCT DepartmentID) AS DepartmentCount,
       MAX(DepartmentID) AS DepartmentID, 
       TimeClassID,
       BudgetPhaseID,
       UnitTypeID,
       COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount,
       MAX(FiscalMonthID) AS FiscalMonthID,
       COUNT(*) AS RecordsCount,
       SUM(RecordValue) AS TotalValue
       INTO #importAdjustments 
       FROM  (SELECT iadj.AdjustmentID,
                     TimeClassID,
                     DepartmentID,
                     BudgetPhaseID,
                     ISNULL(ORIGINALUNITTYPEID, UnitTypeID) AS UnitTypeID,
                     CASE WHEN COUNT(DISTINCT FiscalMonthID)> 1 THEN 13
                          ELSE MAX(FiscalMonthID)
                     END AS FiscalMonthID,
                     SUM(Value) AS RecordValue
                     FROM fp.GeneralLedgerAdjustmentImport AS iadj WITH (NOLOCK)
                     JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
                     GROUP BY iadj.AdjustmentID,
                              TimeClassID,
                              BudgetPhaseID,
                              DepartmentID,
                              AccountID,
                              FinancialReportingID,
                              VariabilityID,
                              EntityID,
                              ISNULL(ORIGINALUNITTYPEID, UnitTypeID)
                              ) AS ImportRecord
       GROUP BY AdjustmentID,
                TimeClassID,
                BudgetPhaseID,
                UnitTypeID

CREATE CLUSTERED    INDEX PK_ImportAdjustments ON #importAdjustments (AdjustmentID, UnitTypeID)


INSERT INTO #SRC(
     BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted,
     IsSetValue)
    SELECT @BudgetConfigID,
           @SectionID,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.[Value],
           res.AdjustedLevel,
           res.UnitTypeID,
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           ISNULL(res.Comment, ''),
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           res.IsErrored,
           res.IsRecordDeleted,
           res.IsSetValue
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, 
                *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber,
                   gla.AdjustmentID,
                   gla.AdjustmentType,
                   fp.GetAdjustmentReportValue(gla.Value, gla.AdjustmentType) AS Value,
                   [fp].[GetAdjustmentPath](gla.AdjustmentFilterJSON, gla.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   gla.Comment,
                   gla.AuthorFullName,
                   gla.LastModifiedDateUtc,
                   gla.DateCreatedUtc,
                   gla.TimeClassID,
                   gla.BudgetPhaseID,
                   gla.ClassificationGroupID,
                   gla.ClassificationCategoryID,
                   gla.UnitTypeId,
                   gla.IsRecordDeleted,
                   gla.IsErrored,
                   0 AS IsSetValue
            FROM   fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK)
                   JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID
                   LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE  gla.AdjustmentType NOT IN (4, 16, 18, 19) 
                    
            UNION ALL

            -- Import Adjustments
            SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID, sai.UnitTypeId  ORDER BY gla.DateCreatedUtc DESC) AS RowNumber,
                   gla.AdjustmentID,
                   gla.AdjustmentType,
                   CASE WHEN sai.RecordsCount = 1 AND sai.UnitTypeID = 33 THEN '1 record affected'
                        WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType)
                        ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN sai.DepartmentCount = 1 THEN d.Name
                        ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple')
                        ELSE 'Multiple'
                   END AS Months,
                   ISNULL(ag.Description, gla.Comment) AS Comment,
                   gla.AuthorFullName,
                   gla.LastModifiedDateUtc,
                   gla.DateCreatedUtc,
                   sai.TimeClassID,
                   sai.BudgetPhaseID,
                   gla.ClassificationGroupID,
                   gla.ClassificationCategoryID,
                   sai.UnitTypeId,
                   gla.IsRecordDeleted,
                   gla.IsErrored,
                   0 AS IsSetValue
            FROM    fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK)
                    JOIN #importAdjustments AS sai ON sai.AdjustmentID = gla.AdjustmentID
                    JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID
                    JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = gla.GroupingGUID
                    LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON sai.FiscalMonthID = dfm.FiscalMonthID
            WHERE   gla.AdjustmentType = 4
                                        
            UNION ALL

            -- SubAccount Adjustments
            SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber,
                   gla.AdjustmentID,
                   gla.AdjustmentType,
                   CASE WHEN subAccountAdj.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType)
                        ELSE CAST(subAccountAdj.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN DepartmentCount = 1 THEN dept.Name
                        ELSE CAST(DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   'Multiple' AS Months ,
                   gla.Comment,
                   gla.AuthorFullName,
                   gla.LastModifiedDateUtc,
                   gla.DateCreatedUtc,
                   gla.TimeClassID,
                   gla.BudgetPhaseID,
                   gla.ClassificationGroupID,
                   gla.ClassificationCategoryID,
                   gla.UnitTypeId,
                   gla.IsRecordDeleted,
                   gla.IsErrored,
                   0 AS IsSetValue
            FROM   fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK)
                   JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID
                   LEFT JOIN (
                            SELECT
                                 OBJ.AdjustmentID AS AdjustmentID
                                 ,MAX(OBJ.DepartmentID) AS DepartmentID
                                 ,COUNT(DISTINCT dept.DepartmentID) AS DepartmentCount
                                 ,SUM(Value01) + SUM(Value02) +SUM(Value03) + SUM(Value04) + SUM(Value05) + SUM(Value06) + SUM(Value07) + SUM(Value08) + SUM(Value09) + SUM(Value10) + SUM(Value11) + SUM(Value12) AS TotalValue
                                 ,COUNT(SubAccountItemizedID) AS RecordsCount
                            FROM  fp.GeneralLedgerSubAccountItemizedAdjustment AS OBJ WITH (NOLOCK)
                                  JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID      
                            WHERE 1=1
                            GROUP BY OBJ.AdjustmentID
                   ) AS subAccountAdj ON subAccountAdj.AdjustmentID = gla.AdjustmentID
                   JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = subAccountAdj.DepartmentID
            WHERE  gla.AdjustmentType = 18
                
            UNION ALL

            -- AddAccount Adj
            SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber,
                   gla.AdjustmentID,
                   gla.AdjustmentType,
                   CASE WHEN addAccountAdj.RecordsCount = 1 THEN '1 record affected'
                       ELSE CAST(addAccountAdj.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN addAccountAdj.DepartmentCount = 1 THEN dept.Name
                       ELSE CAST(addAccountAdj.DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   'All' AS Months,
                   CASE WHEN addAccountAdj.CommentsCount = 0 THEN ''
                        WHEN addAccountAdj.CommentsCount = 1 THEN addAccountAdj.Comment
                        ELSE 'Multiple Comments'
                   END AS Comment,
                   gla.AuthorFullName,
                   gla.LastModifiedDateUtc,
                   gla.DateCreatedUtc,
                   TimeClassID,
                   gla.BudgetPhaseID,
                   0 AS ClassificationGroupID,
                   0 AS ClassificationCategoryID,
                   0 AS UnitTypeId,
                   gla.IsRecordDeleted,
                   gla.IsErrored,
                   0 AS IsSetValue
            FROM   fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK)
                   JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID
                   LEFT JOIN (
                            SELECT
                                  OBJ.AdjustmentID AS AdjustmentID,
                                  MAX(OBJ.DepartmentID) AS DepartmentID,
                                  COUNT(DISTINCT DepartmentID) AS DepartmentCount,
                                  STRING_AGG(CASE WHEN Comment <> '' THEN CAST(Comment AS NVARCHAR(MAX)) ELSE NULL END, ';') AS Comment,
                                  SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentsCount,
                                  COUNT(RowID) AS RecordsCount
                            FROM  fp.GeneralLedgerAddAccountAdjustment AS OBJ WITH (NOLOCK)       
                            WHERE 1=1 
                            GROUP BY OBJ.AdjustmentID
                    ) AS addAccountAdj ON addAccountAdj.AdjustmentID = gla.AdjustmentID
                    JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = addAccountAdj.DepartmentID
            WHERE gla.AdjustmentType = 19

            UNION ALL
            -- My Budget Adjustments
           SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID, adjDetail.TimeClassID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber,
                  gla.AdjustmentID,
                  gla.AdjustmentType,
                  CASE WHEN adjDetail.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType)
                       ELSE CAST(adjDetail.RecordsCount as varchar(30)) + ' records affected'
                  END AS [Value],
                  dept.Name AS AdjustedLevel,
                  'All' AS Months,
                  CASE WHEN adjDetail.CommentsCount = 0 THEN ''
                       WHEN adjDetail.CommentsCount = 1 THEN adjDetail.CommentTotal
                       ELSE 'Multiple Comments'
                  END AS Comment,
                  gla.AuthorFullName,
                  gla.LastModifiedDateUtc,
                  gla.DateCreatedUtc,
                  adjDetail.TimeClassID,
                  gla.BudgetPhaseID,
                  gla.ClassificationGroupID,
                  gla.ClassificationCategoryID,
                  33,  -- UNIT TYPE ID
                  gla.IsRecordDeleted,
                  gla.IsErrored,
                  adjDetail.IsSetValue
            FROM  fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK)
                  JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID            
                  JOIN (SELECT AdjustmentID,
                               DepartmentID,
                               TimeClassID,
                               STRING_AGG(CASE WHEN Comment <> '' THEN CAST(Comment AS NVARCHAR(MAX)) ELSE NULL END, ';') AS CommentTotal,
                               COUNT(Comment) AS RecordsCount,
                               SUM(DollarsValue) AS TotalValue,
                               SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentsCount,
                               1 AS IsSetValue
                         FROM fp.GeneralLedgerVariableDetail WITH (NOLOCK)
                         GROUP BY AdjustmentID, DepartmentID, TimeClassID
                       ) AS adjDetail ON gla.AdjustmentID = adjDetail.AdjustmentID
                 JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = adjDetail.DepartmentID 
            WHERE AdjustmentType = 16
                 
            UNION ALL
                 
            SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID, adjDetail.TimeClassID, adjDetail.IsMarkedForDeletion ORDER BY gla.DateCreatedUtc DESC) AS RowNumber,
                   gla.AdjustmentID,
                   gla.AdjustmentType,
                   CASE WHEN adjDetail.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType) 
                        ELSE CAST(adjDetail.RecordsCount as varchar(30)) + ' records affected' 
                   END AS [Value],
                   dept.Name AS AdjustedLevel,
                   'All' AS Months,
                   CASE WHEN adjDetail.CommentsCount = 0 THEN ''
                       WHEN adjDetail.CommentsCount = 1 THEN adjDetail.CommentTotal
                       ELSE 'Multiple Comments'
                   END AS Comment,
                   gla.AuthorFullName,
                   gla.LastModifiedDateUtc,
                   gla.DateCreatedUtc,
                   adjDetail.TimeClassID,
                   gla.BudgetPhaseID,
                   gla.ClassificationGroupID,
                   gla.ClassificationCategoryID,
                   34,  -- UNIT TYPE ID
                   adjDetail.IsMarkedForDeletion AS IsRecordDeleted,
                   gla.IsErrored,
                   adjDetail.IsSetValue
            FROM fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK)
                 JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID            
                 JOIN (SELECT AdjustmentID, 
                              DepartmentID,
                              TimeClassID,
                              STRING_AGG(CASE WHEN Comment <> '' THEN CAST(Comment AS NVARCHAR(MAX)) ELSE NULL END, ';') AS CommentTotal,
                              COUNT(Comment) AS RecordsCount,
                              SUM(DollarsValue) AS TotalValue,
                              SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentsCount,
                              IsSetValue,
                              IsMarkedForDeletion
                       FROM fp.GeneralLedgerFixedDetail WITH (NOLOCK)
                       GROUP BY AdjustmentID, DepartmentID, TimeClassID, IsSetValue, IsMarkedForDeletion
                     ) AS adjDetail ON gla.AdjustmentID = adjDetail.AdjustmentID
                 JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = adjDetail.DepartmentID 
            WHERE AdjustmentType = 16     
                 
            ) AS res_inner
        WHERE res_inner.RowNumber = 1 ) AS res
        
----------------------------------------------------------------------
-- Insert data to reportTable
----------------------------------------------------------------------
;WITH TGT AS 
(
    SELECT BudgetConfigID,
           SectionID,
           AdjustmentID,
           AdjustmentType,
           Months,
           AdjustmentValue,
           AdjustedLevel,
           UnitTypeID,
           TimeClassID,
           LastModifiedDateUtc,
           DateCreatedUtc,
           Comment,
           AuthorFullName,
           ClassificationGroupID,
           ClassificationCategoryID,
           IsErrored,
           IsRecordDeleted,
           IsSetValue
    FROM fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID 
          AND fr.SectionID = @SectionID
)
    MERGE TGT AS target
    USING #src AS source
        ON (
            target.BudgetConfigID   = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID    = source.SectionID
            AND target.TimeClassID  = source.TimeClassID
            AND target.UnitTypeID   = source.UnitTypeID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                target.AdjustmentValue          = source.AdjustmentValue,
                target.IsErrored                = source.IsErrored,
                target.IsRecordDeleted          = source.IsRecordDeleted,
                target.ClassificationGroupID    = source.ClassificationGroupID,
                target.ClassificationCategoryID = source.ClassificationCategoryID,
                target.Comment                  = source.Comment
                                                 
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                 BudgetConfigID,
                 SectionID,
                 AdjustmentID,
                 AdjustmentType,
                 Months,
                 AdjustmentValue,
                 AdjustedLevel,
                 UnitTypeID,
                 TimeClassID,
                 LastModifiedDateUtc,
                 DateCreatedUtc,
                 Comment,
                 AuthorFullName,
                 ClassificationGroupID,
                 ClassificationCategoryID,
                 IsErrored,
                 IsRecordDeleted,
                 IsSetValue
            )
            VALUES (
                 source.BudgetConfigID,
                 source.SectionID, 
                 source.AdjustmentID,  
                 source.AdjustmentType,  
                 source.Months, 
                 source.AdjustmentValue,
                 source.AdjustedLevel,
                 source.UnitTypeID,   
                 source.TimeClassID,
                 source.LastModifiedDateUtc, 
                 source.DateCreatedUtc,
                 source.Comment,
                 source.AuthorFullName,
                 source.ClassificationGroupID,
                 source.ClassificationCategoryID,
                 source.IsErrored,
                 source.IsRecordDeleted,
                 source.IsSetValue
            );        

END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_ProviderCompensation
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1       2024-10-15   NH       JAZZ-74988  Adjustment history report 
 *************************************************************/

CREATE   PROCEDURE fp.procReportAdjustmentHistory_ProviderCompensation (
    @BudgetConfigID INT
)
AS
BEGIN

EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'

CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(max),
    AdjustedLevel            NVARCHAR(max),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(max),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 6
DECLARE @PlanSectionID INT = 4
    
----------------------------------------------------------------------
-- Get all adjustments
----------------------------------------------------------------------
SELECT slea.AdjustmentID
INTO #adjustments
FROM fp.StaffingAdjustment slea WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE slea.BudgetConfigGUID = @budgetGUID
      AND slea.SubsectionID = 4  -- Provider
      AND (
           (slea.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND slea.AdjustmentType IN (0, 2, 3))  -- filter roll up adjustments
            OR slea.AdjustmentType IN (1, 4, 8, 10, 11, 12, 13, 14, 15)
           )
      AND (slea.LastModifiedDateUtc <> frah.LastModifiedDateUtc 
           OR frah.LastModifiedDateUtc is NULL)

CREATE CLUSTERED    INDEX PK_SecuredAdjustmnets ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------
SELECT AdjustmentID,
       COUNT(DISTINCT DepartmentID) AS DepartmentCount,
       MAX(DepartmentID) AS DepartmentID, 
       TimeClassID,
       UnitTypeID,
       BudgetPhaseID,
       COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount,
       MAX(FiscalMonthID) AS FiscalMonthID,
       COUNT(*) AS RecordsCount,
       SUM(RecordValue) AS TotalValue
       INTO #importAdjustments 
       FROM  (SELECT iadj.AdjustmentID,
                     TimeClassID,
                     BudgetPhaseID,
                     ISNULL(ORIGINALUNITTYPEID, UnitTypeID) AS UnitTypeID,
                     DepartmentID,
                     CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13
                          ELSE MAX(FiscalMonthID)
                     END AS FiscalMonthID,
                     SUM(Value) AS RecordValue
                     FROM fp.StaffingAdjustmentImport AS iadj WITH (NOLOCK)
                     JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
                     GROUP BY iadj.AdjustmentID,
                              TimeClassID,
                              BudgetPhaseID,
                              DepartmentID,
                              JobCodeID,
                              PayCodeGroupID,
                              --ProductiveClassID, Taken from PayCodeGroupID
                              VariabilityID,
                              --EntityID, Taken from Department
                              --EmployeeID, is zero for ProvComp
                              ProviderID,
                              --ProviderTypeID, Taken from provider
                              ProviderLineItemID,
                              --ProviderSpecialtyID, Taken from provider
                              ISNULL(ORIGINALUNITTYPEID, UnitTypeID)
                              ) AS ImportRecord
       GROUP BY AdjustmentID,
                TimeClassID,
                BudgetPhaseID,
                UnitTypeID
    
-- Creating indexes for faster selection
CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID)

INSERT INTO #src
    (BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted)
    SELECT @BudgetConfigID,
           @SectionID,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.[Value],
           res.AdjustedLevel,
           res.UnitTypeID,
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           res.Comment,
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           res.IsErrored,
           res.IsRecordDeleted
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
               *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.BudgetConfigGUID,
                   slea.AdjustmentType,
                   fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value,
                   fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   slea.Comment AS Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   slea.TimeClassID,
                   slea.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   slea.UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM   fp.StaffingAdjustment AS slea WITH (NOLOCK)
                   JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                   LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE  slea.AdjustmentType NOT IN (4, 15) 

            --Import
            UNION ALL

             SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID, sai.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                    slea.AdjustmentID,
                    slea.BudgetConfigGUID,
                    slea.AdjustmentType,
                    CASE WHEN sai.RecordsCount = 1 AND sai.UnitTypeID IN (144, 159) THEN '1 record affected'
                          WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType)
                          ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' 
                    END AS [Value],
                    CASE WHEN sai.DepartmentCount = 1 THEN d.Name
                         ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' 
                    END AS AdjustedLevel,
                    CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple')
                         ELSE 'Multiple'
                    END AS Months,
                    ag.Description AS Comment,
                    slea.AuthorFullName,
                    slea.LastModifiedDateUtc,
                    slea.DateCreatedUtc,
                    sai.TimeClassID,
                    sai.BudgetPhaseID,
                    slea.ClassificationGroupID,
                    slea.ClassificationCategoryID,
                    sai.UnitTypeID,
                    slea.IsRecordDeleted,
                    slea.IsErrored
            FROM    fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                    JOIN #importAdjustments AS sai ON sai.AdjustmentID = slea.AdjustmentID
                    JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID
                    LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
                    LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID
            WHERE   slea.AdjustmentType = 4 

            -- Add Provider adjustment
            UNION ALL
            
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, impact.TimeClassID, impact.BudgetPhaseID, impact.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.BudgetConfigGUID,
                   slea.AdjustmentType,
                   fp.GetAdjustmentReportValue(impact.ImpactValue, slea.AdjustmentType) AS Value,
                   phys.Physician AS AdjustedLevel,
                   'Multiple'  AS Months,
                   aps.Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   impact.TimeClassID,
                   impact.BudgetPhaseID,
                   aps.ClassificationGroupID,
                   aps.ClassificationCategoryID,
                   impact.UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                    JOIN fp.StatisticAddProviderSummary AS aps ON aps.StaffingAdjustmentGUID = slea.AdjustmentGUID
                    JOIN (SELECT SummaryID, ProjectionImpact AS ImpactValue, UnitTypeID, 12 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.ProvCompAddProviderSummaryDetails WITH (NOLOCK)
                          UNION ALL
                          SELECT SummaryID, COALESCE(NULLIF(BudgetImpact, 0), AnnualImpact) AS ImpactValue, UnitTypeID, 2 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.ProvCompAddProviderSummaryDetails WITH (NOLOCK)
                          UNION ALL
                          SELECT SummaryID, COALESCE(NULLIF(TargetImpact, 0), COALESCE(NULLIF(BudgetImpact, 0), AnnualImpact)) AS ImpactValue, UnitTypeID, 2 AS TimeClassID, 2 AS BudgetPhaseID FROM fp.ProvCompAddProviderSummaryDetails WITH (NOLOCK)
                          ) AS impact ON aps.SummaryID = impact.SummaryID
                    JOIN (SELECT SummaryID, SUM(ProjectionImpact) AS StatisticsImpact, 12 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) GROUP BY SummaryID
                          UNION ALL
                          SELECT SummaryID, SUM(TargetImpact) AS StatisticsImpact, 2 AS TimeClassID, 2 AS BudgetPhaseID FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) GROUP BY SummaryID
                          UNION ALL
                          SELECT SummaryID, SUM(BudgetImpact) AS StatisticsImpact, 2 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) GROUP BY SummaryID)
                          AS apsd ON apsd.SummaryID = impact.SummaryID AND apsd.TimeClassID = impact.TimeClassID AND apsd.BudgetPhaseID = impact.BudgetPhaseID 
                    JOIN dss.DimPhysician AS phys WITH (NOLOCK) ON phys.PhysicianID = aps.ProviderID
            WHERE slea.AdjustmentType = 15 AND apsd.StatisticsImpact <> 0 AND impact.ImpactValue <> 0
                  ) AS res_inner
             WHERE res_inner.RowNumber = 1) AS res
    ORDER BY res.DateCreatedUtc DESC

----------------------------------------------------------------------
-- Insert data to reportTable
----------------------------------------------------------------------

;WITH TGT AS 
(
    SELECT BudgetConfigID,
           SectionID,
           AdjustmentID,
           AdjustmentType,
           Months,
           AdjustmentValue,
           AdjustedLevel,
           UnitTypeID,
           TimeClassID,
           LastModifiedDateUtc,
           DateCreatedUtc,
           Comment,
           AuthorFullName,
           ClassificationGroupID,
           ClassificationCategoryID,
           IsErrored,
           IsRecordDeleted
    FROM fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID
          AND fr.SectionID = @SectionID
)
    MERGE TGT as target
    USING #src AS source
        ON (
            target.BudgetConfigID   = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID    = source.SectionID
            AND target.TimeClassID  = source.TimeClassID
            AND target.UnitTypeID   = source.UnitTypeID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                target.AdjustmentValue          = source.AdjustmentValue,
                target.IsErrored                = source.IsErrored,
                target.IsRecordDeleted          = source.IsRecordDeleted,
                target.ClassificationGroupID    = source.ClassificationGroupID,
                target.ClassificationCategoryID = source.ClassificationCategoryID,
                target.Comment                  = source.Comment
                                             
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                BudgetConfigID,
                SectionID,
                AdjustmentID,
                AdjustmentType,
                Months,
                AdjustmentValue,
                AdjustedLevel,
                UnitTypeID,
                TimeClassID,
                LastModifiedDateUtc,
                DateCreatedUtc,
                Comment,
                AuthorFullName,
                ClassificationGroupID,
                ClassificationCategoryID,
                IsErrored,
                IsRecordDeleted
            )
            VALUES (
                source.BudgetConfigID,
                source.SectionID,
                source.AdjustmentID,  
                source.AdjustmentType,  
                source.Months, 
                source.AdjustmentValue,
                source.AdjustedLevel,
                source.UnitTypeID,   
                source.TimeClassID,
                source.LastModifiedDateUtc,
                source.DateCreatedUtc,
                source.Comment,
                source.AuthorFullName,
                source.ClassificationGroupID,
                source.ClassificationCategoryID,
                source.IsErrored,
                source.IsRecordDeleted
            );
END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_Reimbursement
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1       2024-10-15   NH        JAZZ-74988  Adjustment history report 
 *************************************************************/
CREATE   PROCEDURE fp.procReportAdjustmentHistory_Reimbursement (
    @BudgetConfigID INT
)
AS 
BEGIN

EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 9
DECLARE @PlanSectionID INT = 7

CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

----------------------------------------------------------------------
--Get all adjustments
----------------------------------------------------------------------
SELECT rgla.AdjustmentID
INTO #adjustments
FROM fp.ReimbursementAdjustment AS rgla WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON rgla.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE rgla.BudgetConfigGUID = @BudgetGUID
      AND rgla.BudgetPhaseID <> 2
      AND (rgla.GroupingGUID = '00000000-0000-0000-0000-000000000000' OR rgla.AdjustmentType = 4)
      AND (rgla.LastModifiedDateUtc <> frah.LastModifiedDateUtc OR frah.LastModifiedDateUtc is NULL)

CREATE CLUSTERED INDEX PK_Adjustments ON #adjustments (AdjustmentID)
----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------
SELECT vrai.AdjustmentID, 
       vrai.UnitTypeID,
       vrai.TimeClassID,
       vrai.BudgetPhaseID,
       MIN(PayorGroupCount) AS PayorGroupCount,
       MIN(iadj.PayorGroupID) AS PayorGroupID,
       MIN(FiscalMonthName) AS FiscalMonthName,
       MIN(FiscalMonthCount) AS FiscalMonthCount,
       COUNT(*) AS RecordsCount
INTO #importAdjustments
FROM fp.viewReimbursementAdjustmentImport  vrai WITH (NOLOCK)
JOIN #adjustments AS adj ON vrai.AdjustmentID = adj.AdjustmentID
JOIN ( SELECT AdjustmentID,
              COUNT(DISTINCT PayorGroupID) AS PayorGroupCount,
              MAX(PayorGroupID) AS PayorGroupID,
              UnitTypeID,
              TimeClassID,
              BudgetPhaseID,
              COUNT(DISTINCT Name) AS FiscalMonthCount,
              MAX(Name) AS FiscalMonthName
       FROM   fp.viewReimbursementAdjustmentImport rai WITH (NOLOCK)
       UNPIVOT (Value For FiscalMonth IN (Value01, Value02, Value03,Value04, Value05, Value06, Value07,Value08, Value09, Value10, Value11, Value12)) as f
       LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'Value', 'Month')
       GROUP BY AdjustmentID, UnitTypeID, TimeClassID, BudgetPhaseID
) iadj ON vrai.AdjustmentID = iadj.AdjustmentID AND vrai.UnitTypeID = iadj.UnitTypeID AND vrai.TimeClassID = iadj.TimeClassID AND vrai.BudgetPhaseID = iadj.BudgetPhaseID
GROUP BY vrai.AdjustmentID,
         vrai.UnitTypeID,
         vrai.TimeClassID,
         vrai.BudgetPhaseID

CREATE CLUSTERED    INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID)
----------------------------------------------------------------------
--Build dto
----------------------------------------------------------------------
INSERT INTO #SRC
    (BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted)
    SELECT @BudgetConfigID,
           @SectionID,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.Value,
           AdjustedLevel,
           res.UnitTypeID,
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           res.Comment,
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           0,
           res.IsRecordDeleted  
    FROM (
            SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
                   *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value,
                   fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   slea.Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   slea.TimeClassID,
                   slea.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   slea.UnitTypeID,
                   slea.IsRecordDeleted
            FROM fp.ReimbursementAdjustment AS slea WITH (NOLOCK)
            JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
            LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE slea.AdjustmentType <> 4

                UNION ALL
        
          SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                 slea.AdjustmentID,
                 slea.AdjustmentType,
                 CASE WHEN sai.RecordsCount = 1 THEN '1 record affected'
                      ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' 
                 END AS [Value],
                 CASE WHEN sai.PayorGroupCount = 1 THEN pg.Name
                      ELSE CAST(sai.PayorGroupCount AS VARCHAR(30)) + ' payor groups' 
                 END AS AdjustedLevel,
                 CASE WHEN sai.FiscalMonthCount = 1 THEN FiscalMonthName
                      ELSE 'Multiple'
                 END AS Months,
                 ag.Description AS Comment,
                 slea.AuthorFullName,
                 slea.LastModifiedDateUtc,
                 slea.DateCreatedUtc,
                 sai.TimeClassID,
                 sai.BudgetPhaseID,
                 slea.ClassificationGroupID,
                 slea.ClassificationCategoryID,
                 sai.UnitTypeID,
                 slea.IsRecordDeleted
            FROM fp.ReimbursementAdjustment AS slea WITH (NOLOCK)
            JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
            JOIN #importAdjustments AS sai ON sai.AdjustmentID = slea.AdjustmentID
            JOIN fw.DimPayorGroup AS pg WITH (NOLOCK) ON pg.PayorGroupID = sai.PayorGroupID
            LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
            WHERE  slea.AdjustmentType = 4

            ) AS res_inner
        WHERE res_inner.RowNumber = 1 )  AS res
    WHERE res.RowNumber = 1

----------------------------------------------------------------------
-- Insert data to report cache table
----------------------------------------------------------------------
;WITH TGT AS 
(
    SELECT BudgetConfigID,
           SectionID,
           AdjustmentID,
           AdjustmentType,
           Months,
           AdjustmentValue,
           AdjustedLevel,
           UnitTypeID,
           TimeClassID,
           LastModifiedDateUtc,
           DateCreatedUtc,
           Comment,
           AuthorFullName,
           ClassificationGroupID,
           ClassificationCategoryID,
           IsErrored,
           IsRecordDeleted
    FROM fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID
          AND fr.SectionID = @SectionID
)
    MERGE TGT as target
    USING #SRC AS source
        ON (
            target.BudgetConfigID   = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID    = source.SectionID
            AND target.TimeClassID  = source.TimeClassID
            AND target.UnitTypeID   = source.UnitTypeID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                target.AdjustmentValue          = source.AdjustmentValue,
                target.IsErrored                = source.IsErrored,
                target.IsRecordDeleted          = source.IsRecordDeleted,
                target.ClassificationGroupID    = source.ClassificationGroupID,
                target.ClassificationCategoryID = source.ClassificationCategoryID,
                target.Comment                  = source.Comment
                                                 
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                BudgetConfigID,
                SectionID,
                AdjustmentID,
                AdjustmentType,
                Months,
                AdjustmentValue,
                AdjustedLevel,
                UnitTypeID,
                TimeClassID,
                LastModifiedDateUtc,
                DateCreatedUtc,
                Comment,
                AuthorFullName,
                ClassificationGroupID,
                ClassificationCategoryID,
                IsErrored,
                IsRecordDeleted
            )
            VALUES (
                source.BudgetConfigID,
                source.SectionID,
                source.AdjustmentID,  
                source.AdjustmentType,  
                source.Months, 
                source.AdjustmentValue,
                source.AdjustedLevel,
                source.UnitTypeID,   
                source.TimeClassID,
                source.LastModifiedDateUtc, 
                source.DateCreatedUtc,
                source.Comment,
                source.AuthorFullName,
                source.ClassificationGroupID,
                source.ClassificationCategoryID,
                source.IsErrored,
                source.IsRecordDeleted
            );


END;
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_ReimbursementGeneralLedger
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1       2024-10-15   NH        JAZZ-74988  Adjustment history report 
 *************************************************************/
CREATE   PROCEDURE fp.procReportAdjustmentHistory_ReimbursementGeneralLedger (
    @BudgetConfigID INT
)
AS
BEGIN 

EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'

CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 10
DECLARE @PlanSectionID INT = 7

----------------------------------------------------------------------
--Get all adjustments
----------------------------------------------------------------------
SELECT rgla.AdjustmentID
INTO #adjustments
FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON rgla.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE rgla.BudgetConfigGUID = @budgetGUID
      AND (rgla.GroupingGUID = '00000000-0000-0000-0000-000000000000' 
           OR rgla.AdjustmentType = 4)
      AND (rgla.LastModifiedDateUtc <> frah.LastModifiedDateUtc
           OR frah.LastModifiedDateUtc is NULL)

CREATE CLUSTERED INDEX PK_Adjustment ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------
SELECT impAdj.AdjustmentID, PayourGroupCount, PayorGroupID, TimeClassID, BudgetPhaseID, FiscalMonthCount, FiscalMonthName, RecordsCount
INTO   #importAdjustments
FROM (SELECT AdjustmentID,
      COUNT(DISTINCT PayorGroupID) AS PayourGroupCount,
      MAX(PayorGroupID) AS PayorGroupID,
      TimeClassID,
      BudgetPhaseID,
      COUNT(DISTINCT Name) AS FiscalMonthCount,
      MAX(Name) AS FiscalMonthName,
      COUNT(DISTINCT ROWID) AS RecordsCount,
      SUM(Value) AS RecordValue
      FROM   fp.ReimbursementGeneralLedgerAdjustmentImport rglai WITH (NOLOCK)
      UNPIVOT (Value For FiscalMonth IN (Value01, Value02, Value03,Value04, Value05, Value06, Value07,Value08, Value09, Value10, Value11, Value12)) as f
      LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'Value', 'Month')
      GROUP BY AdjustmentID,
               TimeClassID,
               BudgetPhaseID
      )  impAdj 
JOIN #adjustments adj ON impAdj.AdjustmentID = adj.AdjustmentID

CREATE CLUSTERED INDEX PK_ImportAdjustmen ON #importAdjustments (AdjustmentID)
----------------------------------------------------------------------
--Build dto
----------------------------------------------------------------------

INSERT INTO #src
    (BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted)
    SELECT @BudgetConfigID,
           @SectionID,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.Value,
           AdjustedLevel,
           34,  -- Dollars
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           res.Comment,
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           0, -- IsErrored
           res.IsRecordDeleted
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, *
        FROM (
            SELECT 
                ROW_NUMBER() OVER (PARTITION BY rgla.AdjustmentID ORDER BY rgla.DateCreatedUtc DESC) AS RowNumber,
                rgla.AdjustmentID,
                fp.GetAdjustmentReportValue(rgla.Value, rgla.AdjustmentType) AS VALUE,
                fp.GetAdjustmentPath(rgla.AdjustmentFilterJSON, rgla.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                ISNULL(dfm.Name, 'All')  AS Months,
                rgla.Comment,
                rgla.AuthorFullName,
                rgla.LastModifiedDateUtc,
                rgla.DateCreatedUtc,
                rgla.TimeClassID,
                rgla.BudgetPhaseID,
                rgla.ClassificationGroupID,
                rgla.ClassificationCategoryID,
                rgla.IsRecordDeleted,
                rgla.AdjustmentType
            FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK)
            JOIN #adjustments AS sleas ON sleas.AdjustmentID = rgla.AdjustmentID
            LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE rgla.AdjustmentType <> 4

        UNION ALL

        -- Import
          SELECT 
                ROW_NUMBER() OVER (PARTITION BY rgla.AdjustmentID, iadj.TimeClassID, iadj.BudgetPhaseID ORDER BY rgla.DateCreatedUtc DESC) AS RowNumber,
                rgla.AdjustmentID,
                CASE WHEN iadj.RecordsCount = 1 THEN '1 record affected'
                     ELSE CAST(iadj.RecordsCount AS VARCHAR(30)) + ' records affected' 
                END AS [Value],
                CASE WHEN iadj.PayourGroupCount = 1 THEN pg.Name
                        ELSE CAST(iadj.PayourGroupCount AS VARCHAR(30)) + ' payor groups' 
                END AS AdjustedLevel,
                CASE WHEN iadj.FiscalMonthCount = 1 THEN FiscalMonthName
                     ELSE 'Multiple'
                END AS Months,
                ag.Description AS Comment,
                rgla.AuthorFullName,
                rgla.LastModifiedDateUtc,
                rgla.DateCreatedUtc,
                iadj.TimeClassID,
                iadj.BudgetPhaseID,
                rgla.ClassificationGroupID,
                rgla.ClassificationCategoryID,
                rgla.IsRecordDeleted,
                rgla.AdjustmentType
            FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK)
            JOIN #importAdjustments  AS iadj ON iadj.AdjustmentID = rgla.AdjustmentID
            JOIN fw.DimPayorGroup AS pg WITH (NOLOCK) ON pg.PayorGroupID = iadj.PayorGroupID
            LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = rgla.GroupingGUID
            WHERE rgla.AdjustmentType = 4

        ) AS res_inner
        WHERE res_inner.RowNumber = 1) AS res
    WHERE res.RowNumber = 1
    ORDER BY res.DateCreatedUtc DESC

----------------------------------------------------------------------
-- Insert data to reportTable
----------------------------------------------------------------------
;WITH TGT AS 
(
    SELECT BudgetConfigID,
           SectionID,
           AdjustmentID,
           AdjustmentType,
           Months,
           AdjustmentValue,
           AdjustedLevel,
           UnitTypeID,
           TimeClassID,
           LastModifiedDateUtc,
           DateCreatedUtc,
           Comment,
           AuthorFullName,
           ClassificationGroupID,
           ClassificationCategoryID,
           IsErrored,
           IsRecordDeleted
    FROM fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID
          AND fr.SectionID = @SectionID
)
    MERGE TGT AS target
    USING #src AS source
        ON (
            target.BudgetConfigID   = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID    = source.SectionID
            AND target.TimeClassID  = source.TimeClassID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                target.AdjustmentValue          = source.AdjustmentValue,
                target.IsErrored                = source.IsErrored,
                target.IsRecordDeleted          = source.IsRecordDeleted,
                target.ClassificationGroupID    = source.ClassificationGroupID,
                target.ClassificationCategoryID = source.ClassificationCategoryID,
                target.Comment                  = source.Comment
                                                 
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                BudgetConfigID,
                SectionID,
                AdjustmentID,
                AdjustmentType,
                Months,
                AdjustmentValue,
                AdjustedLevel,
                UnitTypeID,
                TimeClassID,
                LastModifiedDateUtc,
                DateCreatedUtc,
                Comment,
                AuthorFullName,
                ClassificationGroupID,
                ClassificationCategoryID,
                IsErrored,
                IsRecordDeleted
            )
            VALUES (
                source.BudgetConfigID,
                source.SectionID,
                source.AdjustmentID,  
                source.AdjustmentType,  
                source.Months, 
                source.AdjustmentValue,
                source.AdjustedLevel,
                source.UnitTypeID,   
                source.TimeClassID,
                source.LastModifiedDateUtc, 
                source.DateCreatedUtc,
                source.Comment,
                source.AuthorFullName,
                source.ClassificationGroupID,
                source.ClassificationCategoryID,
                source.IsErrored,
                source.IsRecordDeleted
            );

END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_ServiceLine
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI              Description
 ** 1    2024-10-15  NH      JAZZ-74988      Adjustment history report 
 *************************************************************/
CREATE   PROCEDURE fp.procReportAdjustmentHistory_ServiceLine (
    @BudgetConfigID INT
) 
AS
BEGIN

EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'

CREATE TABLE #SRC (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

CREATE TABLE #adjustments (
    AdjustmentID INT
)

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 1
DECLARE @PlanSectionID INT = 1

----------------------------------------------------------------------
-- Get all adjustments
----------------------------------------------------------------------
INSERT INTO #adjustments
SELECT slea.AdjustmentID
FROM fp.ServiceLineEncounterAdjustment slea WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE slea.BudgetConfigGUID = @BudgetGUID 
      AND ((slea.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND slea.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments
           OR slea.AdjustmentType IN (1, 4, 10, 11, 12, 13, 14, 15))
      AND (slea.LastModifiedDateUtc <> frah.LastModifiedDateUtc 
           OR frah.LastModifiedDateUtc is NULL)

CREATE CLUSTERED INDEX PK_SecuredAdjustments ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
-- Get import adjustments
----------------------------------------------------------------------
SELECT AdjustmentID,
       COUNT(DISTINCT DepartmentID) AS DepartmentCount,
       MAX(DepartmentID) AS DepartmentID, 
       TimeClassID,
       UnitTypeID,
       BudgetPhaseID,
       COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount,
       MAX(FiscalMonthID) AS FiscalMonthID,
       COUNT(*) AS RecordsCount,
       SUM(RecordValue) AS TotalValue
       INTO #importAdjustments 
       FROM  (SELECT iadj.AdjustmentID,
                     TimeClassID,
                     BudgetPhaseID,
                     UnitTypeID,
                     DepartmentID,
                     CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13
                          ELSE MAX(FiscalMonthID)
                     END AS FiscalMonthID,
                     SUM(Value) AS RecordValue
                     FROM fp.ServiceLineEncounterAdjustmentImport AS iadj WITH (NOLOCK)
                     JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
                     GROUP BY iadj.AdjustmentID,
                              TimeClassID,
                              BudgetPhaseID,
                              EntityID,
                              PatientClassID,
                              ServiceLineID,
                              --ServiceLineRollupID, taken from ServiceLineID
                              AgeCohortID,
                              MedicalSurgicalID,
                              DepartmentID,
                              PayorID,
                              --PayorGroupID, taken from PayorID
                              MSDRGID,
                              CPTID,
                              ProviderID,
                              --PhysicianSpecialtyID, taken from Provider
                              UnitTypeID) AS ImportRecord
       GROUP BY AdjustmentID,
                TimeClassID,
                BudgetPhaseID,
                UnitTypeID


CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID)

INSERT INTO #SRC
    (BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted)
     SELECT @BudgetConfigID,
            @SectionID,
            res.AdjustmentID,
            res.AdjustmentType,
            res.Months,
            res.Value,
            res.AdjustedLevel,
            res.UnitTypeID,
            fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
            res.LastModifiedDateUtc,
            res.DateCreatedUtc,
            res.Comment,
            res.AuthorFullName,
            res.ClassificationGroupID,
            res.ClassificationCategoryID,
            res.IsErrored,
            res.IsRecordDeleted
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
               *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value,
                   fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   slea.Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   slea.TimeClassID,
                   slea.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   CAST(140 AS TINYINT) AS UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK)
                 JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                 LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE  slea.AdjustmentType NOT IN (4, 15)
                    
            UNION ALL   
            
            -- Import Adjustments
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   CASE WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType)
                        ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN sai.DepartmentCount = 1 THEN d.Name
                        ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple')
                        ELSE 'Multiple'
                   END AS Months,
                   ag.Description AS Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   sai.TimeClassID,
                   sai.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   CAST(140 AS TINYINT) AS UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK) 
                 JOIN #importAdjustments AS sai ON sai.AdjustmentID = slea.AdjustmentID
                 JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID 
                 LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
                 LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID
            WHERE slea.AdjustmentType = 4          

            -- Add Provider adjustments
            UNION ALL            

            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, aps.TimeClassID ORDER BY slea.DateCreatedUTC DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   fp.GetAdjustmentReportValue(aps.Total, slea.AdjustmentType) AS Value,
                   phys.Physician AS AdjustedLevel,
                   'Multiple',
                   aps.Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUTC,
                   aps.TimeClassID,
                   2 AS BudgetPhaseID,
                   aps.ClassificationGroupID,
                   aps.ClassificationCategoryID,
                   140 AS UnitTypeID,              
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK)            
                 JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                 JOIN (SELECT SLEncounterAdjustmentGUID, 
                              ProviderID,
                              Comment,
                              ClassificationGroupID,
                              ClassificationCategoryID,
                              ProjectionTotal AS Total,
                              12 AS TimeClassID
                       FROM fp.AddProviderSummary  WITH (NOLOCK) 
                       UNION ALL
                       SELECT SLEncounterAdjustmentGUID,
                              ProviderID,
                              Comment,
                              ClassificationGroupID,
                              ClassificationCategoryID,
                              BudgetTotal AS Total,
                              2 AS TimeClassID
                       FROM fp.AddProviderSummary WITH (NOLOCK)) AS aps ON aps.SLEncounterAdjustmentGUID = slea.AdjustmentGUID
                 JOIN dss.DimPhysician AS phys ON phys.PhysicianID = aps.ProviderID
            WHERE slea.AdjustmentType = 15
            ) AS res_inner
        WHERE res_inner.RowNumber = 1 ) AS res
    ORDER BY res.DateCreatedUtc DESC
    
----------------------------------------------------------------------
-- Insert data to report Table
----------------------------------------------------------------------
;WITH TGT AS 
(
    SELECT BudgetConfigID,
           SectionID,
           AdjustmentID,
           AdjustmentType,
           Months,
           AdjustmentValue,
           AdjustedLevel,
           UnitTypeID,
           TimeClassID,
           LastModifiedDateUtc,
           DateCreatedUtc,
           Comment,
           AuthorFullName,
           ClassificationGroupID,
           ClassificationCategoryID,
           IsErrored,
           IsRecordDeleted
    FROM fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID
          AND fr.SectionID = @SectionID
)
    MERGE TGT as target
    USING #src AS source
        ON (
            target.BudgetConfigID   = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID    = source.SectionID
            AND target.TimeClassID  = source.TimeClassID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                target.AdjustmentValue          = source.AdjustmentValue,
                target.IsErrored                = source.IsErrored,
                target.IsRecordDeleted          = source.IsRecordDeleted,
                target.ClassificationGroupID    = source.ClassificationGroupID,
                target.ClassificationCategoryID = source.ClassificationCategoryID,
                target.Comment                  = source.Comment
                                                 
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                BudgetConfigID,
                SectionID,
                AdjustmentID,
                AdjustmentType,
                Months,
                AdjustmentValue,
                AdjustedLevel,
                UnitTypeID,
                TimeClassID,
                LastModifiedDateUtc,
                DateCreatedUtc,
                Comment,
                AuthorFullName,
                ClassificationGroupID,
                ClassificationCategoryID,
                IsErrored,
                IsRecordDeleted
            )
            VALUES (
                source.BudgetConfigID,
                source.SectionID,
                source.AdjustmentID,  
                source.AdjustmentType,  
                source.Months, 
                source.AdjustmentValue,
                source.AdjustedLevel,
                source.UnitTypeID,   
                source.TimeClassID,
                source.LastModifiedDateUtc, 
                source.DateCreatedUtc,
                source.Comment,
                source.AuthorFullName,
                source.ClassificationGroupID,
                source.ClassificationCategoryID,
                source.IsErrored,
                source.IsRecordDeleted
            );

END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_Staffing
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1       2024-10-15   NH       JAZZ-74988  Adjustment history report 
 *************************************************************/

CREATE   PROCEDURE fp.procReportAdjustmentHistory_Staffing (
    @BudgetConfigID INT
)
AS
BEGIN
 
EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'
 
CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

CREATE TABLE #adjustments (
    AdjustmentID INT
)

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID INT = 5
DECLARE @PlanSectionID INT = 4

----------------------------------------------------------------------
--Get all adjustments
----------------------------------------------------------------------
INSERT INTO #adjustments
SELECT slea.AdjustmentID
FROM fp.StaffingAdjustment slea WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE slea.BudgetConfigGUID = @budgetGUID
      AND slea.SubsectionID = 3
      AND (slea.AdjustmentType = 6
           OR  (
                ((slea.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND slea.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments
                   OR slea.AdjustmentType IN (1, 4, 5, 8,10, 11, 12, 13, 14, 17, 20))
                 AND (slea.LastModifiedDateUtc <> frah.LastModifiedDateUtc OR frah.LastModifiedDateUtc is NULL))
           )
     
CREATE CLUSTERED    INDEX PK_Adjustmnets ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------
SELECT AdjustmentID,
       COUNT(DISTINCT DepartmentID) AS DepartmentCount,
       MAX(DepartmentID) AS DepartmentID, 
       TimeClassID,
       UnitTypeID,
       BudgetPhaseID,
       COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount,
       MAX(FiscalMonthID) AS FiscalMonthID,
       COUNT(*) AS RecordsCount,
       SUM(RecordValue) AS TotalValue
       INTO #importAdjustments 
       FROM  (SELECT iadj.AdjustmentID,
                     TimeClassID,
                     BudgetPhaseID,
                     ISNULL(ORIGINALUNITTYPEID, UnitTypeID) AS UnitTypeID,
                     DepartmentID,
                     CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13
                          ELSE MAX(FiscalMonthID)
                     END AS FiscalMonthID,
                     SUM(Value) AS RecordValue
                     FROM fp.StaffingAdjustmentImport AS iadj WITH (NOLOCK)
                     JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
                     GROUP BY iadj.AdjustmentID,
                              TimeClassID,
                              BudgetPhaseID,
                              DepartmentID,
                              JobCodeID,
                              PayCodeGroupID,
                              --ProductiveClassID, Taken from PayCodeGroupID
                              VariabilityID,
                              --EntityID, Taken from Department
                              EmployeeID,
                              --ProviderID, not used in Staffing
                              --ProviderTypeID, not used in Staffing
                              --ProviderLineItemID, not used in Staffing
                              --ProviderSpecialtyID, not used in Staffing
                              ISNULL(ORIGINALUNITTYPEID, UnitTypeID)
                              ) AS ImportRecord
       GROUP BY AdjustmentID,
                TimeClassID,
                BudgetPhaseID,
                UnitTypeID

-- Creating indexes for faster selection
CREATE CLUSTERED    INDEX PK_ImportAdjustmets ON #importAdjustments (AdjustmentID, UnitTypeID)

INSERT INTO #src
    (BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted)
    SELECT @BudgetConfigID,
           @SectionID,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.[Value],
           res.AdjustedLevel,
           res.UnitTypeID,
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           res.Comment,
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           res.IsErrored,
           res.IsRecordDeleted
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
               *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value,
                   fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   slea.Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   slea.TimeClassID,
                   slea.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   slea.UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM    fp.StaffingAdjustment AS slea WITH (NOLOCK)
                    JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                    LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE   slea.AdjustmentType NOT IN (4,6, 17, 20)

            UNION ALL

            -- IMPORT
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID, sai.UnitTypeID  ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   CASE WHEN sai.RecordsCount = 1 AND sai.UnitTypeID IN (144, 159, 172) THEN '1 record affected'
                        WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType)
                        ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN sai.DepartmentCount = 1 THEN d.Name
                        ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple')
                        ELSE 'Multiple'
                   END AS Months,
                   ISNULL(ag.[Description], slea.Comment) AS Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   sai.TimeClassID,
                   sai.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   sai.UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM fp.StaffingAdjustment AS slea WITH (NOLOCK)                      
                    JOIN #importAdjustments  AS sai ON sai.AdjustmentID = slea.AdjustmentID
                    JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID
                    LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
                    LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID
            WHERE   slea.AdjustmentType = 4

            UNION ALL
            
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.GroupingGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   CAST(fte.FTEAmount AS VARCHAR(30)) + ' FTEs Added' AS [Value],
                   CASE WHEN DepartmentCount = 1 THEN DepartmentName
                        ELSE CAST(DepartmentCount AS VARCHAR(30)) + ' departments'
                   END AS AdjustedLevel,
                   'Multiple' AS Months,
                   CASE WHEN CommentCount = 0 THEN fte.FTEComment
                        WHEN CommentCount = 1 THEN fte.FTEComment
                        ELSE 'Multiple Comments'
                   END AS Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   slea.TimeClassID,
                   slea.BudgetPhaseID,
                   0 AS ClassificationGroupID,
                   0 AS ClassificationCategoryID,
                   144 AS UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM    (
                        SELECT 
                             slea_inner.GroupingGUID AS AdjustmentGUID,
                             MIN(slea_inner.AdjustmentID) AS AdjustmentID,
                             slea_inner.AdjustmentType,
                             slea_inner.AuthorFullName,
                             MAX(slea_inner.LastModifiedDateUtc) AS LastModifiedDateUtc, 
                             MIN(slea_inner.DateCreatedUtc) AS DateCreatedUtc,
                             slea_inner.GroupingGUID,
                             slea_inner.TimeClassID,
                             slea_inner.BudgetPhaseID,
                             slea_inner.IsRecordDeleted,
                             slea_inner.IsErrored
                        FROM fp.StaffingAdjustment AS slea_inner WITH (NOLOCK)
                             JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea_inner.AdjustmentID
                        WHERE AdjustmentType = 6
                        GROUP BY
                            slea_inner.GroupingGUID,
                            slea_inner.AdjustmentType,
                            slea_inner.AuthorFullName,
                            slea_inner.DateCreatedUtc,
                            slea_inner.GroupingGUID,
                            slea_inner.TimeClassID,
                            slea_inner.BudgetPhaseID,
                            slea_inner.IsRecordDeleted,
                            slea_inner.IsErrored
                        ) AS slea
                    JOIN ( 
                        SELECT 
                              MIN(dept.[Name]) AS DepartmentName,
                              OBJ.GroupingGUID,
                              COUNT(DISTINCT OBJ.DepartmentID) AS DepartmentCount,
                              CAST(SUM(OBJ.FTEAmount) AS DECIMAL(19,2)) AS FTEAmount,
                              MAX(OBJ.Comment) AS FTEComment,
                              SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentCount
                        FROM  fp.FTERequest AS OBJ WITH (NOLOCK)
                              JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID
                        GROUP BY 
                            OBJ.GroupingGUID
                    ) AS fte ON fte.GroupingGUID = slea.GroupingGUID
                          
            UNION ALL
            
            -- ManagerSet (new My Budgets) Adjustments 
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, adjComment.TimeClassID, adjComment.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   CASE WHEN adjComment.RecordsChanged = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType)
                        ELSE CAST(adjComment.RecordsChanged AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   dept.Name AS AdjustedLevel,
                   'All' AS Months,
                   CASE WHEN adjComment.CommentCount = 0 THEN adjComment.CommentTotal
                        WHEN adjComment.CommentCount = 1 THEN adjComment.CommentTotal
                        ELSE 'Multiple Comments'
                   END AS Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   adjComment.TimeClassID,
                   slea.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   adjComment.UnitTypeId,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM fp.StaffingAdjustment AS slea WITH (NOLOCK)
                 JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                 JOIN (SELECT AdjustmentID,
                              DepartmentID,
                              UnitTypeID,
                              TimeClassID,
                              MAX(Comment) AS CommentTotal,
                              SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentCount,
                              SUM(Value) AS TotalValue,
                              COUNT(*) AS RecordsChanged
                       FROM fp.StaffingManagerSetAdjustmentComment
                       GROUP BY AdjustmentID,
                                DepartmentID,
                                UnitTypeID,
                                TimeClassID
                    ) AS adjComment ON slea.AdjustmentID = adjComment.AdjustmentID
                 JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = adjComment.DepartmentID 
            WHERE slea.AdjustmentType = 20
                        
            UNION ALL
            
              -- NPE Add Employee Adjustments 
            SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber,
                   slea.AdjustmentID,
                   slea.AdjustmentType,
                   emp.Name AS [Value],
                   dept.Name AS AdjustedLevel,
                   'Multiple' AS Months,
                   slea.Comment AS Comment,
                   slea.AuthorFullName,
                   slea.LastModifiedDateUtc,
                   slea.DateCreatedUtc,
                   smad.TimeClassID,
                   slea.BudgetPhaseID,
                   slea.ClassificationGroupID,
                   slea.ClassificationCategoryID,
                   144 AS UnitTypeID,
                   slea.IsRecordDeleted,
                   slea.IsErrored
            FROM fp.StaffingAdjustment AS slea WITH (NOLOCK)
                 JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID
                 JOIN fp.StaffingManagerAdjustmentData smad WITH (NOLOCK) ON slea.AdjustmentGUID = smad.AdjustmentGUID
                 JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = smad.DepartmentID
                 JOIN fw.DimEmployee AS emp WITH (NOLOCK) ON smad.EmployeeID = emp.EmployeeID
            WHERE slea.AdjustmentType = 17
                  ) AS res_inner
                  -- Selecting only unique adjustments
             WHERE res_inner.RowNumber = 1) AS res
    ORDER BY res.DateCreatedUtc DESC

    -- Insert data to reportTable

    ;WITH TGT AS 
    (
        SELECT BudgetConfigID,
               SectionID,
               AdjustmentID,
               AdjustmentType,
               Months,
               AdjustmentValue,
               AdjustedLevel,
               UnitTypeID,
               TimeClassID,
               LastModifiedDateUtc,
               DateCreatedUtc,
               Comment,
               AuthorFullName,
               ClassificationGroupID,
               ClassificationCategoryID,
               IsErrored,
               IsRecordDeleted
        FROM fp.FactReportAdjustmentHistory fr
        WHERE fr.BudgetConfigID = @BudgetConfigID
              AND fr.SectionID = @SectionID
    )
        MERGE TGT AS target
        USING #src AS source
            ON (
                target.BudgetConfigID   = source.BudgetConfigID
                AND target.AdjustmentID = source.AdjustmentID
                AND target.SectionID    = source.SectionID
                AND target.TimeClassID  = source.TimeClassID
                AND target.UnitTypeID   = source.UnitTypeID
            )
        WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
            THEN
                UPDATE
                SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                    target.AdjustmentValue          = source.AdjustmentValue,
                    target.IsErrored                = source.IsErrored,
                    target.IsRecordDeleted          = source.IsRecordDeleted,
                    target.ClassificationGroupID    = source.ClassificationGroupID,
                    target.ClassificationCategoryID = source.ClassificationCategoryID,
                    target.Comment                  = source.Comment
                                                 
        WHEN NOT MATCHED BY TARGET
            THEN
                INSERT (
                    BudgetConfigID,
                    SectionID,
                    AdjustmentID,
                    AdjustmentType,
                    Months,
                    AdjustmentValue,
                    AdjustedLevel,
                    UnitTypeID,
                    TimeClassID,
                    LastModifiedDateUtc,
                    DateCreatedUtc,
                    Comment,
                    AuthorFullName,
                    ClassificationGroupID,
                    ClassificationCategoryID,
                    IsErrored,
                    IsRecordDeleted
                )
                VALUES (
                    source.BudgetConfigID,
                    source.SectionID,
                    source.AdjustmentID,  
                    source.AdjustmentType,  
                    source.Months, 
                    source.AdjustmentValue,
                    source.AdjustedLevel,
                    source.UnitTypeID,   
                    source.TimeClassID,
                    source.LastModifiedDateUtc, 
                    source.DateCreatedUtc,
                    source.Comment,
                    source.AuthorFullName,
                    source.ClassificationGroupID,
                    source.ClassificationCategoryID,
                    source.IsErrored,
                    source.IsRecordDeleted
                );
                
-- clean up Add FTE
DELETE frah FROM fp.FactReportAdjustmentHistory frah
LEFT JOIN fp.StaffingAdjustment slea ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID
WHERE frah.AdjustmentType = 6 AND slea.AdjustmentID  IS NULL 
END
GO


---------------------------------------------

-- fp.procReportAdjustmentHistory_Statistics
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI             Description
 ** 1    2024-10-15  NH      JAZZ-74988     Adjustment history report 
 *************************************************************/
CREATE   PROCEDURE fp.procReportAdjustmentHistory_Statistics (
    @BudgetConfigID INT
) 
AS
BEGIN

EXEC [dbo].[procSysDropTempTable] '#src'
EXEC [dbo].[procSysDropTempTable] '#adjustments'
EXEC [dbo].[procSysDropTempTable] '#importAdjustments'

DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID)
DECLARE @SectionID_Driver INT = 3
DECLARE @SectionID_Dependent INT = 4
DECLARE @PlanSectionID INT = 3

CREATE TABLE #src (
    BudgetConfigID           INT,
    SectionID                INT,
    AdjustmentID             INT,
    AdjustmentType           TINYINT, 
    Months                   NVARCHAR(50),
    AdjustmentValue          NVARCHAR(MAX),
    AdjustedLevel            NVARCHAR(MAX),
    UnitTypeID               TINYINT,
    TimeClassID              TINYINT,
    LastModifiedDateUtc      DATETIME,
    DateCreatedUtc           DATETIME,
    Comment                  NVARCHAR(MAX),
    AuthorFullName           NVARCHAR(260),
    ClassificationGroupID    INT,
    ClassificationCategoryID INT,
    IsErrored                BIT,
    IsRecordDeleted          BIT
)

----------------------------------------------------------------------
--Get all adjustments
----------------------------------------------------------------------
SELECT sa.AdjustmentID
INTO #adjustments
FROM fp.StatisticsAdjustment sa WITH (NOLOCK)
LEFT JOIN fp.FactReportAdjustmentHistory frah ON sa.AdjustmentID = frah.AdjustmentID AND frah.SectionID IN (@SectionID_Driver, @SectionID_Dependent)
WHERE sa.BudgetConfigGUID = @BudgetGUID
      AND (
           (sa.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND sa.AdjustmentType IN (0, 2, 3))  -- filter roll up adjustments
            OR sa.AdjustmentType IN (1, 4, 10, 11, 12, 13, 14, 15)
           )
      AND (sa.LastModifiedDateUtc <> frah.LastModifiedDateUtc 
           OR frah.LastModifiedDateUtc IS NULL)
        
CREATE CLUSTERED INDEX PK_Adjustments ON #adjustments (AdjustmentID)

----------------------------------------------------------------------
--Get import adjustments
----------------------------------------------------------------------
SELECT AdjustmentID,
       COUNT(DISTINCT DepartmentID) AS DepartmentCount,
       MAX(DepartmentID) AS DepartmentID, 
       TimeClassID,
       BudgetPhaseID,
       UnitTypeID,
       COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount,
       MAX(FiscalMonthID) AS FiscalMonthID,
       COUNT(*) AS RecordsCount,
       SUM(RecordValue) AS TotalValue
       INTO #importAdjustments 
       FROM  (SELECT iadj.AdjustmentID,
                     TimeClassID,
                     BudgetPhaseID,
                     UnitTypeID,
                     DepartmentID,
                     SUM(Value) AS RecordValue,
                     CASE WHEN COUNT(DISTINCT FiscalMonthID)> 1 THEN 13
                          ELSE MIN(FiscalMonthID)
                     END AS FiscalMonthID
                     FROM fp.StatisticsAdjustmentImport AS iadj WITH (NOLOCK)
                     JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID
                     GROUP BY iadj.AdjustmentID,
                              TimeClassID,
                              BudgetPhaseID,
                              DepartmentID,
                              EntityID,
                              AccountID,
                              FinancialReportingID,
                              PayorID,
                              PatientClassID,
                              UnitTypeID,
                              ProviderID,
                              ProviderLineItemID,
                              ProviderSpecialtyID,
                              ProviderTypeID) AS ImportRecord
       GROUP BY AdjustmentID,
                TimeClassID, 
                BudgetPhaseID, 
                UnitTypeID

CREATE CLUSTERED   INDEX PK_ImportAdjustments ON #importAdjustments (AdjustmentID, UnitTypeID)

INSERT INTO #src
    (BudgetConfigID,
     SectionID,
     AdjustmentID,
     AdjustmentType,
     Months,
     AdjustmentValue,
     AdjustedLevel,
     UnitTypeID,
     TimeClassID,
     LastModifiedDateUtc,
     DateCreatedUtc,
     Comment,
     AuthorFullName,
     ClassificationGroupID,
     ClassificationCategoryID,
     IsErrored,
     IsRecordDeleted)
    SELECT @BudgetConfigID,
           CASE WHEN res.SubsectionID = 1 THEN @SectionID_Driver
                ELSE @SectionID_Dependent
           END,
           res.AdjustmentID,
           res.AdjustmentType,
           res.Months,
           res.[Value],
           res.AdjustedLevel,
           140,
           fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID),
           res.LastModifiedDateUtc,
           res.DateCreatedUtc,
           res.Comment,
           res.AuthorFullName,
           res.ClassificationGroupID,
           res.ClassificationCategoryID,
           res.IsErrored,
           res.IsRecordDeleted
    FROM (
        SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount,
               *
        FROM (
            SELECT ROW_NUMBER() OVER (PARTITION BY sa.AdjustmentID ORDER BY sa.DateCreatedUtc DESC) AS RowNumber,
                   sa.AdjustmentID,
                   sa.AdjustmentType,
                   fp.GetAdjustmentReportValue(sa.Value, sa.AdjustmentType) AS Value,
                   fp.GetAdjustmentPath(sa.AdjustmentFilterJSON, sa.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel,
                   ISNULL(dfm.Name, 'All')  AS Months,
                   sa.Comment,
                   sa.AuthorFullName,
                   sa.LastModifiedDateUtc,
                   sa.DateCreatedUtc,
                   sa.SubsectionID,
                   sa.TimeClassID,
                   sa.BudgetPhaseID,
                   sa.ClassificationGroupID,
                   sa.ClassificationCategoryID,
                   CAST(140 AS TINYINT) AS UnitTypeID,
                   sa.IsErrored,
                   sa.IsRecordDeleted
            FROM fp.StatisticsAdjustment AS sa WITH (NOLOCK)
                 JOIN #adjustments AS sadj ON sadj.AdjustmentID = sa.AdjustmentID                            
                 LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT)
            WHERE sa.AdjustmentType IN (0, 1, 2, 3, 10, 11, 12, 13, 14)

            UNION ALL 

            -- Import Adjustments
            SELECT ROW_NUMBER() OVER (PARTITION BY sa.AdjustmentID, iadj.BudgetPhaseID  ORDER BY sa.DateCreatedUtc DESC) AS RowNumber,
                   sa.AdjustmentID,
                   sa.AdjustmentType,
                   CASE WHEN iadj.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, sa.AdjustmentType)
                        ELSE CAST(iadj.RecordsCount AS VARCHAR(30)) + ' records affected' 
                   END AS [Value],
                   CASE WHEN iadj.DepartmentCount = 1 THEN d.Name
                        ELSE CAST(iadj.DepartmentCount AS VARCHAR(30)) + ' departments' 
                   END AS AdjustedLevel,
                   CASE WHEN iadj.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple')
                        ELSE 'Multiple'
                   END AS Months,
                   ag.Description AS Comment,
                   sa.AuthorFullName,
                   sa.LastModifiedDateUtc,
                   sa.DateCreatedUtc,
                   sa.SubsectionID,
                   iadj.TimeClassID,
                   iadj.BudgetPhaseID,
                   sa.ClassificationGroupID,
                   sa.ClassificationCategoryID,
                   iadj.UnitTypeID,
                   sa.IsErrored,
                   sa.IsRecordDeleted
            FROM  fp.StatisticsAdjustment AS sa WITH (NOLOCK) 
                  JOIN #importAdjustments AS iadj ON iadj.AdjustmentID = sa.AdjustmentID 
                  JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = sa.GroupingGUID
                  JOIN fw.DimDepartment AS d WITH (NOLOCK) ON iadj.DepartmentID = d.DepartmentID
                  LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on iadj.FiscalMonthID = dfm.FiscalMonthID
            WHERE sa.AdjustmentType = 4

            -- Add Provider adjustments
            UNION ALL            

            SELECT ROW_NUMBER() OVER (PARTITION BY sa.AdjustmentID, apsd.TimeClassID, apsd.BudgetPhaseID ORDER BY sa.DateCreatedUtc DESC) AS RowNumber,
                  sa.AdjustmentID,
                  sa.AdjustmentType,
                  fp.GetAdjustmentReportValue(apsd.Impact, sa.AdjustmentType)  AS Value,
                  phys.Physician AS AdjustedLevel,
                  'Multiple'  AS Months,
                  aps.Comment,
                  sa.AuthorFullName,
                  sa.LastModifiedDateUtc,
                  sa.DateCreatedUtc,
                  sa.SubsectionID,
                  apsd.TimeClassID,
                  apsd.BudgetPhaseID,
                  aps.ClassificationGroupID,
                  aps.ClassificationCategoryID,
                  140 AS UnitTypeID,
                  sa.IsErrored,
                  sa.IsRecordDeleted
            FROM  fp.StatisticsAdjustment AS sa WITH (NOLOCK)            
                  JOIN #adjustments AS adj ON adj.AdjustmentID = sa.AdjustmentID
                  JOIN fp.StatisticAddProviderSummary AS aps ON aps.DriverAdjustmentGUID = sa.AdjustmentGUID
                  JOIN (SELECT SummaryID,
                        SUM(ProjectionImpact) AS Impact,
                        12 AS TimeClassID,
                        2 AS BudgetPhaseID 
                        FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK)
                        GROUP BY SummaryID
                          UNION ALL
                        SELECT SummaryID,
                        SUM(TargetImpact) AS Impact,
                        2 AS TimeClassID,
                        2 AS BudgetPhaseID 
                        FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK)
                        GROUP BY SummaryID
                          UNION ALL
                        SELECT SummaryID, 
                        SUM(BudgetImpact) AS Impact, 
                        2 AS TimeClassID, 
                        3 AS BudgetPhaseID 
                        FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK)
                        GROUP BY SummaryID) AS apsd ON aps.SummaryID = apsd.SummaryID
                    JOIN dss.DimPhysician AS phys  WITH (NOLOCK) ON phys.PhysicianID = aps.ProviderID
             WHERE sa.AdjustmentType = 15  AND Impact <> 0
            ) AS res_inner
        WHERE res_inner.RowNumber = 1 ) AS res
    ORDER BY res.DateCreatedUtc DESC      

----------------------------------------------------------------------
-- Insert data to reportTable
----------------------------------------------------------------------
;WITH TGT AS 
(
    SELECT BudgetConfigID,
    SectionID,
    AdjustmentID,
    AdjustmentType,
    Months,
    AdjustmentValue,
    AdjustedLevel,
    UnitTypeID,
    TimeClassID,
    LastModifiedDateUtc,
    DateCreatedUtc,
    Comment,
    AuthorFullName,
    ClassificationGroupID,
    ClassificationCategoryID,
    IsErrored,
    IsRecordDeleted
    FROM fp.FactReportAdjustmentHistory fr
    WHERE fr.BudgetConfigID = @BudgetConfigID
          AND fr.SectionID IN (@SectionID_Driver, @SectionID_Dependent)
)
    MERGE TGT AS target
    USING #src AS source
        ON (
            target.BudgetConfigID = source.BudgetConfigID
            AND target.AdjustmentID = source.AdjustmentID
            AND target.SectionID = source.SectionID
            AND target.TimeClassID = source.TimeClassID
        )
    WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc)
        THEN
            UPDATE
            SET target.LastModifiedDateUtc      = source.LastModifiedDateUtc,
                target.AdjustmentValue          = source.AdjustmentValue,
                target.IsErrored                = source.IsErrored,
                target.IsRecordDeleted          = source.IsRecordDeleted,
                target.ClassificationGroupID    = source.ClassificationGroupID,
                target.ClassificationCategoryID = source.ClassificationCategoryID,
                target.Comment                  = source.Comment
                                                 
    WHEN NOT MATCHED BY TARGET
        THEN
            INSERT (
                BudgetConfigID,
                SectionID,
                AdjustmentID,
                AdjustmentType,
                Months,
                AdjustmentValue,
                AdjustedLevel,
                UnitTypeID,
                TimeClassID,
                LastModifiedDateUtc,
                DateCreatedUtc,
                Comment,
                AuthorFullName,
                ClassificationGroupID,
                ClassificationCategoryID,
                IsErrored,
                IsRecordDeleted
            )
            VALUES (
                source.BudgetConfigID,
                source.SectionID,
                source.AdjustmentID,
                source.AdjustmentType, 
                source.Months,
                source.AdjustmentValue,
                source.AdjustedLevel,
                source.UnitTypeID,   
                source.TimeClassID,
                source.LastModifiedDateUtc, 
                source.DateCreatedUtc,
                source.Comment,
                source.AuthorFullName,
                source.ClassificationGroupID,
                source.ClassificationCategoryID,
                source.IsErrored,
                source.IsRecordDeleted
            );


END
GO


---------------------------------------------

-- fp.procReportCacheToggle
CREATE proc fp.procReportCacheToggle
	@isEnabled bit
as
	--disable proc logic
	update fp.SystemSetting set Value = @isEnabled where Name = 'AP Report Cache Auto-Refresh';

	if (@isEnabled = 0) begin
		--make report datasources pull data live
		exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted AS SELECT * FROM fp.viewFactGeneralLedger_Unpivoted_source WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted AS SELECT * FROM fp.viewFactGeneralLedgerHistory_Unpivoted_source WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactStaffing_Unpivoted AS SELECT * FROM fp.viewFactStaffing_Unpivoted_source');
		exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted AS SELECT * FROM fp.viewFactStaffingHistory_Unpivoted_source');
		exec('ALTER VIEW fp.viewFactStatistics_Unpivoted AS SELECT * FROM fp.viewFactStatistics_Unpivoted_source');
		exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted AS SELECT * FROM fp.viewFactStatisticsHistory_Unpivoted_source');
		exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted_archive AS SELECT * FROM fp.viewFactGeneralLedger_Unpivoted_source WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted_archive AS SELECT * FROM fp.viewFactGeneralLedgerHistory_Unpivoted_source WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactStaffing_Unpivoted_archive AS SELECT * FROM fp.viewFactStaffing_Unpivoted_source');
		exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted_archive AS SELECT * FROM fp.viewFactStaffingHistory_Unpivoted_source');
		exec('ALTER VIEW fp.viewFactStatistics_Unpivoted_archive AS SELECT * FROM fp.viewFactStatistics_Unpivoted_source');
		exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted_archive AS SELECT * FROM fp.viewFactStatisticsHistory_Unpivoted_source');

		--make built-in IS report available, hide ad hoc IS report
		update dbo.REReport set Name = 'Advanced Planning Income Statement' where ReportGUID = 'B58061D1-B9AB-446D-8C19-2545B2E5C190';
		update fp.SystemSetting set Value = 'B58061D1-B9AB-446D-8C19-2545B2E5C190' where Name ='AP Income Statement Report';
		update dbo.REReport set Name = '(Archived) Advanced Planning Income Statement' where ReportGUID = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D';
		delete from dbo.S3SimplePermission where LootID in('B58061D1-B9AB-446D-8C19-2545B2E5C190', '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D');
		insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('B58061D1-B9AB-446D-8C19-2545B2E5C190', 'F27A1CAA-8C07-4093-8990-A865BD82EDF2', 1, 0, 0);
		insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('B58061D1-B9AB-446D-8C19-2545B2E5C190', 'F314A324-D974-4F50-B26A-C89B8C1C5138', 1, 1, 0);
	end else begin
		--make report datasources pull data from cache
		exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted AS SELECT * FROM fp.FactReportGeneralLedger WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted AS SELECT * FROM fp.FactReportGeneralLedgerHistory WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactStaffing_Unpivoted AS SELECT * FROM fp.FactReportStaffing');
		exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted AS SELECT * FROM fp.FactReportStaffingHistory');
		exec('ALTER VIEW fp.viewFactStatistics_Unpivoted AS SELECT * FROM fp.FactReportStatistics');
		exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted AS SELECT * FROM fp.FactReportStatisticsHistory');
		exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedger_archive WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedgerHistory_archive WHERE UnitTypeID = 34');
		exec('ALTER VIEW fp.viewFactStaffing_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffing_archive');
		exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffingHistory_archive');
		exec('ALTER VIEW fp.viewFactStatistics_Unpivoted_archive AS SELECT * FROM fp.FactReportStatistics_archive');
		exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStatisticsHistory_archive');

		--make ad hoc IS report available, hide built-in IS report
		update dbo.REReport set Name = 'Advanced Planning Income Statement' where ReportGUID = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D';
		update fp.SystemSetting set Value = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D' where Name ='AP Income Statement Report';
		update dbo.REReport set Name = '(Archived) Advanced Planning Income Statement' where ReportGUID = 'B58061D1-B9AB-446D-8C19-2545B2E5C190';
		delete from dbo.S3SimplePermission where LootID in('B58061D1-B9AB-446D-8C19-2545B2E5C190', '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D');
		insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('04B7FB79-05D3-4DC4-BA44-9EC64990DF3D', 'F27A1CAA-8C07-4093-8990-A865BD82EDF2', 1, 0, 0);
		insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('04B7FB79-05D3-4DC4-BA44-9EC64990DF3D', 'F314A324-D974-4F50-B26A-C89B8C1C5138', 1, 1, 0);

		print 'WARNING: Report data will be incorrect until a full engine run completes or you manually run fp.procFactReportFinancialStatementInsert'
	end

	--ad hoc history report security should always match the base report
	delete from dbo.S3SimplePermission where LootID = '5A864BEA-D27E-435E-B192-05283781EA30';
	insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue)
	select LootID, IdentityGUID, ReadValue, WriteValue, SecureValue from dbo.S3SimplePermission where LootID = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D';
GO


---------------------------------------------

-- fp.procReportFactReimbursementHistory
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2022-10-13   MD      JAZZ-32897		Adding union all for data transfer table
 ** 2   2024-09-18   BW      JAZZ-75453		Updated merge ON Clause to include ServiceLineRollupID
*************************************************************/
CREATE   PROCEDURE fp.procReportFactReimbursementHistory (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE 
AS
BEGIN

exec [dbo].[procSysDropTempTable] '#SRC'
exec [dbo].[procSysDropTempTable] '#rawChargeData'
exec [dbo].[procSysDropTempTable] '#rawEncounterData'
exec [dbo].[procSysDropTempTable] '#calculatedData'

CREATE TABLE #SRC (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,
	FiscalMonthID TINYINT,
	UnitTypeID INT,
	Value DECIMAL(19,8)
)

CREATE TABLE #rawChargeData (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,
	NetReimbursement01 DECIMAL (19,8),
	NetReimbursement02 DECIMAL (19,8),
	NetReimbursement03 DECIMAL (19,8),
	NetReimbursement04 DECIMAL (19,8),
	NetReimbursement05 DECIMAL (19,8),
	NetReimbursement06 DECIMAL (19,8),
	NetReimbursement07 DECIMAL (19,8),
	NetReimbursement08 DECIMAL (19,8),
	NetReimbursement09 DECIMAL (19,8),
	NetReimbursement10 DECIMAL (19,8),
	NetReimbursement11 DECIMAL (19,8),
	NetReimbursement12 DECIMAL (19,8),
	GrossCharges01 DECIMAL (19,8),
	GrossCharges02 DECIMAL (19,8),
	GrossCharges03 DECIMAL (19,8),
	GrossCharges04 DECIMAL (19,8),
	GrossCharges05 DECIMAL (19,8),
	GrossCharges06 DECIMAL (19,8),
	GrossCharges07 DECIMAL (19,8),
	GrossCharges08 DECIMAL (19,8),
	GrossCharges09 DECIMAL (19,8),
	GrossCharges10 DECIMAL (19,8),
	GrossCharges11 DECIMAL (19,8),
	GrossCharges12 DECIMAL (19,8)
)

CREATE TABLE #rawEncounterData (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,
	NetReimbursement01 DECIMAL (19,8),
	NetReimbursement02 DECIMAL (19,8),
	NetReimbursement03 DECIMAL (19,8),
	NetReimbursement04 DECIMAL (19,8),
	NetReimbursement05 DECIMAL (19,8),
	NetReimbursement06 DECIMAL (19,8),
	NetReimbursement07 DECIMAL (19,8),
	NetReimbursement08 DECIMAL (19,8),
	NetReimbursement09 DECIMAL (19,8),
	NetReimbursement10 DECIMAL (19,8),
	NetReimbursement11 DECIMAL (19,8),
	NetReimbursement12 DECIMAL (19,8)
)

CREATE TABLE #calculatedData (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,	
	GrossCharges01 DECIMAL (19,8),
	GrossCharges02 DECIMAL (19,8),
	GrossCharges03 DECIMAL (19,8),
	GrossCharges04 DECIMAL (19,8),
	GrossCharges05 DECIMAL (19,8),
	GrossCharges06 DECIMAL (19,8),
	GrossCharges07 DECIMAL (19,8),
	GrossCharges08 DECIMAL (19,8),
	GrossCharges09 DECIMAL (19,8),
	GrossCharges10 DECIMAL (19,8),
	GrossCharges11 DECIMAL (19,8),
	GrossCharges12 DECIMAL (19,8),
	NetReimbursement01 DECIMAL (19,8),
	NetReimbursement02 DECIMAL (19,8),
	NetReimbursement03 DECIMAL (19,8),
	NetReimbursement04 DECIMAL (19,8),
	NetReimbursement05 DECIMAL (19,8),
	NetReimbursement06 DECIMAL (19,8),
	NetReimbursement07 DECIMAL (19,8),
	NetReimbursement08 DECIMAL (19,8),
	NetReimbursement09 DECIMAL (19,8),
	NetReimbursement10 DECIMAL (19,8),
	NetReimbursement11 DECIMAL (19,8),
	NetReimbursement12 DECIMAL (19,8),	
	ContractualAllowance01 DECIMAL (19,8),
	ContractualAllowance02 DECIMAL (19,8),
	ContractualAllowance03 DECIMAL (19,8),
	ContractualAllowance04 DECIMAL (19,8),
	ContractualAllowance05 DECIMAL (19,8),
	ContractualAllowance06 DECIMAL (19,8),
	ContractualAllowance07 DECIMAL (19,8),
	ContractualAllowance08 DECIMAL (19,8),
	ContractualAllowance09 DECIMAL (19,8),
	ContractualAllowance10 DECIMAL (19,8),
	ContractualAllowance11 DECIMAL (19,8),
	ContractualAllowance12 DECIMAL (19,8)
)

--------------------------------------------------------------
--Get reimbursement encounter data
--------------------------------------------------------------
INSERT INTO #rawEncounterData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
	NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04,
	NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08,
	NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12)
SELECT 
	fre.BudgetConfigID,
	fre.EntityGroupConfigID,
	fre.EntityID,
	fre.PatientClassID, 
	fre.ServiceLineID,
	fre.ServiceLineRollupID,
	fre.MedicalSurgicalID,
	fre.PayorID, 
	fre.PayorGroupID,
	fre.MSDRGID,
	fre.CPTID,
	fre.TimeClassID,
	fre.FiscalYearID,
	fre.NetReimbursementValue01,
	fre.NetReimbursementValue02,
	fre.NetReimbursementValue03,
	fre.NetReimbursementValue04,
	fre.NetReimbursementValue05,
	fre.NetReimbursementValue06,
	fre.NetReimbursementValue07,
	fre.NetReimbursementValue08,
	fre.NetReimbursementValue09,
	fre.NetReimbursementValue10,
	fre.NetReimbursementValue11,
	fre.NetReimbursementValue12
FROM fp.viewFactReimbursementEncountersHistory_Unpivoted_source fre
WHERE
	fre.BudgetConfigID = @BudgetConfigID

--------------------------------------------------------------
--Get reimbursement charge data
--------------------------------------------------------------
INSERT INTO #rawChargeData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
	GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04,
	GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08,
	GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12,
	NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04,
	NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08,
	NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12)
SELECT 
	frc.BudgetConfigID,
	frc.EntityGroupConfigID,
	frc.EntityID,
	frc.PatientClassID, 
	frc.ServiceLineID,
	frc.ServiceLineRollupID,
	frc.MedicalSurgicalID,
	frc.PayorID, 
	frc.PayorGroupID,
	frc.MSDRGID,
	frc.PrimaryCPTID,
	frc.TimeClassID,
	frc.FiscalYearID,
	frc.ChargeDollarsValue01,
	frc.ChargeDollarsValue02,
	frc.ChargeDollarsValue03,
	frc.ChargeDollarsValue04,
	frc.ChargeDollarsValue05,
	frc.ChargeDollarsValue06,
	frc.ChargeDollarsValue07,
	frc.ChargeDollarsValue08,
	frc.ChargeDollarsValue09,
	frc.ChargeDollarsValue10,
	frc.ChargeDollarsValue11,
	frc.ChargeDollarsValue12,
	frc.NetReimbursementValue01,
	frc.NetReimbursementValue02,
	frc.NetReimbursementValue03,
	frc.NetReimbursementValue04,
	frc.NetReimbursementValue05,
	frc.NetReimbursementValue06,
	frc.NetReimbursementValue07,
	frc.NetReimbursementValue08,
	frc.NetReimbursementValue09,
	frc.NetReimbursementValue10,
	frc.NetReimbursementValue11,
	frc.NetReimbursementValue12
FROM fp.viewFactReimbursementChargesHistory_Unpivoted_source frc
WHERE
	frc.BudgetConfigID = @BudgetConfigID

--------------------------------------------------------------
--Do allocation calculation
--ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX
--------------------------------------------------------------
INSERT INTO #calculatedData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
	GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04,
	GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08,
	GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12,
	NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04,
	NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08,
	NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12,
	ContractualAllowance01, ContractualAllowance02, ContractualAllowance03, ContractualAllowance04,
	ContractualAllowance05, ContractualAllowance06, ContractualAllowance07, ContractualAllowance08,
	ContractualAllowance09, ContractualAllowance10, ContractualAllowance11, ContractualAllowance12
)
SELECT 
	ISNULL(frc.BudgetConfigID, fre.BudgetConfigID),
	ISNULL(frc.EntityGroupConfigID, fre.EntityGroupConfigID),
	ISNULL(frc.EntityID, fre.EntityID),
	ISNULL(frc.PatientClassID, fre.PatientClassID), 
	ISNULL(frc.ServiceLineID, fre.ServiceLineID),
	ISNULL(frc.ServiceLineRollupID, fre.ServiceLineRollupID),
	ISNULL(frc.MedicalSurgicalID, fre.MedicalSurgicalID),
	ISNULL(frc.PayorID, fre.PayorID), 
	ISNULL(frc.PayorGroupID, fre.PayorGroupID),
	ISNULL(frc.MSDRGID, fre.MSDRGID),
	ISNULL(frc.PrimaryCPTID, fre.PrimaryCPTID),
	ISNULL(frc.TimeClassID, fre.TimeClassID),
	ISNULL(frc.FiscalYearID, fre.FiscalYearID),
	ISNULL(frc.GrossCharges01,0),
	ISNULL(frc.GrossCharges02,0),
	ISNULL(frc.GrossCharges03,0),
	ISNULL(frc.GrossCharges04,0),
	ISNULL(frc.GrossCharges05,0),
	ISNULL(frc.GrossCharges06,0),
	ISNULL(frc.GrossCharges07,0),
	ISNULL(frc.GrossCharges08,0),
	ISNULL(frc.GrossCharges09,0),
	ISNULL(frc.GrossCharges10,0),
	ISNULL(frc.GrossCharges11,0),
	ISNULL(frc.GrossCharges12,0),
	ISNULL(ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0),0),
	ISNULL(ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0),0),
	ISNULL(ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0),0),
	ISNULL(ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0),0),
	ISNULL(ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0),0),
	ISNULL(ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0),0),
	ISNULL(ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0),0),
	ISNULL(ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0),0),
	ISNULL(ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0),0),
	ISNULL(ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0),0),
	ISNULL(ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0),0),
	ISNULL(ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0),0),
	ISNULL(ISNULL(frc.GrossCharges01,0) - (ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0)),0),
	ISNULL(ISNULL(frc.GrossCharges02,0) - (ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0)),0),
	ISNULL(ISNULL(frc.GrossCharges03,0) - (ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0)),0),
	ISNULL(ISNULL(frc.GrossCharges04,0) - (ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0)),0),
	ISNULL(ISNULL(frc.GrossCharges05,0) - (ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0)),0),
	ISNULL(ISNULL(frc.GrossCharges06,0) - (ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0)),0),
	ISNULL(ISNULL(frc.GrossCharges07,0) - (ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0)),0),
	ISNULL(ISNULL(frc.GrossCharges08,0) - (ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0)),0),
	ISNULL(ISNULL(frc.GrossCharges09,0) - (ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0)),0),
	ISNULL(ISNULL(frc.GrossCharges10,0) - (ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0)),0),
	ISNULL(ISNULL(frc.GrossCharges11,0) - (ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0)),0),
	ISNULL(ISNULL(frc.GrossCharges12,0) - (ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0)),0)
FROM #rawChargeData frc
FULL JOIN #rawEncounterData fre
	ON frc.BudgetConfigID = fre.BudgetConfigID
	AND frc.EntityGroupConfigID = fre.EntityGroupConfigID
	AND frc.EntityID = fre.EntityID
	AND frc.PatientClassID = fre.PatientClassID
	AND frc.ServiceLineID = fre.ServiceLineID
	AND frc.ServiceLineRollupID = fre.ServiceLineRollupID
	AND frc.MedicalSurgicalID = fre.MedicalSurgicalID
	AND frc.PayorID = fre.PayorID
	AND frc.PayorGroupID = fre.PayorGroupID
	AND frc.MSDRGID = fre.MSDRGID
	AND frc.PrimaryCPTID = fre.PrimaryCPTID
	AND frc.TimeClassID = fre.TimeClassID
	AND frc.FiscalYearID = frc.FiscalYearID

CREATE CLUSTERED INDEX inx_src ON #SRC (
	BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	PatientClassID, 
	ServiceLineID,
	ServiceLineRollupID,
	MedicalSurgicalID,
	PayorID, 
	PayorGroupID,
	MSDRGID,
	PrimaryCPTID,
	TimeClassID,
	FiscalYearID,
	FiscalMonthID
)

--------------------------------------------------------------
--Pivot data into #SRC table
--------------------------------------------------------------
INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value)
SELECT 
	cv.BudgetConfigID, 
	cv.EntityGroupConfigID, 
	cv.EntityID, 
	cv.PatientClassID, 
	cv.ServiceLineID, 
	cv.ServiceLineRollupID, 
	cv.MedicalSurgicalID, 
	cv.PayorID, 
	cv.PayorGroupID, 
	cv.MSDRGID, 
	cv.PrimaryCPTID, 
	cv.TimeClassID,
	cv.FiscalYearID, 
	m.FiscalMonthID, 
	cv.UnitTypeID,
	SUM(cv.Value) AS Value
FROM (
	SELECT
		BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, 
		ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, 
		PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
		FiscalMonth, UnitTypeID, Value
	FROM #calculatedData cd
	CROSS APPLY (
		VALUES 
		('Month01', GrossCharges01, 177),
		('Month02', GrossCharges02, 177),
		('Month03', GrossCharges03, 177),
		('Month04', GrossCharges04, 177),
		('Month05', GrossCharges05, 177),
		('Month06', GrossCharges06, 177),
		('Month07', GrossCharges07, 177),
		('Month08', GrossCharges08, 177),
		('Month09', GrossCharges09, 177),
		('Month10', GrossCharges10, 177),
		('Month11', GrossCharges11, 177),
		('Month12', GrossCharges12, 177),
		('Month01', NetReimbursement01, 179),
		('Month02', NetReimbursement02, 179),
		('Month03', NetReimbursement03, 179),
		('Month04', NetReimbursement04, 179),
		('Month05', NetReimbursement05, 179),
		('Month06', NetReimbursement06, 179),
		('Month07', NetReimbursement07, 179),
		('Month08', NetReimbursement08, 179),
		('Month09', NetReimbursement09, 179),
		('Month10', NetReimbursement10, 179),
		('Month11', NetReimbursement11, 179),
		('Month12', NetReimbursement12, 179),
		('Month01', ContractualAllowance01, 178),
		('Month02', ContractualAllowance02, 178),
		('Month03', ContractualAllowance03, 178),
		('Month04', ContractualAllowance04, 178),
		('Month05', ContractualAllowance05, 178),
		('Month06', ContractualAllowance06, 178),
		('Month07', ContractualAllowance07, 178),
		('Month08', ContractualAllowance08, 178),
		('Month09', ContractualAllowance09, 178),
		('Month10', ContractualAllowance10, 178),
		('Month11', ContractualAllowance11, 178),
		('Month12', ContractualAllowance12, 178)) X (FiscalMonth, Value, UnitTypeID)
) cv
INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
GROUP BY cv.BudgetConfigID, 
	cv.EntityGroupConfigID, 
	cv.EntityID, 
	cv.PatientClassID, 
	cv.ServiceLineID, 
	cv.ServiceLineRollupID, 
	cv.MedicalSurgicalID, 
	cv.PayorID, 
	cv.PayorGroupID, 
	cv.MSDRGID, 
	cv.PrimaryCPTID, 
	cv.TimeClassID,
	cv.FiscalYearID, 
	m.FiscalMonthID, 
	cv.UnitTypeID

;WITH TGT AS 
(
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
		MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value
	FROM fp.FactReportReimbursement fr
	WHERE fr.BudgetConfigID = @BudgetConfigID
)
	MERGE TGT as target
	USING #SRC AS source
		ON (
			target.BudgetConfigID = source.BudgetConfigID
			AND target.EntityGroupConfigID = source.EntityGroupConfigID
			AND target.EntityID = source.EntityID
			AND target.PatientClassID = source.PatientClassID
			AND target.ServiceLineID = source.ServiceLineID
			AND target.ServiceLineRollupID = source.ServiceLineRollupID
			AND target.MedicalSurgicalID = source.MedicalSurgicalID
			AND target.PayorID = source.PayorID
			AND target.PayorGroupID = source.PayorGroupID
			AND target.MSDRGID = source.MSDRGID
			AND target.PrimaryCPTID = source.PrimaryCPTID
			AND target.TimeClassID = source.TimeClassID
			AND target.FiscalYearID = source.FiscalYearID
			AND target.FiscalMonthID = source.FiscalMonthID
			AND target.UnitTypeID = source.UnitTypeID
		)
	WHEN MATCHED AND (target.Value <> source.Value)
		THEN
			UPDATE
			SET target.Value = ISNULL(source.Value, 0)
	WHEN NOT MATCHED BY TARGET
		THEN
			INSERT (
				BudgetConfigID, 
				EntityGroupConfigID, 
				EntityID, 
				PatientClassID, 
				ServiceLineID, 
				ServiceLineRollupID, 
				MedicalSurgicalID, 
				PayorID,
				PayorGroupID, 
				MSDRGID, 
				PrimaryCPTID, 
				TimeClassID, 
				FiscalYearID,
				FiscalMonthID,
				UnitTypeID, 
				Value
			)
			VALUES (
				source.BudgetConfigID, 
				source.EntityGroupConfigID, 
				source.EntityID, 
				source.PatientClassID, 
				source.ServiceLineID, 
				source.ServiceLineRollupID, 
				source.MedicalSurgicalID, 
				source.PayorID,
				source.PayorGroupID, 
				source.MSDRGID, 
				source.PrimaryCPTID, 
				source.TimeClassID, 
				source.FiscalYearID,
				source.FiscalMonthID,
				source.UnitTypeID, 
				ISNULL(source.Value, 0)
			);
END;
GO


---------------------------------------------

-- fp.procReportFactReimbursement_ProjectionAndBudget
/**************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI				Description  
 ** 1   2022-10-13   MD      JAZZ-32897		Adding union all for data transfer table
 ** 2   2024-09-18   BW      JAZZ-75453		Updated merge ON Clause to include ServiceLineRollupID
*************************************************************/
CREATE   PROCEDURE fp.procReportFactReimbursement_ProjectionAndBudget (
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
WITH RECOMPILE 
AS
BEGIN

exec [dbo].[procSysDropTempTable] '#SRC'
exec [dbo].[procSysDropTempTable] '#rawChargeData'
exec [dbo].[procSysDropTempTable] '#rawEncounterData'
exec [dbo].[procSysDropTempTable] '#calculatedData'

CREATE TABLE #SRC (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,
	FiscalMonthID TINYINT,
	UnitTypeID INT,
	Value DECIMAL(19,8)
)

CREATE TABLE #rawChargeData (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,
	NetReimbursement01 DECIMAL (19,8),
	NetReimbursement02 DECIMAL (19,8),
	NetReimbursement03 DECIMAL (19,8),
	NetReimbursement04 DECIMAL (19,8),
	NetReimbursement05 DECIMAL (19,8),
	NetReimbursement06 DECIMAL (19,8),
	NetReimbursement07 DECIMAL (19,8),
	NetReimbursement08 DECIMAL (19,8),
	NetReimbursement09 DECIMAL (19,8),
	NetReimbursement10 DECIMAL (19,8),
	NetReimbursement11 DECIMAL (19,8),
	NetReimbursement12 DECIMAL (19,8),
	GrossCharges01 DECIMAL (19,8),
	GrossCharges02 DECIMAL (19,8),
	GrossCharges03 DECIMAL (19,8),
	GrossCharges04 DECIMAL (19,8),
	GrossCharges05 DECIMAL (19,8),
	GrossCharges06 DECIMAL (19,8),
	GrossCharges07 DECIMAL (19,8),
	GrossCharges08 DECIMAL (19,8),
	GrossCharges09 DECIMAL (19,8),
	GrossCharges10 DECIMAL (19,8),
	GrossCharges11 DECIMAL (19,8),
	GrossCharges12 DECIMAL (19,8)
)

CREATE TABLE #rawEncounterData (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,
	NetReimbursement01 DECIMAL (19,8),
	NetReimbursement02 DECIMAL (19,8),
	NetReimbursement03 DECIMAL (19,8),
	NetReimbursement04 DECIMAL (19,8),
	NetReimbursement05 DECIMAL (19,8),
	NetReimbursement06 DECIMAL (19,8),
	NetReimbursement07 DECIMAL (19,8),
	NetReimbursement08 DECIMAL (19,8),
	NetReimbursement09 DECIMAL (19,8),
	NetReimbursement10 DECIMAL (19,8),
	NetReimbursement11 DECIMAL (19,8),
	NetReimbursement12 DECIMAL (19,8)
)

CREATE TABLE #calculatedData (
	BudgetConfigID INT,
	EntityGroupConfigID INT,
	EntityID INT, 
	PatientClassID INT, 
	ServiceLineID INT,
	ServiceLineRollupID INT,
	MedicalSurgicalID INT,
	PayorID INT, 
	PayorGroupID INT,
	MSDRGID INT,
	PrimaryCPTID INT,
	TimeClassID INT,
	FiscalYearID INT,	
	GrossCharges01 DECIMAL (19,8),
	GrossCharges02 DECIMAL (19,8),
	GrossCharges03 DECIMAL (19,8),
	GrossCharges04 DECIMAL (19,8),
	GrossCharges05 DECIMAL (19,8),
	GrossCharges06 DECIMAL (19,8),
	GrossCharges07 DECIMAL (19,8),
	GrossCharges08 DECIMAL (19,8),
	GrossCharges09 DECIMAL (19,8),
	GrossCharges10 DECIMAL (19,8),
	GrossCharges11 DECIMAL (19,8),
	GrossCharges12 DECIMAL (19,8),
	NetReimbursement01 DECIMAL (19,8),
	NetReimbursement02 DECIMAL (19,8),
	NetReimbursement03 DECIMAL (19,8),
	NetReimbursement04 DECIMAL (19,8),
	NetReimbursement05 DECIMAL (19,8),
	NetReimbursement06 DECIMAL (19,8),
	NetReimbursement07 DECIMAL (19,8),
	NetReimbursement08 DECIMAL (19,8),
	NetReimbursement09 DECIMAL (19,8),
	NetReimbursement10 DECIMAL (19,8),
	NetReimbursement11 DECIMAL (19,8),
	NetReimbursement12 DECIMAL (19,8),	
	ContractualAllowance01 DECIMAL (19,8),
	ContractualAllowance02 DECIMAL (19,8),
	ContractualAllowance03 DECIMAL (19,8),
	ContractualAllowance04 DECIMAL (19,8),
	ContractualAllowance05 DECIMAL (19,8),
	ContractualAllowance06 DECIMAL (19,8),
	ContractualAllowance07 DECIMAL (19,8),
	ContractualAllowance08 DECIMAL (19,8),
	ContractualAllowance09 DECIMAL (19,8),
	ContractualAllowance10 DECIMAL (19,8),
	ContractualAllowance11 DECIMAL (19,8),
	ContractualAllowance12 DECIMAL (19,8)
)

--------------------------------------------------------------
--Get reimbursement encounter data
--------------------------------------------------------------
INSERT INTO #rawEncounterData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
	NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04,
	NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08,
	NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12)
SELECT 
	fre.BudgetConfigID,
	fre.EntityGroupConfigID,
	fre.EntityID,
	fre.PatientClassID, 
	fre.ServiceLineID,
	fre.ServiceLineRollupID,
	fre.MedicalSurgicalID,
	fre.PayorID, 
	fre.PayorGroupID,
	fre.MSDRGID,
	fre.CPTID,
	fre.TimeClassID,
	fre.FiscalYearID,
	fre.NetReimbursementValue01,
	fre.NetReimbursementValue02,
	fre.NetReimbursementValue03,
	fre.NetReimbursementValue04,
	fre.NetReimbursementValue05,
	fre.NetReimbursementValue06,
	fre.NetReimbursementValue07,
	fre.NetReimbursementValue08,
	fre.NetReimbursementValue09,
	fre.NetReimbursementValue10,
	fre.NetReimbursementValue11,
	fre.NetReimbursementValue12
FROM fp.viewFactReimbursementEncounters_Unpivoted_source fre
WHERE
	fre.BudgetConfigID = @BudgetConfigID

--------------------------------------------------------------
--Get reimbursement charge data
--------------------------------------------------------------
INSERT INTO #rawChargeData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
	GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04,
	GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08,
	GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12,
	NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04,
	NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08,
	NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12)
SELECT 
	frc.BudgetConfigID,
	frc.EntityGroupConfigID,
	frc.EntityID,
	frc.PatientClassID, 
	frc.ServiceLineID,
	frc.ServiceLineRollupID,
	frc.MedicalSurgicalID,
	frc.PayorID, 
	frc.PayorGroupID,
	frc.MSDRGID,
	frc.PrimaryCPTID,
	frc.TimeClassID,
	frc.FiscalYearID,
	frc.ChargeDollarsValue01,
	frc.ChargeDollarsValue02,
	frc.ChargeDollarsValue03,
	frc.ChargeDollarsValue04,
	frc.ChargeDollarsValue05,
	frc.ChargeDollarsValue06,
	frc.ChargeDollarsValue07,
	frc.ChargeDollarsValue08,
	frc.ChargeDollarsValue09,
	frc.ChargeDollarsValue10,
	frc.ChargeDollarsValue11,
	frc.ChargeDollarsValue12,
	frc.NetReimbursementValue01,
	frc.NetReimbursementValue02,
	frc.NetReimbursementValue03,
	frc.NetReimbursementValue04,
	frc.NetReimbursementValue05,
	frc.NetReimbursementValue06,
	frc.NetReimbursementValue07,
	frc.NetReimbursementValue08,
	frc.NetReimbursementValue09,
	frc.NetReimbursementValue10,
	frc.NetReimbursementValue11,
	frc.NetReimbursementValue12
FROM fp.viewFactReimbursementCharges_Unpivoted_source frc
WHERE
	frc.BudgetConfigID = @BudgetConfigID

--------------------------------------------------------------
--Do allocation calculation
--ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX
--------------------------------------------------------------
INSERT INTO #calculatedData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
	GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04,
	GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08,
	GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12,
	NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04,
	NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08,
	NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12,
	ContractualAllowance01, ContractualAllowance02, ContractualAllowance03, ContractualAllowance04,
	ContractualAllowance05, ContractualAllowance06, ContractualAllowance07, ContractualAllowance08,
	ContractualAllowance09, ContractualAllowance10, ContractualAllowance11, ContractualAllowance12
)
SELECT 
	ISNULL(frc.BudgetConfigID, fre.BudgetConfigID),
	ISNULL(frc.EntityGroupConfigID, fre.EntityGroupConfigID),
	ISNULL(frc.EntityID, fre.EntityID),
	ISNULL(frc.PatientClassID, fre.PatientClassID), 
	ISNULL(frc.ServiceLineID, fre.ServiceLineID),
	ISNULL(frc.ServiceLineRollupID, fre.ServiceLineRollupID),
	ISNULL(frc.MedicalSurgicalID, fre.MedicalSurgicalID),
	ISNULL(frc.PayorID, fre.PayorID), 
	ISNULL(frc.PayorGroupID, fre.PayorGroupID),
	ISNULL(frc.MSDRGID, fre.MSDRGID),
	ISNULL(frc.PrimaryCPTID, fre.PrimaryCPTID),
	ISNULL(frc.TimeClassID, fre.TimeClassID),
	ISNULL(frc.FiscalYearID, fre.FiscalYearID),
	ISNULL(frc.GrossCharges01,0),
	ISNULL(frc.GrossCharges02,0),
	ISNULL(frc.GrossCharges03,0),
	ISNULL(frc.GrossCharges04,0),
	ISNULL(frc.GrossCharges05,0),
	ISNULL(frc.GrossCharges06,0),
	ISNULL(frc.GrossCharges07,0),
	ISNULL(frc.GrossCharges08,0),
	ISNULL(frc.GrossCharges09,0),
	ISNULL(frc.GrossCharges10,0),
	ISNULL(frc.GrossCharges11,0),
	ISNULL(frc.GrossCharges12,0),
	ISNULL(ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0),0),
	ISNULL(ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0),0),
	ISNULL(ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0),0),
	ISNULL(ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0),0),
	ISNULL(ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0),0),
	ISNULL(ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0),0),
	ISNULL(ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0),0),
	ISNULL(ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0),0),
	ISNULL(ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0),0),
	ISNULL(ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0),0),
	ISNULL(ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0),0),
	ISNULL(ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0),0),
	ISNULL(ISNULL(frc.GrossCharges01,0) - (ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0)),0),
	ISNULL(ISNULL(frc.GrossCharges02,0) - (ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0)),0),
	ISNULL(ISNULL(frc.GrossCharges03,0) - (ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0)),0),
	ISNULL(ISNULL(frc.GrossCharges04,0) - (ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0)),0),
	ISNULL(ISNULL(frc.GrossCharges05,0) - (ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0)),0),
	ISNULL(ISNULL(frc.GrossCharges06,0) - (ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0)),0),
	ISNULL(ISNULL(frc.GrossCharges07,0) - (ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0)),0),
	ISNULL(ISNULL(frc.GrossCharges08,0) - (ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0)),0),
	ISNULL(ISNULL(frc.GrossCharges09,0) - (ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0)),0),
	ISNULL(ISNULL(frc.GrossCharges10,0) - (ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0)),0),
	ISNULL(ISNULL(frc.GrossCharges11,0) - (ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0)),0),
	ISNULL(ISNULL(frc.GrossCharges12,0) - (ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0)),0)
FROM #rawChargeData frc
FULL JOIN #rawEncounterData fre
	ON frc.BudgetConfigID = fre.BudgetConfigID
	AND frc.EntityGroupConfigID = fre.EntityGroupConfigID
	AND frc.EntityID = fre.EntityID
	AND frc.PatientClassID = fre.PatientClassID
	AND frc.ServiceLineID = fre.ServiceLineID
	AND frc.ServiceLineRollupID = fre.ServiceLineRollupID
	AND frc.MedicalSurgicalID = fre.MedicalSurgicalID
	AND frc.PayorID = fre.PayorID
	AND frc.PayorGroupID = fre.PayorGroupID
	AND frc.MSDRGID = fre.MSDRGID
	AND frc.PrimaryCPTID = fre.PrimaryCPTID
	AND frc.TimeClassID = fre.TimeClassID
	AND frc.FiscalYearID = frc.FiscalYearID

CREATE CLUSTERED INDEX inx_src ON #SRC (
	BudgetConfigID,
	EntityGroupConfigID,
	EntityID,
	PatientClassID, 
	ServiceLineID,
	ServiceLineRollupID,
	MedicalSurgicalID,
	PayorID, 
	PayorGroupID,
	MSDRGID,
	PrimaryCPTID,
	TimeClassID,
	FiscalYearID,
	FiscalMonthID
)

--------------------------------------------------------------
--Pivot data into #SRC table
--------------------------------------------------------------
INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value)
SELECT 
	cv.BudgetConfigID, 
	cv.EntityGroupConfigID, 
	cv.EntityID, 
	cv.PatientClassID, 
	cv.ServiceLineID, 
	cv.ServiceLineRollupID, 
	cv.MedicalSurgicalID, 
	cv.PayorID, 
	cv.PayorGroupID, 
	cv.MSDRGID, 
	cv.PrimaryCPTID, 
	cv.TimeClassID,
	cv.FiscalYearID, 
	m.FiscalMonthID, 
	cv.UnitTypeID,
	SUM(cv.Value) AS Value
FROM (
	SELECT
		BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, 
		ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, 
		PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID,
		FiscalMonth, UnitTypeID, Value
	FROM #calculatedData cd
	CROSS APPLY (
		VALUES 
		('Month01', GrossCharges01, 177),
		('Month02', GrossCharges02, 177),
		('Month03', GrossCharges03, 177),
		('Month04', GrossCharges04, 177),
		('Month05', GrossCharges05, 177),
		('Month06', GrossCharges06, 177),
		('Month07', GrossCharges07, 177),
		('Month08', GrossCharges08, 177),
		('Month09', GrossCharges09, 177),
		('Month10', GrossCharges10, 177),
		('Month11', GrossCharges11, 177),
		('Month12', GrossCharges12, 177),
		('Month01', NetReimbursement01, 179),
		('Month02', NetReimbursement02, 179),
		('Month03', NetReimbursement03, 179),
		('Month04', NetReimbursement04, 179),
		('Month05', NetReimbursement05, 179),
		('Month06', NetReimbursement06, 179),
		('Month07', NetReimbursement07, 179),
		('Month08', NetReimbursement08, 179),
		('Month09', NetReimbursement09, 179),
		('Month10', NetReimbursement10, 179),
		('Month11', NetReimbursement11, 179),
		('Month12', NetReimbursement12, 179),
		('Month01', ContractualAllowance01, 178),
		('Month02', ContractualAllowance02, 178),
		('Month03', ContractualAllowance03, 178),
		('Month04', ContractualAllowance04, 178),
		('Month05', ContractualAllowance05, 178),
		('Month06', ContractualAllowance06, 178),
		('Month07', ContractualAllowance07, 178),
		('Month08', ContractualAllowance08, 178),
		('Month09', ContractualAllowance09, 178),
		('Month10', ContractualAllowance10, 178),
		('Month11', ContractualAllowance11, 178),
		('Month12', ContractualAllowance12, 178)) X (FiscalMonth, Value, UnitTypeID)
) cv
INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth
GROUP BY cv.BudgetConfigID, 
	cv.EntityGroupConfigID, 
	cv.EntityID, 
	cv.PatientClassID, 
	cv.ServiceLineID, 
	cv.ServiceLineRollupID, 
	cv.MedicalSurgicalID, 
	cv.PayorID, 
	cv.PayorGroupID, 
	cv.MSDRGID, 
	cv.PrimaryCPTID, 
	cv.TimeClassID,
	cv.FiscalYearID, 
	m.FiscalMonthID, 
	cv.UnitTypeID

;WITH TGT AS 
(
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
		MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value
	FROM fp.FactReportReimbursement fr
	WHERE fr.BudgetConfigID = @BudgetConfigID
)
	MERGE TGT as target
	USING #SRC AS source
		ON (
			target.BudgetConfigID = source.BudgetConfigID
			AND target.EntityGroupConfigID = source.EntityGroupConfigID
			AND target.EntityID = source.EntityID
			AND target.PatientClassID = source.PatientClassID
			AND target.ServiceLineID = source.ServiceLineID
			AND target.ServiceLineRollupID = source.ServiceLineRollupID
			AND target.MedicalSurgicalID = source.MedicalSurgicalID
			AND target.PayorID = source.PayorID
			AND target.PayorGroupID = source.PayorGroupID
			AND target.MSDRGID = source.MSDRGID
			AND target.PrimaryCPTID = source.PrimaryCPTID
			AND target.TimeClassID = source.TimeClassID
			AND target.FiscalYearID = source.FiscalYearID
			AND target.FiscalMonthID = source.FiscalMonthID
			AND target.UnitTypeID = source.UnitTypeID
		)
	WHEN MATCHED AND (target.Value <> source.Value)
		THEN
			UPDATE
			SET target.Value = ISNULL(source.Value, 0)
	WHEN NOT MATCHED BY TARGET
		THEN
			INSERT (
				BudgetConfigID, 
				EntityGroupConfigID, 
				EntityID, 
				PatientClassID, 
				ServiceLineID, 
				ServiceLineRollupID, 
				MedicalSurgicalID, 
				PayorID,
				PayorGroupID, 
				MSDRGID, 
				PrimaryCPTID, 
				TimeClassID, 
				FiscalYearID,
				FiscalMonthID,
				UnitTypeID, 
				Value
			)
			VALUES (
				source.BudgetConfigID, 
				source.EntityGroupConfigID, 
				source.EntityID, 
				source.PatientClassID, 
				source.ServiceLineID, 
				source.ServiceLineRollupID, 
				source.MedicalSurgicalID, 
				source.PayorID,
				source.PayorGroupID, 
				source.MSDRGID, 
				source.PrimaryCPTID, 
				source.TimeClassID, 
				source.FiscalYearID,
				source.FiscalMonthID,
				source.UnitTypeID, 
				ISNULL(source.Value, 0)
			);

END;
GO


---------------------------------------------

-- fp.procReportFactStatisticsISBackup
CREATE   PROCEDURE [fp].[procReportFactStatisticsISBackup] (  
	 @BudgetConfigID INT,  
	 @AnnualizationFactor DECIMAL(19,8),
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,  
	 @IsDebug BIT = 0  
)  
AS  
BEGIN  

 /**************************************************************
** Change History
** CID  Date		Author	WI				Description
** 1	2022-10-10	MD		JAZZ-1162 		Update IS proc to populate annual days in period for all time classes
** 2	2022-11-18	BK		JAZZ-46281		Use temp table and filter
** 3	2022-11-29	MD		JAZZ-6207 		Update IS proc to populate primary stat drivers for revenue only stats
** 4    2022-11-30  NT		JAZZ-30106		Fix Working Hours calculation as they are getting rolled up across Job Codes
** 5    2023-06-26  MD		JAZZ-54581		Update current year actual FTEs to calculate with only loaded working hours
** 6	2024-01-08  MY		JAZZ-63564		Final Pass Of Fact References (SQL)
** 7	2024-10-15  MY		JAZZ-78155		Recommendation to add index on temp tables within fp.ProcReportFactStatisticsISBackup
** 8	2024-12-05  MY		JAZZ-80822		Add Option Recompile
*************************************************************/
  
 SET NOCOUNT ON;  
  
 EXEC [dbo].[procSysDropTempTable] '#SRC'  
 EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality'  
 EXEC [dbo].[procSysDropTempTable] '#FactStatisticsDriversAccountsStaffing'  
 EXEC [dbo].[procSysDropTempTable] '#FactStatisticsDriversAccountsNonStaffing'  
 EXEC [dbo].[procSysDropTempTable] '#FactStatisticsDriversAccountsRevenueOnly'  
 EXEC [dbo].[procSysDropTempTable] '#StagingCandidates'  
 EXEC [dbo].[procSysDropTempTable] '#StagingCandidatesPlusDrivers'  
 EXEC [dbo].[procSysDropTempTable] '#StagingCandidatesPlusDriversPlusUOS'  
 EXEC [dbo].[procSysDropTempTable] '#StagingCandidatesPlusDriversPlusUOSPlusWorkingDays'  
 EXEC [dbo].[procSysDropTempTable] '#SRC'  
 EXEC [dbo].[procSysDropTempTable] '#rolledUpHours'  
 EXEC [dbo].[procSysDropTempTable] '#Dimensionality'  
 EXEC [dbo].[procSysDropTempTable] '#DaysInYear'  
 EXEC [dbo].[procSysDropTempTable] '#Yr'  
 EXEC [dbo].[procSysDropTempTable] '#DimensionalityForActuals' 
  
 DECLARE @fiscalYearEndMonth INT  
 SELECT @fiscalYearEndMonth = Setting FROM DBSetting WHERE Name = 'GENERAL_FISCALYEARENDMONTH'  
   
 -- Cleanup non-active configs  
 DELETE fs  
 FROM [fp].[FactISReportStatistics] fs  
  INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID  
 WHERE bc.IsActive != 1   
   
 -- Build the department filter  
 SELECT DISTINCT DepartmentID   
 INTO #SourceDimensionality   
 FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)  
  
 -- If the filter is empty, passing in all to avoid a bunch of duplicate statements  
 -- if this ends up being slow, well, then we'll have to duplicate a bunch of statements   
 IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL)  
 BEGIN  
  INSERT INTO #SourceDimensionality (DepartmentID)  
  SELECT DISTINCT DepartmentID   
  FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED)   
 END   
   
 SELECT DISTINCT a.AccountID,  
  a.PatientClass, c.DepartmentID  
 INTO #FactStatisticsDriversAccountsStaffing  
 FROM [fp].[PrimaryStatisticsConfig] c WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON c.DepartmentID = src.DepartmentID  
  INNER JOIN [fw].[DimAccount] a WITH (READUNCOMMITTED) ON a.AccountID = c.AccountID  
  INNER JOIN [fp].[EntityGroupConfig] egc WITH (READUNCOMMITTED) ON c.EntityGroupConfigGUID = egc.EntityGroupConfigGUID  
  INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON egc.BudgetConfigGUID = bc.BudgetConfigGUID  
 WHERE IsStaffing = 1  
  AND bc.BudgetConfigID = @BudgetConfigID  
  
 SELECT DISTINCT a.AccountID,  
  a.PatientClass, c.DepartmentID  
 INTO #FactStatisticsDriversAccountsNonStaffing  
 FROM [fp].[PrimaryStatisticsConfig] c WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON c.DepartmentID = src.DepartmentID  
  INNER JOIN [fw].[DimAccount] a WITH (READUNCOMMITTED) ON a.AccountID = c.AccountID  
  INNER JOIN [fp].[EntityGroupConfig] egc WITH (READUNCOMMITTED) ON c.EntityGroupConfigGUID = egc.EntityGroupConfigGUID  
  INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON egc.BudgetConfigGUID = bc.BudgetConfigGUID  
 WHERE IsNonStaffing = 1  
  AND bc.BudgetConfigID = @BudgetConfigID  

 SELECT DISTINCT a.AccountID,  
  a.PatientClass, c.DepartmentID  
 INTO #FactStatisticsDriversAccountsRevenueOnly 
 FROM [fp].[PrimaryStatisticsConfig] c WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON c.DepartmentID = src.DepartmentID  
  INNER JOIN [fw].[DimAccount] a WITH (READUNCOMMITTED) ON a.AccountID = c.AccountID  
  INNER JOIN [fp].[EntityGroupConfig] egc WITH (READUNCOMMITTED) ON c.EntityGroupConfigGUID = egc.EntityGroupConfigGUID  
  INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON egc.BudgetConfigGUID = bc.BudgetConfigGUID  
 WHERE IsRevenue = 1 AND IsStaffing = 0 AND IsNonStaffing = 0
  AND bc.BudgetConfigID = @BudgetConfigID  
  
 CREATE TABLE #StagingCandidates (BudgetConfigID INT, DepartmentID INT, JobCodeID INT DEFAULT(0), AccountID INT, FinancialReportingID INT, FiscalYearID INT,   
  FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4))  
  
 CREATE TABLE #StagingCandidatesPlusDrivers (BudgetConfigID INT, DepartmentID INT, JobCodeID INT DEFAULT(0), AccountID INT, FinancialReportingID INT, FiscalYearID INT,   
  FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4))  
    
 CREATE TABLE #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID INT, DepartmentID INT, JobCodeID INT DEFAULT(0), AccountID INT, FinancialReportingID INT, FiscalYearID INT,   
  FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4),
  INDEX BASE CLUSTERED ([FinancialReportingID],[FiscalMonthID])  /* JAZZ-78155: Recommendation from CS */
 )

 CREATE TABLE #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, FiscalYearID INT,   
  FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4))  
  
 CREATE TABLE #SRC (BudgetConfigID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, FiscalYearID INT,   
  FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4), 
  INDEX BASE CLUSTERED ([BudgetConfigID],[DepartmentID],[AccountID],[FinancialReportingID],[FiscalYearID],[FiscalMonthID],[TimeClassID]) /* JAZZ-78155: Recommendation from CS */
 )  
    
 CREATE TABLE #Dimensionality (DepartmentID INT, JobCodeID INT)  

 CREATE TABLE #DimensionalityForActuals (FiscalYearID INT, FiscalMonthID INT, TimeClassID INT, DepartmentID INT, JobCodeID INT) --JAZZ-54581

 CREATE TABLE #DaysInYear (FiscalYearID SMALLINT, TimeClassID TINYINT, DaysInYear INT)

 CREATE TABLE #rolledUpHours (BudgetConfigID INT, DepartmentID INT, JobCodeID INT, AccountID INT, FinancialReportingID INT, FiscalYearID INT,   
  FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4))
   
 DECLARE @FiscalYearID SMALLINT;
 SET @FiscalYearID = (SELECT TOP 1 FiscalYearID FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID)
 CREATE TABLE #Yr (FiscalYearID SMALLINT)

 INSERT INTO #Yr SELECT @FiscalYearID     -- budget year
 INSERT INTO #Yr SELECT @FiscalYearID - 1 -- projection (current year)
 INSERT INTO #Yr SELECT @FiscalYearID - 2 -- prior year 

 INSERT INTO #Dimensionality (DepartmentID, JobCodeID)  
 SELECT DISTINCT data.DepartmentID, JobCodeID   
 FROM [fp].[Staffing] data  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
 WHERE BudgetConfigID = @BudgetConfigID    
  AND VariabilityID = 1 -- Simply limiting rows here, this has no significance other than that.  

    INSERT INTO #DaysInYear (FiscalYearID, TimeClassID, DaysInYear)
	SELECT 
		fy.FiscalYearID,
		tc.TimeClassID,
		DaysInYear = 
			SUM(
				CASE WHEN 
				(  
					(CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0  
					AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0  
				)  
				OR 
					(CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 
					THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END)
	FROM fw.DimFiscalMonth fm 
		CROSS JOIN #Yr fy
		CROSS JOIN (SELECT TimeClassID FROM fw.DimTimeClass WHERE TimeClassID IN (1, 2, 12, 20) ) tc  
	WHERE fm.FiscalMonthID <> 0
		AND fy.FiscalYearID <> 0
	GROUP BY
		fy.FiscalYearID,
		tc.TimeClassID

	--JAZZ-54581
	INSERT INTO #DaysInYear (FiscalYearID, TimeClassID, DaysInYear)
	SELECT 
		FiscalYearID, 
		19 AS TimeClassID, 
		DaysInYear 
	FROM #DaysInYear
	WHERE 
		FiscalYearID = @FiscalYearID - 1
		AND TimeClassID = 1
   
 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
 -----------------------------------------------------------------------------   Statistics   ------------------------------------------------------------------------------------  
 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
   
 -- Statistics, Projection  
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT data.BudgetConfigID,  
  data.DepartmentID,  
  data.AccountID,  
  FinancialReportingID = CASE WHEN a.PatientClass = 'Inpatient' THEN 497   
         WHEN a.PatientClass = 'Outpatient' THEN 498   
         WHEN a.PatientClass = 'Other' THEN 499   
         WHEN a.PatientClass = 'Observation' THEN 1000   
         WHEN a.PatientClass = 'ED' THEN 1001   
         WHEN a.PatientClass = 'Clinic' THEN 1002   
  END,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  data.TimeClassID,  
  SUM(data.ManagerValue) AS Amount,  
  SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.ManagerValue ELSE 0 END) AS YTD,  
  SUM(data.ManagerValue) AS Yearly,  
  SUM(data.ManagerValue) AS Total  
 FROM fp.viewFactStatistics_UnPivoted data WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
  INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID  
  INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID  
  INNER JOIN fw.DimAccount a ON a.AccountID = data.AccountID  
 WHERE data.TimeClassID = 12  
  AND data.BudgetConfigID = @BudgetConfigID  
  AND a.PatientClass IN (  
   'Inpatient', --UOS Inpatient  
   'Outpatient', --UOS Outpatient  
   'Other', --UOS Other  
   'Observation', --UOS Observation  
   'ED', --UOS ED  
   'Clinic' --UOS Clinic  
 )  
 GROUP BY data.BudgetConfigID, data.DepartmentID, data.AccountID, FinancialReportingID, data.FiscalYearID, data.FiscalMonthID, data.TimeClassID, a.PatientClass
  
 -- Statistics, Target/Budget  
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT data.BudgetConfigID,  
  data.DepartmentID,  
  data.AccountID,  
  FinancialReportingID = CASE WHEN a.PatientClass = 'Inpatient' THEN 497   
         WHEN a.PatientClass = 'Outpatient' THEN 498   
         WHEN a.PatientClass = 'Other' THEN 499   
         WHEN a.PatientClass = 'Observation' THEN 1000   
         WHEN a.PatientClass = 'ED' THEN 1001   
         WHEN a.PatientClass = 'Clinic' THEN 1002   
  END,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  tc.TimeClassID,  
  SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Amount,  
  SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded  
    AND tc.TimeClassID = 2 THEN data.ManagerValue WHEN fm.SortOrder <= bc.MonthsLoaded  
    AND tc.TimeClassID = 20 THEN data.Value ELSE 0 END) AS YTD,  
  SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Yearly,  
  SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Total  
 FROM fp.viewFactStatistics_UnPivoted data WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
  INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID  
  INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID  
  INNER JOIN fw.DimAccount a WITH (READUNCOMMITTED) ON a.AccountID = data.AccountID  
  CROSS JOIN fw.DimTimeClass tc WITH (READUNCOMMITTED)  
 WHERE data.TimeClassID = 2  
  AND data.BudgetConfigID = @BudgetConfigID  
  AND tc.TimeClassID IN (2, 20)  
  AND a.PatientClass IN (  
   'Inpatient', --UOS Inpatient  
   'Outpatient', --UOS Outpatient  
   'Other', --UOS Other  
   'Observation', --UOS Observation  
   'ED', --UOS ED  
   'Clinic' --UOS Clinic  
 )  
  GROUP BY data.BudgetConfigID, data.DepartmentID, data.AccountID, FinancialReportingID, data.FiscalYearID, data.FiscalMonthID, tc.TimeClassID, a.PatientClass  
   
 -- Statistics, Actual  
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT data.BudgetConfigID,  
  data.DepartmentID,  
  data.AccountID,  
  FinancialReportingID = CASE WHEN a.PatientClass = 'Inpatient' THEN 497   
         WHEN a.PatientClass = 'Outpatient' THEN 498   
         WHEN a.PatientClass = 'Other' THEN 499   
         WHEN a.PatientClass = 'Observation' THEN 1000   
         WHEN a.PatientClass = 'ED' THEN 1001   
         WHEN a.PatientClass = 'Clinic' THEN 1002   
  END,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  data.TimeClassID,  
  SUM(data.Value) AS Amount,  
  SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.Value ELSE 0 END) AS YTD,  
  SUM(data.Value) AS Yearly,  
  SUM(data.Value) AS Total  
 FROM [fp].[viewFactStatisticsHistory_Unpivoted] data WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
  INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID  
  INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID  
  INNER JOIN fw.DimAccount a WITH (READUNCOMMITTED) ON a.AccountID = data.AccountID  
 WHERE 1=1  
   AND data.BudgetConfigID = @BudgetConfigID  
   AND a.PatientClass IN (  
   'Inpatient',--UOS Inpatient  
   'Outpatient',--UOS Outpatient  
   'Other',--UOS Other  
   'Observation',--UOS Observation  
   'ED',--UOS ED  
   'Clinic'--UOS Clinic  
 )  
   GROUP BY data.BudgetConfigID, data.DepartmentID, data.AccountID, FinancialReportingID, data.FiscalYearID, data.FiscalMonthID, data.TimeClassID, a.PatientClass 
  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ------------------------------------------------------------------------------   Staffing   -------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
  
 -- Staffing Hours,Non-Productive Hours,Contract Labor Hours -  Projection  
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  0 AS AccountID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  data.TimeClassID,  
  SUM(data.ManagerValue) AS Amount,  
  SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.ManagerValue ELSE 0 END) AS YTD,  
  SUM(data.ManagerValue) AS Yearly,  
  SUM(data.ManagerValue) AS Total  
 FROM fp.viewFactStaffing_UnPivoted data WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
  INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID  
  INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID  
  INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID  
  INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID  
  INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID  
  INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID  
 CROSS APPLY (  
  SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive'  
  UNION ALL   
  SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive'  
  UNION ALL  
  SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor'  
 ) X  
 WHERE 1=1  
  AND data.BudgetConfigID = @BudgetConfigID  
  AND (  
     pc.NAME IN ('Non-Productive', 'Productive')  
    OR jcg.NAME = 'Contract Labor'  
  )  
  AND data.UnitTypeID = 51  
  AND data.TimeClassID = 12  
 GROUP BY data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  data.TimeClassID  
  
 -- Staffing Hours,Non-Productive Hours,Contract Labor Hours, Target/Budget  
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  0 AS AccountID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  tc.TimeClassID,  
  SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Amount,  
  SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded  
    AND tc.TimeClassID = 2 THEN data.ManagerValue WHEN fm.SortOrder <= bc.MonthsLoaded  
    AND tc.TimeClassID = 20 THEN data.Value ELSE 0 END) AS YTD,  
  SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Yearly,  
  SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Total  
 FROM fp.viewFactStaffing_UnPivoted data WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
  INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID  
  INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID  
  INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID  
  INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID  
  INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID  
  INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID  
  CROSS JOIN fw.DimTimeClass tc WITH (READUNCOMMITTED)  
  CROSS APPLY (  
   SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive'  
   UNION ALL   
   SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive'  
   UNION ALL  
   SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor'  
  ) X  
 WHERE 1=1  
  AND data.BudgetConfigID = @BudgetConfigID  
  AND (  
   pc.NAME IN ('Non-Productive', 'Productive')  
   OR jcg.NAME = 'Contract Labor'  
   )  
  AND data.UnitTypeID = 51  
  AND data.TimeClassID = 2  
  AND tc.TimeClassID IN (2, 20)  
 GROUP BY data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  tc.TimeClassID  
  
 -- Staffing Hours,Non-Productive Hours,Contract Labor Hours, Actual  
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  0 AS AccountID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  data.TimeClassID,  
  SUM(data.Value) AS Amount,  
  SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.Value ELSE 0 END) AS YTD,  
  SUM(data.Value) AS Yearly,  
  SUM(data.Value) AS Total  
 FROM [fp].[viewFactStaffingHistory_Unpivoted] data WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
  INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID  
  INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID  
  INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID  
  INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID  
  INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID  
  INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID  
  CROSS APPLY (  
   SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive'  
   UNION ALL   
   SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive'  
   UNION ALL  
   SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor'  
  ) X  
 WHERE 1=1  
  AND data.BudgetConfigID = @BudgetConfigID  
  AND (  
   pc.NAME IN ('Non-Productive', 'Productive')  
   OR jcg.NAME = 'Contract Labor'  
   )  
  AND data.UnitTypeID = 51  
 GROUP BY data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  data.TimeClassID  

  
    UNION ALL
	--JAZZ-54581 - added current year actual data again, but with TimeClassID=19 (Annualized)
   SELECT data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  0 AS AccountID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID,  
  19 AS TimeClassID,  
  SUM(data.Value) AS Amount,  
  SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.Value ELSE 0 END) AS YTD,  
  SUM(data.Value) AS Yearly,  
  SUM(data.Value) AS Total  
 FROM [fp].[viewFactStaffingHistory_Unpivoted] data WITH (READUNCOMMITTED)  
  INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID  
  INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID  
  INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID  
  INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID  
  INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID  
  INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID  
  INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID  
  CROSS APPLY (  
   SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive'  
   UNION ALL   
   SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive'  
   UNION ALL  
   SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor'  
  ) X  
 WHERE 1=1  
  AND data.BudgetConfigID = @BudgetConfigID  
  AND (  
   pc.NAME IN ('Non-Productive', 'Productive')  
   OR jcg.NAME = 'Contract Labor'  
   )  
  AND data.UnitTypeID = 51  
  AND data.TimeClassID = 1
  AND data.FiscalYearID = @FiscalYearID - 1
 GROUP BY data.BudgetConfigID,  
  data.DepartmentID,  
  data.JobCodeID,  
  X.FinancialReportingID,  
  data.FiscalYearID,  
  data.FiscalMonthID

  --JAZZ-54581
  INSERT INTO #DimensionalityForActuals (FiscalYearID, FiscalMonthID, TimeClassID, DepartmentID, JobCodeID)
  SELECT DISTINCT sc.FiscalYearID, sc.FiscalMonthID, sc.TimeClassID, sc.DepartmentID, sc.JobCodeID
  FROM #StagingCandidates sc
  WHERE sc.TimeClassID = 1
  AND sc.FiscalYearID = @FiscalYearID - 1
    
 -- Working Hours - Monthly 
 -- We will be storing JobCodeID in Account as Working Hours are otherwise getting summarized across JobCodes and skewing FTE numbers on the IS report (JAZZ-30106)
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT   
  bc.BudgetConfigID,  
  d.DepartmentID,  
  jc.JobCodeID,  
  jc.JobCodeID as AccountID, --storing JobCodeID in Account as we do not have JobCodeID in fp.FactISReportStatistics and we need this detail for WorkingHours  
  1015 as FinancialReportingID, --Stats - Other - Working Hours  
  WH.FiscalYearID,  
  WH.FiscalMonthID,  
  tc.TimeClassID,  
  WH.Hours as Amount,  
  WH.YTDHours as AmountYTD,  
  WH.Hours as Yearly,  
  WH.Hours as Total  
 FROM   
  #Dimensionality data  -- Using the staffing data to get the unique departments/job codes currently in use  
  INNER JOIN [fw].[DimDepartment] d with (READUNCOMMITTED) ON data.DepartmentID = d.DepartmentID  
  INNER JOIN [fw].[DimJobCode] jc with (READUNCOMMITTED) ON data.JobCodeID = jc.JobCodeID    
  INNER JOIN #SourceDimensionality src ON d.DepartmentID = src.DepartmentID  
  INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH WITH (READUNCOMMITTED) ON WH.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)           
  INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID  
  CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted)  
 WHERE   
  tc.TimeClassID in(1, 2, 12, 19, 20)  --JAZZ-54581 - added TimeClassID 19
  AND bc.BudgetConfigID = @BudgetConfigID  
  
 -- Working Hours - Annual  
 INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT   
  bc.BudgetConfigID,  
  d.DepartmentID,  
  jc.JobCodeID,  
  jc.JobCodeID as AccountID, --storing JobCodeID in Account as we do not have JobCodeID in fp.FactISReportStatistics and we need this detail for WorkingHours  
  1015 as FinancialReportingID, --Stats - Other - Working Hours  
  WH.FiscalYearID,  
  0 as FiscalMonthID,  
  tc.TimeClassID,  
  SUM(WH.Hours) as Amount,  
  SUM(WH.Hours) as AmountYTD,  
  SUM(WH.Hours) as Yearly,  
  SUM(WH.Hours) as Total  
 FROM   
  #Dimensionality data -- Using the staffing data to get the unique departments/job codes currently in use  
  INNER JOIN [fw].[DimDepartment] d with (READUNCOMMITTED) ON data.DepartmentID = d.DepartmentID  
  INNER JOIN [fw].[DimJobCode] jc with (READUNCOMMITTED) ON data.JobCodeID = jc.JobCodeID  
  INNER JOIN #SourceDimensionality src ON d.DepartmentID = src.DepartmentID  
  INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH WITH (READUNCOMMITTED) ON WH.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)           
  INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID  
  CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted)  
 WHERE   
  tc.TimeClassID in(1, 2, 12, 19, 20)  --JAZZ-54581 - added TimeClassID 19
  AND bc.BudgetConfigID = @BudgetConfigID  
 GROUP BY  
  bc.BudgetConfigID,  
  d.DepartmentID,  
  jc.JobCodeID,  
  WH.FiscalYearID,  
  tc.TimeClassID   
  
  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ------------------------------------------------------------------------------   Drivers   --------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
  
 INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total   
 FROM #StagingCandidates  
   
 --Inpatient/Outpatient/Observation/ED/Clinic/Other/Staffing/Non-Staffing Driver  
 INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT BudgetConfigID,  
  s.DepartmentID,  
  s.AccountID,  
  FinancialReportingID = CASE WHEN PatientClass = 'Inpatient' THEN 1003   
         WHEN PatientClass = 'Outpatient' THEN 1004   
         WHEN PatientClass = 'Other' THEN 1008  
         WHEN PatientClass = 'Observation' THEN 1005   
         WHEN PatientClass = 'ED' THEN 1006   
         WHEN PatientClass = 'Clinic' THEN 1007   
  END,  
  FiscalYearID,  
  FiscalMonthID,  
  TimeClassID,  
  Amount,  
  YTD,  
  Yearly,  
  Total  
 FROM #StagingCandidates s  
  INNER JOIN #FactStatisticsDriversAccountsStaffing a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID  
 WHERE FinancialReportingID IN (  
   497, -- Stats - UOS - Inpatient  
   498, --Stats - UOS - Outpatient  
   499, --Stats - UOS - Other  
   1000, --Stats - UOS - Observation  
   1001, --Stats - UOS - ED   
   1002 --Stats - UOS - Clinic  
 )  
    
  
 INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT BudgetConfigID,  
  s.DepartmentID,  
  s.AccountID,  
  FinancialReportingID = 1009, -- Stats - Primary UOS - Staffing Driver  
  FiscalYearID,  
  FiscalMonthID,  
  TimeClassID,  
  Amount,  
  YTD,  
  Yearly,  
  Total  
 FROM #StagingCandidates s  
  INNER JOIN #FactStatisticsDriversAccountsStaffing a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID  
 WHERE FinancialReportingID IN (  
   497, -- Stats - UOS - Inpatient  
   498, --Stats - UOS - Outpatient  
   499,--Stats - UOS - Other  
   1000,--Stats - UOS - Observation  
   1001,--Stats - UOS - ED   
   1002--Stats - UOS - Clinic  
 )  
  
 INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT BudgetConfigID,  
  s.DepartmentID,  
  s.AccountID,  
  FinancialReportingID = 1010, -- Stats - Primary UOS - Non-Staffing Driver  
  FiscalYearID,  
  FiscalMonthID,  
  TimeClassID,  
  Amount,  
  YTD,  
  Yearly,  
  Total  
 FROM #StagingCandidates s  
  INNER JOIN #FactStatisticsDriversAccountsNonStaffing a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID  
 WHERE FinancialReportingID IN (  
   497, -- Stats - UOS - Inpatient  
   498, --Stats - UOS - Outpatient  
   499,--Stats - UOS - Other  
   1000,--Stats - UOS - Observation  
   1001,--Stats - UOS - ED   
   1002--Stats - UOS - Clinic  
   )  

 INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT BudgetConfigID,  
  s.DepartmentID,  
  s.AccountID,  
  FinancialReportingID = 1008, -- Stats - Primary UOS - Non-Staffing Driver  
  FiscalYearID,  
  FiscalMonthID,  
  TimeClassID,  
  Amount,  
  YTD,  
  Yearly,  
  Total  
 FROM #StagingCandidates s  
  INNER JOIN #FactStatisticsDriversAccountsRevenueOnly a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID  
 WHERE FinancialReportingID IN (  
   497, -- Stats - UOS - Inpatient  
   498, --Stats - UOS - Outpatient  
   499,--Stats - UOS - Other  
   1000,--Stats - UOS - Observation  
   1001,--Stats - UOS - ED   
   1002--Stats - UOS - Clinic  
 )  
  
  
 INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total   
 FROM #StagingCandidatesPlusDrivers  
   
 --Hours per UOS Standard  
 INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  1012 AS FinancialReportingID, --Stats - Hours - Hours per UOS Standard  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID,  
  Amount = CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END,  
  YTD = CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END,  
  Yearly = CASE WHEN ISNULL(b.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / b.Yearly END,  
  Total = CASE WHEN ISNULL(b.Total, 0) = 0 THEN 0 ELSE a.Total / b.Total END  
 FROM #StagingCandidatesPlusDrivers a  
  INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID  
   AND a.DepartmentID = b.DepartmentID  
   AND a.FiscalYearID = b.FiscalYearID  
   AND a.FiscalMonthID = b.FiscalMonthID  
   AND a.TimeClassID = b.TimeClassID  
   AND a.FinancialReportingID = 589 --Productive Hours  
   AND b.FinancialReportingID = 1009 -- Staffing Driver  
  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- --------------------------------------------------------------------------------   FTES   ---------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
-- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  

 -- Roll Up all of the Hours at the job code level so we can correctly calculate the FTE  
 INSERT INTO #rolledUpHours (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID,
	Amount, YTD, Yearly, Total)
 SELECT a.BudgetConfigID,  
  a.DepartmentID,  
  a.JobCodeID,  
  a.AccountID,  
  a.FinancialReportingID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID,  
  SUM(a.Amount) AS Amount,  
  SUM(a.YTD) AS YTD,  
  SUM(a.Yearly) AS Yearly,  
  SUM(a.Total) AS Total  
 FROM #StagingCandidatesPlusDrivers a  
 WHERE a.FinancialReportingID IN (  
  589, -- Stats - Productive Hours  
  590, -- Stats- Non-Productive Hours  
  2591, -- Stats - Hours - GL Physician Hours  
  2590 -- Stats - GL Hours  
 )  
 OR (a.FiscalYearID <> @FiscalYearID - 1 AND a.TimeClassID <> 1)
 GROUP BY a.BudgetConfigID,  
  a.DepartmentID,  
  a.JobCodeID,  
  a.FinancialReportingID,  
  a.AccountID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID  

  UNION ALL
  --JAZZ-54581 - Pull in current year actuals differently, joining on dimensionality to make sure we're calculating FTEs correctly
 SELECT a.BudgetConfigID,  
  a.DepartmentID,  
  a.JobCodeID,  
  a.AccountID,  
  a.FinancialReportingID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID,  
  SUM(a.Amount) AS Amount,  
  SUM(a.YTD) AS YTD,  
  SUM(a.Yearly) AS Yearly,  
  SUM(a.Total) AS Total  
 FROM #StagingCandidatesPlusDrivers a  
 JOIN #DimensionalityForActuals dim 
	ON a.DepartmentID = dim.DepartmentID
	AND a.JobCodeID = dim.JobCodeID
	AND a.FiscalYearID = dim.FiscalYearID
	AND a.FiscalMonthID = dim.FiscalMonthID
	AND a.TimeClassID = dim.TimeClassID
 WHERE a.FinancialReportingID IN (  
  589, -- Stats - Productive Hours  
  590, -- Stats- Non-Productive Hours  
  2591, -- Stats - Hours - GL Physician Hours  
  2590 -- Stats - GL Hours  
 )  
 AND a.FiscalYearID = @FiscalYearID - 1
 AND a.TimeClassID = 1
 GROUP BY a.BudgetConfigID,  
  a.DepartmentID,  
  a.JobCodeID,  
  a.FinancialReportingID,  
  a.AccountID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID 
  
 --Productive FTEs  
 INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  591 AS FinancialReportingID, -- Stats - FTEs - Productive FTEs  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID,  
  Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END),  
  YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END),  
  Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END),  
  Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END)  
 FROM #rolledUpHours a  
  INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID  
   AND a.DepartmentID = b.DepartmentID  
   AND a.JobCodeID = b.JobCodeID  
   AND a.FiscalYearID = b.FiscalYearID  
   AND a.FiscalMonthID = b.FiscalMonthID  
   AND a.TimeClassID = b.TimeClassID  
   AND a.FinancialReportingID = 589 -- Stats - Productive Hours  
   AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
  LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID  
   AND a.DepartmentID = yearly.DepartmentID  
   AND a.JobCodeID = yearly.JobCodeID  
   AND a.FiscalYearID = yearly.FiscalYearID  
   AND a.TimeClassID = yearly.TimeClassID  
   AND a.FinancialReportingID = 589 -- Stats - Productive Hours  
   AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
   AND yearly.FiscalMonthID = 0  
 GROUP BY a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID  
OPTION (RECOMPILE) -- JAZZ-80822


 --Non-Productive FTEs  
 INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  592 AS FinancialReportingID, -- Stats - FTEs - Non-Productive FTEs    
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID,  
  Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END),  
  YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END),  
  Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END),  
  Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END)  
 FROM #rolledUpHours a  
  INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID  
   AND a.DepartmentID = b.DepartmentID  
   AND a.JobCodeID = b.JobCodeID  
   AND a.FiscalYearID = b.FiscalYearID  
   AND a.FiscalMonthID = b.FiscalMonthID  
   AND a.TimeClassID = b.TimeClassID  
   AND a.FinancialReportingID = 590 -- Stats- Non-Productive Hours  
   AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
  LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID  
   AND a.DepartmentID = yearly.DepartmentID  
   AND a.JobCodeID = yearly.JobCodeID  
   AND a.FiscalYearID = yearly.FiscalYearID  
   AND a.TimeClassID = yearly.TimeClassID  
   AND a.FinancialReportingID = 590 -- Stats - Non-Productive Hours  
   AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
   AND yearly.FiscalMonthID = 0  
 GROUP BY a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID  
OPTION (RECOMPILE) -- JAZZ-80822


 --Physician FTEs  
 INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  1 AS FinancialReportingID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID,  
  Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END),  
  YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END),  
  Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END),  
  Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END)  
 FROM #rolledUpHours a  
  INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID  
   AND a.DepartmentID = b.DepartmentID  
   AND a.JobCodeID = b.JobCodeID  
   AND a.FiscalYearID = b.FiscalYearID  
   AND a.FiscalMonthID = b.FiscalMonthID  
   AND a.TimeClassID = b.TimeClassID  
   AND a.FinancialReportingID = 2591 -- Stats - Hours - GL Physician Hours  
   AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
  LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID  
   AND a.DepartmentID = yearly.DepartmentID  
   AND a.JobCodeID = yearly.JobCodeID  
   AND a.FiscalYearID = yearly.FiscalYearID  
   AND a.TimeClassID = yearly.TimeClassID  
   AND a.FinancialReportingID = 2591 -- Stats - Hours - GL Physciain Hours  
   AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
   AND yearly.FiscalMonthID = 0  
 GROUP BY a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID  
OPTION (RECOMPILE) -- JAZZ-80822


 --Non-Physician Provider FTEs  
 INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  2 AS FinancialReportingID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID,  
  Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END),  
  YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END),  
  Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END),  
  Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END)  
 FROM #rolledUpHours a  
  INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID  
   AND a.DepartmentID = b.DepartmentID  
   AND a.JobCodeID = b.JobCodeID  
   AND a.FiscalYearID = b.FiscalYearID  
   AND a.FiscalMonthID = b.FiscalMonthID  
   AND a.TimeClassID = b.TimeClassID  
   AND a.FinancialReportingID = 2590 -- Stats - GL Hours  
   AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
  LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID  
   AND a.DepartmentID = yearly.DepartmentID  
   AND a.JobCodeID = yearly.JobCodeID  
   AND a.FiscalYearID = yearly.FiscalYearID  
   AND a.TimeClassID = yearly.TimeClassID  
   AND a.FinancialReportingID = 2590 -- Stats - GL Hours  
   AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours  
   AND yearly.FiscalMonthID = 0  
 GROUP BY a.BudgetConfigID,  
  a.DepartmentID,  
  a.AccountID,  
  a.FiscalYearID,  
  a.FiscalMonthID,  
  a.TimeClassID  
OPTION (RECOMPILE) -- JAZZ-80822
  
 INSERT INTO #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total  
 FROM #StagingCandidatesPlusDriversPlusUOS  
   
 INSERT INTO #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT DISTINCT BudgetConfigID,  
  fs.DepartmentID,  
  CASE WHEN FinancialReportingID = 1015 THEN 0 ELSE AccountID END AS AccountID,  --JAZZ-30106 we put JobCodeID in AccountID for 1015 but we need to ignore that here
  1014 AS FinancialReportingID, --Stats - Other - Days in Period  
  FiscalYearID = CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END,  
  fm.FiscalMonthID,  
  TimeClassID,  
  Amount = CASE WHEN (  
     (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0  
     AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0  
     )  
    OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END,  
  YTD = CASE WHEN (  
     (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0  
     AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0  
     )  
    OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END,  
  Yearly = CASE WHEN (  
     (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0  
     AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0  
     )  
    OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END,  
  Total = CASE WHEN (  
     (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0  
     AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0  
     )  
    OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END  
 FROM fw.DimFiscalMonth fm WITH (READUNCOMMITTED)  
  CROSS JOIN fw.DimFiscalYear fy WITH (READUNCOMMITTED)  
  INNER JOIN #StagingCandidatesPlusDriversPlusUOS fs ON fs.FiscalYearID = fy.FiscalYearID  --JAZZ-46281 changed this to use the temp table and not fp.FactISReportStatistics 
   AND fs.FiscalMonthID = fm.FiscalMonthID  
  INNER JOIN #SourceDimensionality src ON fs.DepartmentID = src.DepartmentID  
 WHERE fm.FiscalMonthID != 0  
  AND fy.FiscalYearID != 0  
  AND fs.BudgetConfigID = @BudgetConfigID  

   --JAZZ-1162 - INSERT "Days in Period" at annual level
	INSERT INTO #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
	SELECT DISTINCT
		fs.BudgetConfigID,
		fs.DepartmentID,
		0 as AccountID,
		1014 AS FinancialReportingID, --Stats - Other - Days in Period  
		diy.FiscalYearID,
		0 as FiscalMonthID,
		diy.TimeClassID, 
		Amount = diy.DaysInYear,
		YTD = diy.DaysInYear,
		Yearly = diy.DaysInYear,
		Total = diy.DaysInYear		 
	FROM #StagingCandidatesPlusDriversPlusUOS fs
    INNER JOIN #SourceDimensionality src ON fs.DepartmentID = src.DepartmentID  --JAZZ-46281 this should be unnecessary but am leaving here as a safeguard
	INNER JOIN #DaysInYear diy 
		on diy.FiscalYearID = fs.FiscalYearID 
		AND diy.TimeClassID = fs.TimeClassID
	WHERE fs.FiscalYearID <> 0
	GROUP BY
		fs.BudgetConfigID,
		fs.DepartmentID,
		diy.FiscalYearID,
		diy.TimeClassID, 
		diy.DaysInYear

  --JAZZ-54581 - Annualize all data
  UPDATE #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays
  SET 
	Amount = Amount * @AnnualizationFactor,
	YTD = YTD * @AnnualizationFactor,
	Yearly = Yearly * @AnnualizationFactor,
	Total = Total * @AnnualizationFactor
  WHERE 
	FiscalYearID = @FiscalYearID - 1
	AND TimeClassID = 19

  --JAZZ-54581 - delete all TimeClass=19 data for all fiscal years not current year
  DELETE FROM #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays
  WHERE 
    FiscalYearID != @FiscalYearID - 1
	AND TimeClassID = 19
  
 INSERT INTO #SRC (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total)  
 SELECT   
  cte.BudgetConfigID,  
  cte.DepartmentID,  
  cte.AccountID,  
  cte.FinancialReportingID,  
  cte.FiscalYearID,  
  cte.FiscalMonthID,  
  cte.TimeClassID,  
  SUM(cte.Amount) as Amount,  
  SUM(cte.YTD) as YTD,  
  SUM(cte.Yearly) as Yearly,  
  SUM(cte.Total) as Total  
 FROM #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays cte  
 WHERE cte.BudgetConfigID = @BudgetConfigID  
 GROUP BY cte.BudgetConfigID,  
  cte.DepartmentID,  
  cte.AccountID,  
  cte.FinancialReportingID,  
  cte.FiscalYearID,  
  cte.FiscalMonthID,  
  cte.TimeClassID  
  
   
 IF (@IsDebug = 1)  
 BEGIN  
    
  SELECT '#SourceDimensionality', DepartmentID FROM #SourceDimensionality  
  SELECT '#FactStatisticsDriversAccountsStaffing', AccountID, DepartmentID FROM #FactStatisticsDriversAccountsStaffing  
  SELECT '#FactStatisticsDriversAccountsNonStaffing', AccountID, DepartmentID FROM #FactStatisticsDriversAccountsNonStaffing  
  SELECT '#FactStatisticsDriversAccountsRevenueOnly', AccountID, DepartmentID FROM #FactStatisticsDriversAccountsRevenueOnly
  SELECT '#StagingCandidates', BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidates  
  SELECT '#StagingCandidatesPlusDrivers', BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidatesPlusDrivers  
  SELECT '#StagingCandidatesPlusDriversPlusUOS', BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidatesPlusDriversPlusUOS  
  SELECT '#StagingCandidatesPlusDriversPlusUOSPlusWorkingDays', BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays  
  SELECT '#SRC', BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #SRC  
   
 END ELSE  
 BEGIN  
    
  WITH TGT AS   
  (  
   SELECT BudgetConfigID, s.DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total  
   FROM fp.FactISReportStatistics s  
    INNER JOIN #SourceDimensionality sd ON s.DepartmentID = sd.DepartmentID  
   WHERE s.BudgetConfigID = @BudgetConfigID  
  )  
  MERGE TGT AS target  
 USING #SRC AS source  
  ON      source.BudgetConfigID = target.BudgetConfigID  
   AND source.DepartmentID = target.DepartmentID  
   AND source.AccountID = target.AccountID  
   AND source.FinancialReportingID = target.FinancialReportingID  
   AND source.FiscalYearID = target.FiscalYearID  
   AND source.FiscalMonthID = target.FiscalMonthID  
   AND source.TimeClassID = target.TimeClassID  
 WHEN MATCHED  
  AND (  
   source.Amount <> target.Amount  
   OR source.YTD <> target.YTD  
   OR source.Yearly <> target.Yearly  
   OR source.Total <> target.Total  
   )  
  THEN  
   UPDATE  
   SET Amount = source.Amount,  
    YTD = source.YTD,  
    Yearly = source.Yearly,  
    Total = source.Total  
 WHEN NOT MATCHED BY TARGET  
  THEN  
   INSERT (  
    BudgetConfigID,  
    DepartmentID,  
    AccountID,  
    FinancialReportingID,  
    FiscalYearID,  
    FiscalMonthID,  
    TimeClassID,  
    Amount,  
    YTD,  
    Yearly,  
    Total  
    )  
   VALUES (  
    source.BudgetConfigID,  
    source.DepartmentID,  
    source.AccountID,  
    source.FinancialReportingID,  
    source.FiscalYearID,  
    source.FiscalMonthID,  
    source.TimeClassID,  
    source.Amount,  
    source.YTD,  
    source.Yearly,  
    source.Total  
    )  
 WHEN NOT MATCHED BY Source  
  THEN  
   DELETE;  
 END  

 END
GO


---------------------------------------------

-- fp.procReprocessEncountersAddProviderTask
/**************************************************************
** CID  Date         Author   WI			Description
** 1	2022-11-28	 NH,OA	  JAZZ-38339	Encounters Add Provider: reprocess provider
** 2	2023-05-18	 MY		  JAZZ-55153	Update to new structure
*************************************************************/	 
CREATE    PROCEDURE [fp].[procReprocessEncountersAddProviderTask]
	@ServiceProviderID INT
 AS
 BEGIN

--Select AdjustmentGUID
DECLARE @adjGuid UNIQUEIDENTIFIER;

SELECT DISTINCT @adjGuid = AdjustmentGUID 
FROM fp.AddProviderEncountersDataForCharges
WHERE IsProcessed = 0 AND ServiceProviderID = @ServiceProviderID

-- Insert all dimensionality by adjGuid to identify records in ChargeVolume
SELECT * 
	INTO #addProvEncDataForChargesToRemove
	FROM fp.AddProviderEncountersDataForCharges
	WHERE AdjustmentGUID = @adjGuid

-- Identifying records which we want to remove in FactChargeVolume
SELECT DISTINCT fcv.* INTO #FactChargeVolumesToRemove
FROM fp.ChargeVolume fcv
	INNER JOIN #addProvEncDataForChargesToRemove apetr ON fcv.BudgetConfigID = apetr.BudgetConfigID
	AND fcv.EntityID = apetr.EntityID
	AND fcv.DepartmentID = apetr.DepartmentID
	AND fcv.ServiceLineID = apetr.ServiceLineID
	AND fcv.PatientClassID = apetr.PatientClassID
	AND fcv.AgeCohortID = apetr.AgeCohortID
	AND fcv.MedicalSurgicalID = apetr.MedicalSurgicalID
	AND fcv.UnitTypeID = apetr.UnitTypeID
	AND fcv.ServiceEntityID = apetr.ServiceEntityID
	AND fcv.MSDRGID = apetr.MSDRGID
	AND fcv.UBRevCodeID = apetr.UBRevCodeID
	AND fcv.PrimaryCPTID = apetr.PrimaryCPTID
	AND fcv.ServiceProviderID = apetr.ServiceProviderID
	AND fcv.ServiceProviderSpecialtyID = apetr.ServiceProviderSpecialtyID
	AND fcv.PerformingProviderID = apetr.PerformingProviderID
	AND fcv.PerformingProviderSpecialtyID = apetr.PerformingProviderSpecialtyID
	AND fcv.BillingCPTID = apetr.BillingCPTID

BEGIN TRY
	BEGIN TRAN

		--Clean up additional table from proc padChargeVolume
		DELETE fcvh 
		FROM [fp].[ChargeVolumeHistory] fcvh
		INNER JOIN #FactChargeVolumesToRemove fcvtr ON fcvh.ChargeVolumeID = fcvtr.ChargeVolumeID

		--Clean up ChargeVolume
		DELETE fcv 
		FROM fp.ChargeVolume fcv
			INNER JOIN #FactChargeVolumesToRemove fcvtr ON fcv.ChargeVolumeID = fcvtr.ChargeVolumeID

		IF @@TRANCOUNT > 0 COMMIT TRAN
END TRY
BEGIN CATCH
	IF @@TRANCOUNT > 0 ROLLBACK TRAN
END CATCH;
	

DROP TABLE IF EXISTS #addProvEncDataForChargesToRemove
DROP TABLE IF EXISTS #FactChargeVolumesToRemove

--Reprocess 
DECLARE @AssemblyQualifiedName varchar(1024);
DECLARE @SLEncounterAdjGUID UNIQUEIDENTIFIER;

SET @AssemblyQualifiedName = 'Strata.CS.Jazz.ABB.PlanEditor.Provider.EncountersAddProviderTask, Strata.CS.Jazz.ABB';
 
--xmlContent for EncountersAddProviderTask is @SLEncounterAdjGUID
--SHOULD BE in ""
SELECT @SLEncounterAdjGUID = SLEncounterAdjustmentGUID 
FROM fp.AddProviderSummary
WHERE DCVolumeAdjustmentGUID = @adjGuid

DECLARE @xmlContent VARCHAR(50) = '"' + CAST(@SLEncounterAdjGUID AS VARCHAR(50)) + '"';
 
DECLARE @statusCode INT;
EXEC dbo.procCreateTask
	@taskTypeName = @AssemblyQualifiedName,
	@contextXML = @xmlContent,
	@userName = 'HangfireMigration',
	@taskSource = 'Migration',
	@statusCode = @statusCode OUTPUT;

END
GO


---------------------------------------------

-- fp.procResetBenefitsFixedAccountRateAndDrivers
/**************************************************************
** Change History
** CID   Date		 Author	 WI			Description
** 1 	 2020-05-28  BK 	 D-08014 	Created proc to reset all driver and rate data for fixed benefits accounts to 0
*************************************************************/
CREATE   PROCEDURE [fp].[procResetBenefitsFixedAccountRateAndDrivers]
 	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
 	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 WITH RECOMPILE
 AS
 BEGIN
  
	CREATE TABLE #FixedAccounts (AccountID int)

	
	INSERT INTO #FixedAccounts 
	SELECT AccountID FROM fp.AccountFlexConfig WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID AND FlexMethodClassName = ''

	IF NOT EXISTS (SELECT * FROM #FixedAccounts)
	BEGIN
		RETURN;
	END

	CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int)
	INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID)
	SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
    -- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID		
	END	
 	
	UPDATE ben 
	SET   SampledBudget01 = 0
		, SampledBudget02 = 0
		, SampledBudget03 = 0
		, SampledBudget04 = 0
		, SampledBudget05 = 0
		, SampledBudget06 = 0
		, SampledBudget07 = 0
		, SampledBudget08 = 0
		, SampledBudget09 = 0
		, SampledBudget10 = 0
		, SampledBudget11 = 0
		, SampledBudget12 = 0
		, SampledProjection01 = 0
		, SampledProjection02 = 0
		, SampledProjection03 = 0
		, SampledProjection04 = 0
		, SampledProjection05 = 0
		, SampledProjection06 = 0
		, SampledProjection07 = 0
		, SampledProjection08 = 0
		, SampledProjection09 = 0
		, SampledProjection10 = 0
		, SampledProjection11 = 0
		, SampledProjection12 = 0
		, InitialBudget01 = 0
		, InitialBudget02 = 0
		, InitialBudget03 = 0
		, InitialBudget04 = 0
		, InitialBudget05 = 0
		, InitialBudget06 = 0
		, InitialBudget07 = 0
		, InitialBudget08 = 0
		, InitialBudget09 = 0
		, InitialBudget10 = 0
		, InitialBudget11 = 0
		, InitialBudget12 = 0
		, InitialProjection01 = 0
		, InitialProjection02 = 0
		, InitialProjection03 = 0
		, InitialProjection04 = 0
		, InitialProjection05 = 0
		, InitialProjection06 = 0
		, InitialProjection07 = 0
		, InitialProjection08 = 0
		, InitialProjection09 = 0
		, InitialProjection10 = 0
		, InitialProjection11 = 0
		, InitialProjection12 = 0
	FROM fp.FactBenefits ben INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID
	INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID
	WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171)

	UPDATE budget
	SET   budget.FlexedValue01 = 0
		, budget.FlexedValue02 = 0
		, budget.FlexedValue03 = 0
		, budget.FlexedValue04 = 0
		, budget.FlexedValue05 = 0
		, budget.FlexedValue06 = 0
		, budget.FlexedValue07 = 0
		, budget.FlexedValue08 = 0
		, budget.FlexedValue09 = 0
		, budget.FlexedValue10 = 0
		, budget.FlexedValue11 = 0
		, budget.FlexedValue12 = 0
		, budget.AdjustedValue01 = 0
		, budget.AdjustedValue02 = 0
		, budget.AdjustedValue03 = 0
		, budget.AdjustedValue04 = 0
		, budget.AdjustedValue05 = 0
		, budget.AdjustedValue06 = 0
		, budget.AdjustedValue07 = 0
		, budget.AdjustedValue08 = 0
		, budget.AdjustedValue09 = 0
		, budget.AdjustedValue10 = 0
		, budget.AdjustedValue11 = 0
		, budget.AdjustedValue12 = 0
	FROM [fp].[FactBenefits] ben
		INNER JOIN [fp].[FactBenefitsBudget] budget ON ben.BenefitsID = budget.BenefitsID
		INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID
		INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171)

	UPDATE proj
		SET   proj.FlexedValue01 = 0
			, proj.FlexedValue02 = 0
			, proj.FlexedValue03 = 0
			, proj.FlexedValue04 = 0
			, proj.FlexedValue05 = 0
			, proj.FlexedValue06 = 0
			, proj.FlexedValue07 = 0
			, proj.FlexedValue08 = 0
			, proj.FlexedValue09 = 0
			, proj.FlexedValue10 = 0
			, proj.FlexedValue11 = 0
			, proj.FlexedValue12 = 0
			, proj.AdjustedValue01 = 0
			, proj.AdjustedValue02 = 0
			, proj.AdjustedValue03 = 0
			, proj.AdjustedValue04 = 0
			, proj.AdjustedValue05 = 0
			, proj.AdjustedValue06 = 0
			, proj.AdjustedValue07 = 0
			, proj.AdjustedValue08 = 0
			, proj.AdjustedValue09 = 0
			, proj.AdjustedValue10 = 0
			, proj.AdjustedValue11 = 0
			, proj.AdjustedValue12 = 0
		FROM [fp].[FactBenefits] ben
			INNER JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID
		    INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID
			INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID
			WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171)

	UPDATE hist
	SET   hist.PriorYearActualValue01 = 0
		, hist.PriorYearActualValue02 = 0
		, hist.PriorYearActualValue03 = 0
		, hist.PriorYearActualValue04 = 0
		, hist.PriorYearActualValue05 = 0
		, hist.PriorYearActualValue06 = 0
		, hist.PriorYearActualValue07 = 0
		, hist.PriorYearActualValue08 = 0
		, hist.PriorYearActualValue09 = 0
		, hist.PriorYearActualValue10 = 0
		, hist.PriorYearActualValue11 = 0
		, hist.PriorYearActualValue12 = 0
		, hist.ActualYTDValue01 = 0
		, hist.ActualYTDValue02 = 0
		, hist.ActualYTDValue03 = 0
		, hist.ActualYTDValue04 = 0
		, hist.ActualYTDValue05 = 0
		, hist.ActualYTDValue06 = 0
		, hist.ActualYTDValue07 = 0
		, hist.ActualYTDValue08 = 0
		, hist.ActualYTDValue09 = 0
		, hist.ActualYTDValue10 = 0
		, hist.ActualYTDValue11 = 0
		, hist.ActualYTDValue12 = 0
		, hist.CurrentYearBudget01 = 0
		, hist.CurrentYearBudget02 = 0
		, hist.CurrentYearBudget03 = 0
		, hist.CurrentYearBudget04 = 0
		, hist.CurrentYearBudget05 = 0
		, hist.CurrentYearBudget06 = 0
		, hist.CurrentYearBudget07 = 0
		, hist.CurrentYearBudget08 = 0
		, hist.CurrentYearBudget09 = 0
		, hist.CurrentYearBudget10 = 0
		, hist.CurrentYearBudget11 = 0
		, hist.CurrentYearBudget12 = 0
	FROM [fp].[FactBenefits] ben
		INNER JOIN [fp].[FactBenefitsHistory] hist ON ben.BenefitsID = hist.BenefitsID
		INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID
		INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171)


 END
GO


---------------------------------------------

-- fp.procResetBenefitsFlexMethod
CREATE PROCEDURE [fp].[procResetBenefitsFlexMethod]
	@EntityGroupConfigID INT
	,@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS 
BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2   2021-02-16  NN      JAZZ-466	Remove null joins
	 *************************************************************/ 
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID	
	END	
	
	UPDATE fb
    SET FlexMethodID = 0
    FROM [fp].[FactBenefits] fb 
	INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID
		INNER JOIN [fp].[EntityGroupConfig] egc 
			ON fb.EntityGroupConfigID = egc.EntityGroupConfigID
		INNER JOIN [fp].[AccountFlexConfig] afc 
			ON fb.AccountID = afc.AccountID
			AND egc.EntityGroupConfigGUID = afc.EntityGroupConfigGUID
    WHERE fb.EntityGroupConfigID = @EntityGroupConfigID
		AND FlexMethodID <> 0
		AND FlexMethodClassName = ''

	UPDATE fb
    SET FlexMethodID = 1
    FROM [fp].[FactBenefits] fb 
	INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID 
		INNER JOIN [fp].[EntityGroupConfig] egc 
			ON fb.EntityGroupConfigID = egc.EntityGroupConfigID
		INNER JOIN [fp].[AccountFlexConfig] afc 
			ON fb.AccountID = afc.AccountID
			AND egc.EntityGroupConfigGUID = afc.EntityGroupConfigGUID
    WHERE fb.EntityGroupConfigID = @EntityGroupConfigID
		AND FlexMethodID <> 1
		AND FlexMethodClassName = 'FlexAccountByFTEs'	
		
	UPDATE fb
    SET FlexMethodID = 2
    FROM [fp].[FactBenefits] fb 
	INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID
		INNER JOIN [fp].[EntityGroupConfig] egc 
			ON fb.EntityGroupConfigID = egc.EntityGroupConfigID
		INNER JOIN [fp].[AccountFlexConfig] afc 
			ON fb.AccountID = afc.AccountID
			AND egc.EntityGroupConfigGUID = afc.EntityGroupConfigGUID
    WHERE fb.EntityGroupConfigID = @EntityGroupConfigID
		AND FlexMethodID <> 2
		AND FlexMethodClassName = 'FlexAccountBySalaries'	

END
GO


---------------------------------------------

-- fp.procResetBenefitsManager
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1 	2022-08-09  JB  	JAZZ-23177	Switch usages of funcGetSourceDimensionalityAsTable to a temp table. Combined separate budget staffing temp tables. 
*************************************************************/
CREATE PROCEDURE [fp].[procResetBenefitsManager]
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	
	IF OBJECT_ID('tempdb..#tmpResetBenefitsItems') IS NOT NULL DROP TABLE #tmpResetBenefitsItems
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #tmpResetBenefitsItems (
		BenefitsID INT
	)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN
		INSERT INTO #tmpResetBenefitsItems (BenefitsID)
		SELECT BenefitsID
		FROM [fp].[FactBenefits] data
			INNER JOIN #FilterByDepartment SD ON (SD.DepartmentID = data.DepartmentID) 
		WHERE data.BudgetConfigID = @BudgetConfigID
	END
	ELSE BEGIN
		INSERT INTO #tmpResetBenefitsItems (BenefitsID)
		SELECT BenefitsID
		FROM [fp].[FactBenefits]
		WHERE BudgetConfigID = @BudgetConfigID
	END
	
	UPDATE mgr
    SET
        mgr.AdjustedValue01 = admin.AdjustedValue01,
        mgr.AdjustedValue02 = admin.AdjustedValue02,
        mgr.AdjustedValue03 = admin.AdjustedValue03,
        mgr.AdjustedValue04 = admin.AdjustedValue04,
        mgr.AdjustedValue05 = admin.AdjustedValue05,
        mgr.AdjustedValue06 = admin.AdjustedValue06,
        mgr.AdjustedValue07 = admin.AdjustedValue07,
        mgr.AdjustedValue08 = admin.AdjustedValue08,
        mgr.AdjustedValue09 = admin.AdjustedValue09,
        mgr.AdjustedValue10 = admin.AdjustedValue10,
        mgr.AdjustedValue11 = admin.AdjustedValue11,
        mgr.AdjustedValue12 = admin.AdjustedValue12,
        mgr.LockType = admin.LockType,
        mgr.LockFlag = admin.LockFlag
    FROM [fp].[FactBenefitsBudget] mgr
        INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID
        INNER JOIN [fp].[FactBenefitsBudget] admin ON admin.BenefitsID = mgr.BenefitsID
		INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
        AND mgr.LockType NOT IN (2, 3)
        AND admin.BudgetPhaseID = 2
        AND mgr.BudgetPhaseID = 3
        AND (
            mgr.AdjustedValue01 != admin.AdjustedValue01 OR 
            mgr.AdjustedValue02 != admin.AdjustedValue02 OR 
            mgr.AdjustedValue03 != admin.AdjustedValue03 OR 
            mgr.AdjustedValue04 != admin.AdjustedValue04 OR 
            mgr.AdjustedValue05 != admin.AdjustedValue05 OR 
            mgr.AdjustedValue06 != admin.AdjustedValue06 OR 
            mgr.AdjustedValue07 != admin.AdjustedValue07 OR 
            mgr.AdjustedValue08 != admin.AdjustedValue08 OR 
            mgr.AdjustedValue09 != admin.AdjustedValue09 OR 
            mgr.AdjustedValue10 != admin.AdjustedValue10 OR 
            mgr.AdjustedValue11 != admin.AdjustedValue11 OR 
            mgr.AdjustedValue12 != admin.AdjustedValue12)
            
   UPDATE mgr
    SET
        mgr.AdjustedValue01 = admin.AdjustedValue01,
        mgr.AdjustedValue02 = admin.AdjustedValue02,
        mgr.AdjustedValue03 = admin.AdjustedValue03,
        mgr.AdjustedValue04 = admin.AdjustedValue04,
        mgr.AdjustedValue05 = admin.AdjustedValue05,
        mgr.AdjustedValue06 = admin.AdjustedValue06,
        mgr.AdjustedValue07 = admin.AdjustedValue07,
        mgr.AdjustedValue08 = admin.AdjustedValue08,
        mgr.AdjustedValue09 = admin.AdjustedValue09,
        mgr.AdjustedValue10 = admin.AdjustedValue10,
        mgr.AdjustedValue11 = admin.AdjustedValue11,
        mgr.AdjustedValue12 = admin.AdjustedValue12,
        mgr.LockType = admin.LockType,
        mgr.LockFlag = admin.LockFlag
    FROM [fp].[FactBenefitsProjection] mgr
        INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID
        INNER JOIN [fp].[FactBenefitsProjection] admin ON admin.BenefitsID = mgr.BenefitsID
		INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
        AND mgr.LockType NOT IN (2, 3)
        AND admin.BudgetPhaseID = 2
        AND mgr.BudgetPhaseID = 3
        AND (
            mgr.AdjustedValue01 != admin.AdjustedValue01 OR 
            mgr.AdjustedValue02 != admin.AdjustedValue02 OR 
            mgr.AdjustedValue03 != admin.AdjustedValue03 OR 
            mgr.AdjustedValue04 != admin.AdjustedValue04 OR 
            mgr.AdjustedValue05 != admin.AdjustedValue05 OR 
            mgr.AdjustedValue06 != admin.AdjustedValue06 OR 
            mgr.AdjustedValue07 != admin.AdjustedValue07 OR 
            mgr.AdjustedValue08 != admin.AdjustedValue08 OR 
            mgr.AdjustedValue09 != admin.AdjustedValue09 OR 
            mgr.AdjustedValue10 != admin.AdjustedValue10 OR 
            mgr.AdjustedValue11 != admin.AdjustedValue11 OR 
            mgr.AdjustedValue12 != admin.AdjustedValue12)

END
GO


---------------------------------------------

-- fp.procResetBenefitsManagerFixedAccounts
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1 	2022-08-09  JB  	JAZZ-23177	Switch usages of funcGetSourceDimensionalityAsTable to a temp table. Combined separate budget staffing temp tables. 
*************************************************************/

 CREATE PROCEDURE [fp].[procResetBenefitsManagerFixedAccounts]
 	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
 AS
 BEGIN
 IF OBJECT_ID('tempdb..#tmpResetBenefitsItems') IS NOT NULL DROP TABLE #tmpResetBenefitsItems
 IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	CREATE TABLE #tmpResetBenefitsItems (
		BenefitsID INT
	)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #tmpResetBenefitsItems (BenefitsID)
		SELECT BenefitsID
		FROM [fp].[FactBenefits] data
			INNER JOIN #FilterByDepartment SD ON (SD.DepartmentID = data.DepartmentID) 
		WHERE data.FlexMethodID = 0 and data.BudgetConfigID = @BudgetConfigID
	END
	ELSE BEGIN
		INSERT INTO #tmpResetBenefitsItems (BenefitsID)
		SELECT BenefitsID
		FROM [fp].[FactBenefits]
		WHERE FlexMethodID = 0 and BudgetConfigID = @BudgetConfigID
	END
	
	UPDATE mgr
    SET
        mgr.AdjustedValue01 = admin.AdjustedValue01,
        mgr.AdjustedValue02 = admin.AdjustedValue02,
        mgr.AdjustedValue03 = admin.AdjustedValue03,
        mgr.AdjustedValue04 = admin.AdjustedValue04,
        mgr.AdjustedValue05 = admin.AdjustedValue05,
        mgr.AdjustedValue06 = admin.AdjustedValue06,
        mgr.AdjustedValue07 = admin.AdjustedValue07,
        mgr.AdjustedValue08 = admin.AdjustedValue08,
        mgr.AdjustedValue09 = admin.AdjustedValue09,
        mgr.AdjustedValue10 = admin.AdjustedValue10,
        mgr.AdjustedValue11 = admin.AdjustedValue11,
        mgr.AdjustedValue12 = admin.AdjustedValue12,
        mgr.LockType = admin.LockType,
        mgr.LockFlag = admin.LockFlag
    FROM [fp].[FactBenefitsBudget] mgr
        INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID
        INNER JOIN [fp].[FactBenefitsBudget] admin ON admin.BenefitsID = mgr.BenefitsID
		INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
        AND mgr.LockType NOT IN (2, 3)
        AND admin.BudgetPhaseID = 2
        AND mgr.BudgetPhaseID = 3
        AND (
            mgr.AdjustedValue01 != admin.AdjustedValue01 OR 
            mgr.AdjustedValue02 != admin.AdjustedValue02 OR 
            mgr.AdjustedValue03 != admin.AdjustedValue03 OR 
            mgr.AdjustedValue04 != admin.AdjustedValue04 OR 
            mgr.AdjustedValue05 != admin.AdjustedValue05 OR 
            mgr.AdjustedValue06 != admin.AdjustedValue06 OR 
            mgr.AdjustedValue07 != admin.AdjustedValue07 OR 
            mgr.AdjustedValue08 != admin.AdjustedValue08 OR 
            mgr.AdjustedValue09 != admin.AdjustedValue09 OR 
            mgr.AdjustedValue10 != admin.AdjustedValue10 OR 
            mgr.AdjustedValue11 != admin.AdjustedValue11 OR 
            mgr.AdjustedValue12 != admin.AdjustedValue12)
            
   UPDATE mgr
    SET
        mgr.AdjustedValue01 = admin.AdjustedValue01,
        mgr.AdjustedValue02 = admin.AdjustedValue02,
        mgr.AdjustedValue03 = admin.AdjustedValue03,
        mgr.AdjustedValue04 = admin.AdjustedValue04,
        mgr.AdjustedValue05 = admin.AdjustedValue05,
        mgr.AdjustedValue06 = admin.AdjustedValue06,
        mgr.AdjustedValue07 = admin.AdjustedValue07,
        mgr.AdjustedValue08 = admin.AdjustedValue08,
        mgr.AdjustedValue09 = admin.AdjustedValue09,
        mgr.AdjustedValue10 = admin.AdjustedValue10,
        mgr.AdjustedValue11 = admin.AdjustedValue11,
        mgr.AdjustedValue12 = admin.AdjustedValue12,
        mgr.LockType = admin.LockType,
        mgr.LockFlag = admin.LockFlag
    FROM [fp].[FactBenefitsProjection] mgr
        INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID
        INNER JOIN [fp].[FactBenefitsProjection] admin ON admin.BenefitsID = mgr.BenefitsID
		INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
        AND mgr.LockType NOT IN (2, 3)
        AND admin.BudgetPhaseID = 2
        AND mgr.BudgetPhaseID = 3
        AND (
            mgr.AdjustedValue01 != admin.AdjustedValue01 OR 
            mgr.AdjustedValue02 != admin.AdjustedValue02 OR 
            mgr.AdjustedValue03 != admin.AdjustedValue03 OR 
            mgr.AdjustedValue04 != admin.AdjustedValue04 OR 
            mgr.AdjustedValue05 != admin.AdjustedValue05 OR 
            mgr.AdjustedValue06 != admin.AdjustedValue06 OR 
            mgr.AdjustedValue07 != admin.AdjustedValue07 OR 
            mgr.AdjustedValue08 != admin.AdjustedValue08 OR 
            mgr.AdjustedValue09 != admin.AdjustedValue09 OR 
            mgr.AdjustedValue10 != admin.AdjustedValue10 OR 
            mgr.AdjustedValue11 != admin.AdjustedValue11 OR 
            mgr.AdjustedValue12 != admin.AdjustedValue12)
 END
GO


---------------------------------------------

-- fp.procResetChargeVolume
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2023-02-15  BK      JAZZ-48305  Create proc for new structure
** 2    2023-05-25  MY      JAZZ-55544  Add Projection Lock Cols
*************************************************************/
CREATE   PROCEDURE [fp].[procResetChargeVolume]
	 @EntityGroupConfigID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
 AS
 BEGIN
 
 IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
 
 	 -- Build the department filter  
 SELECT DISTINCT DepartmentID   
 INTO #FilterByDepartment   
 FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)  
  
 IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)  
 BEGIN  
  --Unfiltered
  UPDATE cv
    SET
        cv.TargetAdjusted01 = cv.InitialBudget01, cv.TargetAdjusted02 = cv.InitialBudget02, cv.TargetAdjusted03 = cv.InitialBudget03, cv.TargetAdjusted04 = cv.InitialBudget04,	cv.TargetAdjusted05 = cv.InitialBudget05, cv.TargetAdjusted06 = cv.InitialBudget06, cv.TargetAdjusted07 = cv.InitialBudget07, cv.TargetAdjusted08 = cv.InitialBudget08,	cv.TargetAdjusted09 = cv.InitialBudget09, cv.TargetAdjusted10 = cv.InitialBudget10, cv.TargetAdjusted11 = cv.InitialBudget11, cv.TargetAdjusted12 = cv.InitialBudget12,
        cv.BudgetAdjusted01 = cv.InitialBudget01, cv.BudgetAdjusted02 = cv.InitialBudget02, cv.BudgetAdjusted03 = cv.InitialBudget03, cv.BudgetAdjusted04 = cv.InitialBudget04, cv.BudgetAdjusted05 = cv.InitialBudget05, cv.BudgetAdjusted06 = cv.InitialBudget06, cv.BudgetAdjusted07 = cv.InitialBudget07, cv.BudgetAdjusted08 = cv.InitialBudget08, cv.BudgetAdjusted09 = cv.InitialBudget09, cv.BudgetAdjusted10 = cv.InitialBudget10, cv.BudgetAdjusted11 = cv.InitialBudget11, cv.BudgetAdjusted12 = cv.InitialBudget12,
        cv.ProjectionAdjusted01 = cv.InitialProjection01, cv.ProjectionAdjusted02 = cv.InitialProjection02, cv.ProjectionAdjusted03 = cv.InitialProjection03, cv.ProjectionAdjusted04 = cv.InitialProjection04, cv.ProjectionAdjusted05 = cv.InitialProjection05, cv.ProjectionAdjusted06 = cv.InitialProjection06, cv.ProjectionAdjusted07 = cv.InitialProjection07, cv.ProjectionAdjusted08 = cv.InitialProjection08, cv.ProjectionAdjusted09 = cv.InitialProjection09, cv.ProjectionAdjusted10 = cv.InitialProjection10, cv.ProjectionAdjusted11 = cv.InitialProjection11, cv.ProjectionAdjusted12 = cv.InitialProjection12,
        cv.TargetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.TargetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.TargetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.TargetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04,	cv.TargetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.TargetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.TargetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.TargetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08,	cv.TargetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.TargetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.TargetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.TargetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12,
        cv.BudgetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.BudgetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.BudgetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.BudgetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04,	cv.BudgetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.BudgetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.BudgetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.BudgetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08,	cv.BudgetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.BudgetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.BudgetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.BudgetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12,
        cv.ProjectionUnitsPerEncounterAdjusted01 = cv.InitialProjectionUnitsPerEncounter01, cv.ProjectionUnitsPerEncounterAdjusted02 = cv.InitialProjectionUnitsPerEncounter02, cv.ProjectionUnitsPerEncounterAdjusted03 = cv.InitialProjectionUnitsPerEncounter03, cv.ProjectionUnitsPerEncounterAdjusted04 = cv.InitialProjectionUnitsPerEncounter04,	cv.ProjectionUnitsPerEncounterAdjusted05 = cv.InitialProjectionUnitsPerEncounter05, cv.ProjectionUnitsPerEncounterAdjusted06 = cv.InitialProjectionUnitsPerEncounter06, cv.ProjectionUnitsPerEncounterAdjusted07 = cv.InitialProjectionUnitsPerEncounter07, cv.ProjectionUnitsPerEncounterAdjusted08 = cv.InitialProjectionUnitsPerEncounter08,	cv.ProjectionUnitsPerEncounterAdjusted09 = cv.InitialProjectionUnitsPerEncounter09, cv.ProjectionUnitsPerEncounterAdjusted10 = cv.InitialProjectionUnitsPerEncounter10, cv.ProjectionUnitsPerEncounterAdjusted11 = cv.InitialProjectionUnitsPerEncounter11, cv.ProjectionUnitsPerEncounterAdjusted12 = cv.InitialProjectionUnitsPerEncounter12,
        cv.TargetLockType = 0,
        cv.TargetLockFlag = 0,
        cv.BudgetLockType = 0,
        cv.BudgetLockFlag = 0,
		cv.ProjectionLockType = 0,
        cv.ProjectionLockFlag = 0
    FROM [fp].[ChargeVolume] cv
    WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
 
 END ELSE BEGIN
   --Filtered
   UPDATE cv
    SET
        cv.TargetAdjusted01 = cv.InitialBudget01, cv.TargetAdjusted02 = cv.InitialBudget02, cv.TargetAdjusted03 = cv.InitialBudget03, cv.TargetAdjusted04 = cv.InitialBudget04,	cv.TargetAdjusted05 = cv.InitialBudget05, cv.TargetAdjusted06 = cv.InitialBudget06, cv.TargetAdjusted07 = cv.InitialBudget07, cv.TargetAdjusted08 = cv.InitialBudget08,	cv.TargetAdjusted09 = cv.InitialBudget09, cv.TargetAdjusted10 = cv.InitialBudget10, cv.TargetAdjusted11 = cv.InitialBudget11, cv.TargetAdjusted12 = cv.InitialBudget12,
        cv.BudgetAdjusted01 = cv.InitialBudget01, cv.BudgetAdjusted02 = cv.InitialBudget02, cv.BudgetAdjusted03 = cv.InitialBudget03, cv.BudgetAdjusted04 = cv.InitialBudget04, cv.BudgetAdjusted05 = cv.InitialBudget05, cv.BudgetAdjusted06 = cv.InitialBudget06, cv.BudgetAdjusted07 = cv.InitialBudget07, cv.BudgetAdjusted08 = cv.InitialBudget08, cv.BudgetAdjusted09 = cv.InitialBudget09, cv.BudgetAdjusted10 = cv.InitialBudget10, cv.BudgetAdjusted11 = cv.InitialBudget11, cv.BudgetAdjusted12 = cv.InitialBudget12,
        cv.ProjectionAdjusted01 = cv.InitialProjection01, cv.ProjectionAdjusted02 = cv.InitialProjection02, cv.ProjectionAdjusted03 = cv.InitialProjection03, cv.ProjectionAdjusted04 = cv.InitialProjection04, cv.ProjectionAdjusted05 = cv.InitialProjection05, cv.ProjectionAdjusted06 = cv.InitialProjection06, cv.ProjectionAdjusted07 = cv.InitialProjection07, cv.ProjectionAdjusted08 = cv.InitialProjection08, cv.ProjectionAdjusted09 = cv.InitialProjection09, cv.ProjectionAdjusted10 = cv.InitialProjection10, cv.ProjectionAdjusted11 = cv.InitialProjection11, cv.ProjectionAdjusted12 = cv.InitialProjection12,
        cv.TargetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.TargetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.TargetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.TargetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04,	cv.TargetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.TargetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.TargetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.TargetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08,	cv.TargetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.TargetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.TargetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.TargetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12,
        cv.BudgetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.BudgetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.BudgetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.BudgetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04,	cv.BudgetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.BudgetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.BudgetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.BudgetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08,	cv.BudgetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.BudgetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.BudgetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.BudgetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12,
        cv.ProjectionUnitsPerEncounterAdjusted01 = cv.InitialProjectionUnitsPerEncounter01, cv.ProjectionUnitsPerEncounterAdjusted02 = cv.InitialProjectionUnitsPerEncounter02, cv.ProjectionUnitsPerEncounterAdjusted03 = cv.InitialProjectionUnitsPerEncounter03, cv.ProjectionUnitsPerEncounterAdjusted04 = cv.InitialProjectionUnitsPerEncounter04,	cv.ProjectionUnitsPerEncounterAdjusted05 = cv.InitialProjectionUnitsPerEncounter05, cv.ProjectionUnitsPerEncounterAdjusted06 = cv.InitialProjectionUnitsPerEncounter06, cv.ProjectionUnitsPerEncounterAdjusted07 = cv.InitialProjectionUnitsPerEncounter07, cv.ProjectionUnitsPerEncounterAdjusted08 = cv.InitialProjectionUnitsPerEncounter08,	cv.ProjectionUnitsPerEncounterAdjusted09 = cv.InitialProjectionUnitsPerEncounter09, cv.ProjectionUnitsPerEncounterAdjusted10 = cv.InitialProjectionUnitsPerEncounter10, cv.ProjectionUnitsPerEncounterAdjusted11 = cv.InitialProjectionUnitsPerEncounter11, cv.ProjectionUnitsPerEncounterAdjusted12 = cv.InitialProjectionUnitsPerEncounter12,
        cv.TargetLockType = 0,
        cv.TargetLockFlag = 0,
        cv.BudgetLockType = 0,
        cv.BudgetLockFlag = 0,
		cv.ProjectionLockType = 0,
        cv.ProjectionLockFlag = 0
    FROM [fp].[ChargeVolume] cv
   INNER JOIN #FilterByDepartment f on f.DepartmentID = cv.DepartmentID 
    WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
 END 
    
 END
GO


---------------------------------------------

-- fp.procResetDriverAndDependentSection
/************************************************************** 
** Change History 
************************************************************** 
** CID  Date        Author  WI			    Description 
** 1 	12-14-2020  MY  	JAZZ-11324 		Initial 
** 2 	10-23-2023  MY  	JAZZ-62535 		SPIKE - Updating what data appears on the Stats pages 
*************************************************************/ 
CREATE   PROCEDURE [fp].[procResetDriverAndDependentSection] 
	@BudgetConfigID INT, 
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
 AS 
 BEGIN 
 
	DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'), 
		@Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent') 
 	 
	CREATE TABLE #FilterByDepartment (DepartmentID int) 
  	INSERT INTO #FilterByDepartment (DepartmentID) 
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) 
 
	CREATE TABLE #departments (DepartmentID INT); 
 
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) 
	BEGIN 
		INSERT INTO #departments(DepartmentID) 
		SELECT DISTINCT stat.DepartmentID 
		FROM fp.FactStatistics stat 
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = stat.DepartmentID 
		WHERE stat.BudgetConfigID = @BudgetConfigID 
	END ELSE BEGIN 
		INSERT INTO #departments(DepartmentID) 
		SELECT DISTINCT stat.DepartmentID 
		FROM fp.FactStatistics stat 
		WHERE stat.BudgetConfigID = @BudgetConfigID 
	END 
 
	-- We need to reset the sub section for a given record so it not only shows in the correct screen 
	-- but also works with flexing and other areas. This will update the fp.FactStatistics record with the proper 
	-- subsection in case it were to change after sampling. 
	-- An account cannot be both a driver and dependent, so we don't have to worry about this case. 
 
	--------------------------------------------------------------------------------------------------------------------
	-- Dependent Statistic is flexed by a Driver Statistic, Source and Dependent Department Fields left blank
	--------------------------------------------------------------------------------------------------------------------

	-- Driver Statistic Account should appear on the Statistics page for all departments that have data for this statistic (Driver Stat can’t be a primary stat)
	UPDATE stat 
	SET stat.SubSectionID = @Driver 
	FROM fp.FactStatistics stat 
		INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID 
		LEFT JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID 
	WHERE stat.BudgetConfigID = @BudgetConfigID
		AND dsa.DependentAccountID IS NULL
		AND stat.SubSectionID != @Driver 

	-- Dependent Statistic Account should appear on the Dependent Statistics page for all departments that have data for this statistic
	UPDATE stat 
	SET stat.SubSectionID = @Dependent 
	FROM fp.FactStatistics stat 
		INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID 
		INNER JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID
		LEFT JOIN fp.DependentStatisticsAccountDepartment dsad ON dsa.DependentStatisticsAccountID = dsad.DependentStatisticsAccountID
	WHERE stat.BudgetConfigID = @BudgetConfigID 
		AND dsad.RowID IS NULL
		AND stat.SubSectionID != @Dependent 

	--------------------------------------------------------------------------------------------------------------------
	-- Dependent Statistic is flexed by a Driver Statistic, Source and Dependent Department Fields are both filled out 
	--------------------------------------------------------------------------------------------------------------------
	
	-- Driver Statistic Account should appear on the Statistics page for all departments that have data for this statistic (Driver Stat can’t be a primary stat)
	-- Check for department level dependent accounts. Accounts not in the table will be covered in the first check.
	UPDATE stat 
	SET stat.SubSectionID = @Driver 
	FROM fp.FactStatistics stat 
		INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID 
		INNER JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID
		LEFT JOIN fp.DependentStatisticsAccountDepartment dsad ON dsa.DependentStatisticsAccountID = dsad.DependentStatisticsAccountID AND stat.DepartmentID = dsad.DepartmentID
	WHERE stat.BudgetConfigID = @BudgetConfigID
		AND dsa.SourceDepartmentID != -1 -- -1 Means this isn't using Cross Department Flexing
		AND dsad.RowID IS NULL
		AND stat.SubSectionID != @Driver 

	-- Dependent Statistic Account should appear on the Dependent Statistics page only if departments were configured and selected on the Statistics Account mapping.  
	-- If the dependent statistics account has departments that weren’t configured as dependent departments, then these department/account combinations should appear on the Statistics page 
	UPDATE stat 
	SET stat.SubSectionID = @Dependent 
	FROM fp.FactStatistics stat 
		INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID 
		INNER JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID
		INNER JOIN fp.DependentStatisticsAccountDepartment dsad ON dsa.DependentStatisticsAccountID = dsad.DependentStatisticsAccountID AND stat.DepartmentID = dsad.DepartmentID
	WHERE stat.BudgetConfigID = @BudgetConfigID 
		AND stat.SubSectionID != @Dependent 
	
	-- Find anything that doesn't have a sub-section for some reason and assign it to driver. 
	UPDATE stat 
	SET stat.SubSectionID = @Driver 
	FROM fp.FactStatistics stat 
		INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID 
	WHERE stat.BudgetConfigID = @BudgetConfigID 
		AND stat.SubSectionID = 0 
 END
GO


---------------------------------------------

-- fp.procResetFactBenefitsTables
CREATE PROCEDURE [fp].[procResetFactBenefitsTables]
	@EntityGroupConfigID INT,
	@UnitTypeIds dbo.SqlInt32ListTableType READONLY,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 *************************************************************/ 	 
	
	CREATE TABLE #UnitTypeIds (Value int)
	INSERT INTO #UnitTypeIds (VALUE)
	SELECT Value from @UnitTypeIds
	
	
	CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int)
	INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID)
	SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	-- reset the data in the budget table
	UPDATE tbl
    SET
        tbl.AdjustedValue01 = fgl.InitialBudget01, tbl.AdjustedValue02 = fgl.InitialBudget02, tbl.AdjustedValue03 = fgl.InitialBudget03, tbl.AdjustedValue04 = fgl.InitialBudget04,	tbl.AdjustedValue05 = fgl.InitialBudget05, tbl.AdjustedValue06 = fgl.InitialBudget06, tbl.AdjustedValue07 = fgl.InitialBudget07, tbl.AdjustedValue08 = fgl.InitialBudget08,	tbl.AdjustedValue09 = fgl.InitialBudget09, tbl.AdjustedValue10 = fgl.InitialBudget10, tbl.AdjustedValue11 = fgl.InitialBudget11, tbl.AdjustedValue12 = fgl.InitialBudget12,
        tbl.FlexedValue01 = fgl.InitialBudget01, tbl.FlexedValue02 = fgl.InitialBudget02, tbl.FlexedValue03 = fgl.InitialBudget03, tbl.FlexedValue04 = fgl.InitialBudget04, tbl.FlexedValue05 = fgl.InitialBudget05, tbl.FlexedValue06 = fgl.InitialBudget06, tbl.FlexedValue07 = fgl.InitialBudget07, tbl.FlexedValue08 = fgl.InitialBudget08, tbl.FlexedValue09 = fgl.InitialBudget09, tbl.FlexedValue10 = fgl.InitialBudget10, tbl.FlexedValue11 = fgl.InitialBudget11, tbl.FlexedValue12 = fgl.InitialBudget12,
        tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactBenefitsBudget] tbl
        INNER JOIN [fp].[FactBenefits] fgl ON tbl.BenefitsID = fgl.BenefitsID
        INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fgl.DepartmentID or ft.DepartmentID is null) 
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
		AND fgl.UnitTypeID IN (SELECT value FROM #UnitTypeIds)
		AND (tbl.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
        		
	-- reset the data in the projection table
 	UPDATE tbl
    SET
        tbl.AdjustedValue01 = fgl.InitialProjection01, tbl.AdjustedValue02 = fgl.InitialProjection02, tbl.AdjustedValue03 = fgl.InitialProjection03, tbl.AdjustedValue04 = fgl.InitialProjection04,	tbl.AdjustedValue05 = fgl.InitialProjection05, tbl.AdjustedValue06 = fgl.InitialProjection06, tbl.AdjustedValue07 = fgl.InitialProjection07, tbl.AdjustedValue08 = fgl.InitialProjection08,	tbl.AdjustedValue09 = fgl.InitialProjection09, tbl.AdjustedValue10 = fgl.InitialProjection10, tbl.AdjustedValue11 = fgl.InitialProjection11, tbl.AdjustedValue12 = fgl.InitialProjection12,
        tbl.FlexedValue01 = fgl.InitialProjection01, tbl.FlexedValue02 = fgl.InitialProjection02, tbl.FlexedValue03 = fgl.InitialProjection03, tbl.FlexedValue04 = fgl.InitialProjection04, tbl.FlexedValue05 = fgl.InitialProjection05, tbl.FlexedValue06 = fgl.InitialProjection06, tbl.FlexedValue07 = fgl.InitialProjection07, tbl.FlexedValue08 = fgl.InitialProjection08, tbl.FlexedValue09 = fgl.InitialProjection09, tbl.FlexedValue10 = fgl.InitialProjection10, tbl.FlexedValue11 = fgl.InitialProjection11, tbl.FlexedValue12 = fgl.InitialProjection12,
        tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactBenefitsProjection] tbl
        INNER JOIN [fp].[FactBenefits] fgl ON tbl.BenefitsID = fgl.BenefitsID
        INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fgl.DepartmentID or ft.DepartmentID is null) 
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
		AND fgl.UnitTypeID IN (SELECT value FROM #UnitTypeIds)
		AND (tbl.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
 
END
GO


---------------------------------------------

-- fp.procResetFactReimbursementChargesTables
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-16-05  MY      JAZZ-32944		Initial
*************************************************************/
CREATE   PROCEDURE [fp].[procResetFactReimbursementChargesTables]
	 @EntityGroupConfigID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
 AS
 BEGIN
 	
	CREATE TABLE #FilteringTable (
		EntityID INT,
		INDEX ix_1 NONCLUSTERED (EntityID)
	)

	INSERT INTO #FilteringTable (EntityID)
	SELECT src.EntityID
	FROM @SourceDimensionality src
		INNER JOIN fw.DimDepartment dept ON src.DepartmentID = dept.DepartmentID
	UNION
	SELECT d.EntityID
	FROM fw.DimDepartment d
	INNER JOIN @SourceDimensionality sd 
		ON sd.EntityID = d.EntityID
	WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID 
 	
	DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable)

	IF (@isFilterPresent = 0) 
		INSERT INTO #FilteringTable (EntityID) VALUES (NULL)

	UPDATE tbl
    SET
        tbl.AdjustedNetAsPercentOfCharge01 = fgl.InitialBudgetNetAsPercentOfCharge01, tbl.AdjustedNetAsPercentOfCharge02 = fgl.InitialBudgetNetAsPercentOfCharge02, tbl.AdjustedNetAsPercentOfCharge03 = fgl.InitialBudgetNetAsPercentOfCharge03,
        tbl.AdjustedNetAsPercentOfCharge04 = fgl.InitialBudgetNetAsPercentOfCharge04, tbl.AdjustedNetAsPercentOfCharge05 = fgl.InitialBudgetNetAsPercentOfCharge05, tbl.AdjustedNetAsPercentOfCharge06 = fgl.InitialBudgetNetAsPercentOfCharge06,
        tbl.AdjustedNetAsPercentOfCharge07 = fgl.InitialBudgetNetAsPercentOfCharge07, tbl.AdjustedNetAsPercentOfCharge08 = fgl.InitialBudgetNetAsPercentOfCharge08, tbl.AdjustedNetAsPercentOfCharge09 = fgl.InitialBudgetNetAsPercentOfCharge09,
        tbl.AdjustedNetAsPercentOfCharge10 = fgl.InitialBudgetNetAsPercentOfCharge10, tbl.AdjustedNetAsPercentOfCharge11 = fgl.InitialBudgetNetAsPercentOfCharge11, tbl.AdjustedNetAsPercentOfCharge12 = fgl.InitialBudgetNetAsPercentOfCharge12,

        tbl.AdjustedNetPerDiem01 = fgl.InitialBudgetNetPerDiem01, tbl.AdjustedNetPerDiem02 = fgl.InitialBudgetNetPerDiem02, tbl.AdjustedNetPerDiem03 = fgl.InitialBudgetNetPerDiem03,
        tbl.AdjustedNetPerDiem04 = fgl.InitialBudgetNetPerDiem04, tbl.AdjustedNetPerDiem05 = fgl.InitialBudgetNetPerDiem05, tbl.AdjustedNetPerDiem06 = fgl.InitialBudgetNetPerDiem06,
        tbl.AdjustedNetPerDiem07 = fgl.InitialBudgetNetPerDiem07, tbl.AdjustedNetPerDiem08 = fgl.InitialBudgetNetPerDiem08, tbl.AdjustedNetPerDiem09 = fgl.InitialBudgetNetPerDiem09,
        tbl.AdjustedNetPerDiem10 = fgl.InitialBudgetNetPerDiem10, tbl.AdjustedNetPerDiem11 = fgl.InitialBudgetNetPerDiem11, tbl.AdjustedNetPerDiem12 = fgl.InitialBudgetNetPerDiem12,

		tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactReimbursementChargesBudget] tbl
		INNER JOIN [fp].[FactReimbursementCharges] fgl ON tbl.ReimbursementChargesID = fgl.ReimbursementChargesID
		INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID)
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID

	UPDATE tbl
    SET
        tbl.AdjustedNetAsPercentOfCharge01 = fgl.InitialProjectionNetAsPercentOfCharge01, tbl.AdjustedNetAsPercentOfCharge02 = fgl.InitialProjectionNetAsPercentOfCharge02, tbl.AdjustedNetAsPercentOfCharge03 = fgl.InitialProjectionNetAsPercentOfCharge03,
        tbl.AdjustedNetAsPercentOfCharge04 = fgl.InitialProjectionNetAsPercentOfCharge04, tbl.AdjustedNetAsPercentOfCharge05 = fgl.InitialProjectionNetAsPercentOfCharge05, tbl.AdjustedNetAsPercentOfCharge06 = fgl.InitialProjectionNetAsPercentOfCharge06,
        tbl.AdjustedNetAsPercentOfCharge07 = fgl.InitialProjectionNetAsPercentOfCharge07, tbl.AdjustedNetAsPercentOfCharge08 = fgl.InitialProjectionNetAsPercentOfCharge08, tbl.AdjustedNetAsPercentOfCharge09 = fgl.InitialProjectionNetAsPercentOfCharge09,
        tbl.AdjustedNetAsPercentOfCharge10 = fgl.InitialProjectionNetAsPercentOfCharge10, tbl.AdjustedNetAsPercentOfCharge11 = fgl.InitialProjectionNetAsPercentOfCharge11, tbl.AdjustedNetAsPercentOfCharge12 = fgl.InitialProjectionNetAsPercentOfCharge12,

        tbl.AdjustedNetPerDiem01 = fgl.InitialProjectionNetPerDiem01, tbl.AdjustedNetPerDiem02 = fgl.InitialProjectionNetPerDiem02, tbl.AdjustedNetPerDiem03 = fgl.InitialProjectionNetPerDiem03,
        tbl.AdjustedNetPerDiem04 = fgl.InitialProjectionNetPerDiem04, tbl.AdjustedNetPerDiem05 = fgl.InitialProjectionNetPerDiem05, tbl.AdjustedNetPerDiem06 = fgl.InitialProjectionNetPerDiem06,
        tbl.AdjustedNetPerDiem07 = fgl.InitialProjectionNetPerDiem07, tbl.AdjustedNetPerDiem08 = fgl.InitialProjectionNetPerDiem08, tbl.AdjustedNetPerDiem09 = fgl.InitialProjectionNetPerDiem09,
        tbl.AdjustedNetPerDiem10 = fgl.InitialProjectionNetPerDiem10, tbl.AdjustedNetPerDiem11 = fgl.InitialProjectionNetPerDiem11, tbl.AdjustedNetPerDiem12 = fgl.InitialProjectionNetPerDiem12,

		tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactReimbursementChargesProjection] tbl
		INNER JOIN [fp].[FactReimbursementCharges] fgl ON tbl.ReimbursementChargesID = fgl.ReimbursementChargesID
		INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID)
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID

 END
GO


---------------------------------------------

-- fp.procResetFactReimbursementEncounterTables
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-16-05  MY      JAZZ-32944		Initial
*************************************************************/
CREATE   PROCEDURE [fp].[procResetFactReimbursementEncounterTables]
	 @EntityGroupConfigID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
 AS
 BEGIN
 	
	CREATE TABLE #FilteringTable (
		EntityID INT,
		INDEX ix_1 NONCLUSTERED (EntityID)
	)

	INSERT INTO #FilteringTable (EntityID)
	SELECT src.EntityID
	FROM @SourceDimensionality src
		INNER JOIN fw.DimDepartment dept ON src.DepartmentID = dept.DepartmentID
	UNION
	SELECT d.EntityID
	FROM fw.DimDepartment d
	INNER JOIN @SourceDimensionality sd 
		ON sd.EntityID = d.EntityID
	WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID 
 	
	DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable)

	IF (@isFilterPresent = 0) 
		INSERT INTO #FilteringTable (EntityID) VALUES (NULL)

	UPDATE tbl
    SET
        tbl.AdjustedNetPerEncounterValue01 = fgl.InitialBudgetNetPerEncounter01, tbl.AdjustedNetPerEncounterValue02 = fgl.InitialBudgetNetPerEncounter02, tbl.AdjustedNetPerEncounterValue03 = fgl.InitialBudgetNetPerEncounter03,
        tbl.AdjustedNetPerEncounterValue04 = fgl.InitialBudgetNetPerEncounter04, tbl.AdjustedNetPerEncounterValue05 = fgl.InitialBudgetNetPerEncounter05, tbl.AdjustedNetPerEncounterValue06 = fgl.InitialBudgetNetPerEncounter06,
        tbl.AdjustedNetPerEncounterValue07 = fgl.InitialBudgetNetPerEncounter07, tbl.AdjustedNetPerEncounterValue08 = fgl.InitialBudgetNetPerEncounter08, tbl.AdjustedNetPerEncounterValue09 = fgl.InitialBudgetNetPerEncounter09,
        tbl.AdjustedNetPerEncounterValue10 = fgl.InitialBudgetNetPerEncounter10, tbl.AdjustedNetPerEncounterValue11 = fgl.InitialBudgetNetPerEncounter11, tbl.AdjustedNetPerEncounterValue12 = fgl.InitialBudgetNetPerEncounter12,

		tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactReimbursementEncounterBudget] tbl
		INNER JOIN [fp].[FactReimbursementEncounter] fgl ON tbl.ReimbursementEncounterID = fgl.ReimbursementEncounterID
		INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID)
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
		
	UPDATE tbl
    SET
        tbl.AdjustedNetPerEncounterValue01 = fgl.InitialProjectionNetPerEncounter01, tbl.AdjustedNetPerEncounterValue02 = fgl.InitialProjectionNetPerEncounter02, tbl.AdjustedNetPerEncounterValue03 = fgl.InitialProjectionNetPerEncounter03,
        tbl.AdjustedNetPerEncounterValue04 = fgl.InitialProjectionNetPerEncounter04, tbl.AdjustedNetPerEncounterValue05 = fgl.InitialProjectionNetPerEncounter05, tbl.AdjustedNetPerEncounterValue06 = fgl.InitialProjectionNetPerEncounter06,
        tbl.AdjustedNetPerEncounterValue07 = fgl.InitialProjectionNetPerEncounter07, tbl.AdjustedNetPerEncounterValue08 = fgl.InitialProjectionNetPerEncounter08, tbl.AdjustedNetPerEncounterValue09 = fgl.InitialProjectionNetPerEncounter09,
        tbl.AdjustedNetPerEncounterValue10 = fgl.InitialProjectionNetPerEncounter10, tbl.AdjustedNetPerEncounterValue11 = fgl.InitialProjectionNetPerEncounter11, tbl.AdjustedNetPerEncounterValue12 = fgl.InitialProjectionNetPerEncounter12,

		tbl.LockType = 0,
        tbl.LockFlag = 0
    FROM [fp].[FactReimbursementEncounterProjection] tbl
		INNER JOIN [fp].[FactReimbursementEncounter] fgl ON tbl.ReimbursementEncounterID = fgl.ReimbursementEncounterID
		INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID)
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
 END
GO


---------------------------------------------

-- fp.procResetGeneralLedgerFromSnapshot
CREATE   PROCEDURE [fp].[procResetGeneralLedgerFromSnapshot] 
	@EntityGroupConfigID INT,
	@SnapshotID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    07-18-2024   MY        JAZZ-77735  Initial Creation
	*************************************************************/
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED)
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm on egcm.EntityID = d.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc ON  egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
		WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
	END

	UPDATE  gl
	SET
		gl.TargetAdjusted01 = ISNULL(gls.TargetAdjusted01, 0),
		gl.TargetAdjusted02 = ISNULL(gls.TargetAdjusted02, 0),
		gl.TargetAdjusted03 = ISNULL(gls.TargetAdjusted03, 0),
		gl.TargetAdjusted04 = ISNULL(gls.TargetAdjusted04, 0),
		gl.TargetAdjusted05 = ISNULL(gls.TargetAdjusted05, 0),
		gl.TargetAdjusted06 = ISNULL(gls.TargetAdjusted06, 0),
		gl.TargetAdjusted07 = ISNULL(gls.TargetAdjusted07, 0),
		gl.TargetAdjusted08 = ISNULL(gls.TargetAdjusted08, 0),
		gl.TargetAdjusted09 = ISNULL(gls.TargetAdjusted09, 0),
		gl.TargetAdjusted10 = ISNULL(gls.TargetAdjusted10, 0),
		gl.TargetAdjusted11 = ISNULL(gls.TargetAdjusted11, 0),
		gl.TargetAdjusted12 = ISNULL(gls.TargetAdjusted12, 0),

		gl.BudgetAdjusted01 = ISNULL(gls.BudgetAdjusted01, 0),
		gl.BudgetAdjusted02 = ISNULL(gls.BudgetAdjusted02, 0),
		gl.BudgetAdjusted03 = ISNULL(gls.BudgetAdjusted03, 0),
		gl.BudgetAdjusted04 = ISNULL(gls.BudgetAdjusted04, 0),
		gl.BudgetAdjusted05 = ISNULL(gls.BudgetAdjusted05, 0),
		gl.BudgetAdjusted06 = ISNULL(gls.BudgetAdjusted06, 0),
		gl.BudgetAdjusted07 = ISNULL(gls.BudgetAdjusted07, 0),
		gl.BudgetAdjusted08 = ISNULL(gls.BudgetAdjusted08, 0),
		gl.BudgetAdjusted09 = ISNULL(gls.BudgetAdjusted09, 0),
		gl.BudgetAdjusted10 = ISNULL(gls.BudgetAdjusted10, 0),
		gl.BudgetAdjusted11 = ISNULL(gls.BudgetAdjusted11, 0),
		gl.BudgetAdjusted12 = ISNULL(gls.BudgetAdjusted12, 0),

		gl.ProjectionAdjusted01 = ISNULL(gls.ProjectionAdjusted01, 0),
		gl.ProjectionAdjusted02 = ISNULL(gls.ProjectionAdjusted02, 0),
		gl.ProjectionAdjusted03 = ISNULL(gls.ProjectionAdjusted03, 0),
		gl.ProjectionAdjusted04 = ISNULL(gls.ProjectionAdjusted04, 0),
		gl.ProjectionAdjusted05 = ISNULL(gls.ProjectionAdjusted05, 0),
		gl.ProjectionAdjusted06 = ISNULL(gls.ProjectionAdjusted06, 0),
		gl.ProjectionAdjusted07 = ISNULL(gls.ProjectionAdjusted07, 0),
		gl.ProjectionAdjusted08 = ISNULL(gls.ProjectionAdjusted08, 0),
		gl.ProjectionAdjusted09 = ISNULL(gls.ProjectionAdjusted09, 0),
		gl.ProjectionAdjusted10 = ISNULL(gls.ProjectionAdjusted10, 0),
		gl.ProjectionAdjusted11 = ISNULL(gls.ProjectionAdjusted11, 0),
		gl.ProjectionAdjusted12 = ISNULL(gls.ProjectionAdjusted12, 0),

		gl.TargetPercentAdjustmentFactor01 = ISNULL(gls.TargetPercentAdjustmentFactor01, 1),
		gl.TargetPercentAdjustmentFactor02 = ISNULL(gls.TargetPercentAdjustmentFactor02, 1),
		gl.TargetPercentAdjustmentFactor03 = ISNULL(gls.TargetPercentAdjustmentFactor03, 1),
		gl.TargetPercentAdjustmentFactor04 = ISNULL(gls.TargetPercentAdjustmentFactor04, 1),
		gl.TargetPercentAdjustmentFactor05 = ISNULL(gls.TargetPercentAdjustmentFactor05, 1),
		gl.TargetPercentAdjustmentFactor06 = ISNULL(gls.TargetPercentAdjustmentFactor06, 1),
		gl.TargetPercentAdjustmentFactor07 = ISNULL(gls.TargetPercentAdjustmentFactor07, 1),
		gl.TargetPercentAdjustmentFactor08 = ISNULL(gls.TargetPercentAdjustmentFactor08, 1),
		gl.TargetPercentAdjustmentFactor09 = ISNULL(gls.TargetPercentAdjustmentFactor09, 1),
		gl.TargetPercentAdjustmentFactor10 = ISNULL(gls.TargetPercentAdjustmentFactor10, 1),
		gl.TargetPercentAdjustmentFactor11 = ISNULL(gls.TargetPercentAdjustmentFactor11, 1),
		gl.TargetPercentAdjustmentFactor12 = ISNULL(gls.TargetPercentAdjustmentFactor12, 1),

		gl.BudgetPercentAdjustmentFactor01 = ISNULL(gls.BudgetPercentAdjustmentFactor01, 1),
		gl.BudgetPercentAdjustmentFactor02 = ISNULL(gls.BudgetPercentAdjustmentFactor02, 1),
		gl.BudgetPercentAdjustmentFactor03 = ISNULL(gls.BudgetPercentAdjustmentFactor03, 1),
		gl.BudgetPercentAdjustmentFactor04 = ISNULL(gls.BudgetPercentAdjustmentFactor04, 1),
		gl.BudgetPercentAdjustmentFactor05 = ISNULL(gls.BudgetPercentAdjustmentFactor05, 1),
		gl.BudgetPercentAdjustmentFactor06 = ISNULL(gls.BudgetPercentAdjustmentFactor06, 1),
		gl.BudgetPercentAdjustmentFactor07 = ISNULL(gls.BudgetPercentAdjustmentFactor07, 1),
		gl.BudgetPercentAdjustmentFactor08 = ISNULL(gls.BudgetPercentAdjustmentFactor08, 1),
		gl.BudgetPercentAdjustmentFactor09 = ISNULL(gls.BudgetPercentAdjustmentFactor09, 1),
		gl.BudgetPercentAdjustmentFactor10 = ISNULL(gls.BudgetPercentAdjustmentFactor10, 1),
		gl.BudgetPercentAdjustmentFactor11 = ISNULL(gls.BudgetPercentAdjustmentFactor11, 1),
		gl.BudgetPercentAdjustmentFactor12 = ISNULL(gls.BudgetPercentAdjustmentFactor12, 1),

		gl.ProjectionPercentAdjustmentFactor01 = ISNULL(gls.ProjectionPercentAdjustmentFactor01, 1),
		gl.ProjectionPercentAdjustmentFactor02 = ISNULL(gls.ProjectionPercentAdjustmentFactor02, 1),
		gl.ProjectionPercentAdjustmentFactor03 = ISNULL(gls.ProjectionPercentAdjustmentFactor03, 1),
		gl.ProjectionPercentAdjustmentFactor04 = ISNULL(gls.ProjectionPercentAdjustmentFactor04, 1),
		gl.ProjectionPercentAdjustmentFactor05 = ISNULL(gls.ProjectionPercentAdjustmentFactor05, 1),
		gl.ProjectionPercentAdjustmentFactor06 = ISNULL(gls.ProjectionPercentAdjustmentFactor06, 1),
		gl.ProjectionPercentAdjustmentFactor07 = ISNULL(gls.ProjectionPercentAdjustmentFactor07, 1),
		gl.ProjectionPercentAdjustmentFactor08 = ISNULL(gls.ProjectionPercentAdjustmentFactor08, 1),
		gl.ProjectionPercentAdjustmentFactor09 = ISNULL(gls.ProjectionPercentAdjustmentFactor09, 1),
		gl.ProjectionPercentAdjustmentFactor10 = ISNULL(gls.ProjectionPercentAdjustmentFactor10, 1),
		gl.ProjectionPercentAdjustmentFactor11 = ISNULL(gls.ProjectionPercentAdjustmentFactor11, 1),
		gl.ProjectionPercentAdjustmentFactor12 = ISNULL(gls.ProjectionPercentAdjustmentFactor12, 1),

		gl.TargetDollarsPerUOSAdjusted01 = ISNULL(gls.TargetDollarsPerUOSAdjusted01, 0),
		gl.TargetDollarsPerUOSAdjusted02 = ISNULL(gls.TargetDollarsPerUOSAdjusted02, 0),
		gl.TargetDollarsPerUOSAdjusted03 = ISNULL(gls.TargetDollarsPerUOSAdjusted03, 0),
		gl.TargetDollarsPerUOSAdjusted04 = ISNULL(gls.TargetDollarsPerUOSAdjusted04, 0),
		gl.TargetDollarsPerUOSAdjusted05 = ISNULL(gls.TargetDollarsPerUOSAdjusted05, 0),
		gl.TargetDollarsPerUOSAdjusted06 = ISNULL(gls.TargetDollarsPerUOSAdjusted06, 0),
		gl.TargetDollarsPerUOSAdjusted07 = ISNULL(gls.TargetDollarsPerUOSAdjusted07, 0),
		gl.TargetDollarsPerUOSAdjusted08 = ISNULL(gls.TargetDollarsPerUOSAdjusted08, 0),
		gl.TargetDollarsPerUOSAdjusted09 = ISNULL(gls.TargetDollarsPerUOSAdjusted09, 0),
		gl.TargetDollarsPerUOSAdjusted10 = ISNULL(gls.TargetDollarsPerUOSAdjusted10, 0),
		gl.TargetDollarsPerUOSAdjusted11 = ISNULL(gls.TargetDollarsPerUOSAdjusted11, 0),
		gl.TargetDollarsPerUOSAdjusted12 = ISNULL(gls.TargetDollarsPerUOSAdjusted12, 0),

		gl.BudgetDollarsPerUOSAdjusted01 = ISNULL(gls.BudgetDollarsPerUOSAdjusted01, 0),
		gl.BudgetDollarsPerUOSAdjusted02 = ISNULL(gls.BudgetDollarsPerUOSAdjusted02, 0),
		gl.BudgetDollarsPerUOSAdjusted03 = ISNULL(gls.BudgetDollarsPerUOSAdjusted03, 0),
		gl.BudgetDollarsPerUOSAdjusted04 = ISNULL(gls.BudgetDollarsPerUOSAdjusted04, 0),
		gl.BudgetDollarsPerUOSAdjusted05 = ISNULL(gls.BudgetDollarsPerUOSAdjusted05, 0),
		gl.BudgetDollarsPerUOSAdjusted06 = ISNULL(gls.BudgetDollarsPerUOSAdjusted06, 0),
		gl.BudgetDollarsPerUOSAdjusted07 = ISNULL(gls.BudgetDollarsPerUOSAdjusted07, 0),
		gl.BudgetDollarsPerUOSAdjusted08 = ISNULL(gls.BudgetDollarsPerUOSAdjusted08, 0),
		gl.BudgetDollarsPerUOSAdjusted09 = ISNULL(gls.BudgetDollarsPerUOSAdjusted09, 0),
		gl.BudgetDollarsPerUOSAdjusted10 = ISNULL(gls.BudgetDollarsPerUOSAdjusted10, 0),
		gl.BudgetDollarsPerUOSAdjusted11 = ISNULL(gls.BudgetDollarsPerUOSAdjusted11, 0),
		gl.BudgetDollarsPerUOSAdjusted12 = ISNULL(gls.BudgetDollarsPerUOSAdjusted12, 0),

		gl.ProjectionDollarsPerUOSAdjusted01 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted01, 0),
		gl.ProjectionDollarsPerUOSAdjusted02 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted02, 0),
		gl.ProjectionDollarsPerUOSAdjusted03 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted03, 0),
		gl.ProjectionDollarsPerUOSAdjusted04 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted04, 0),
		gl.ProjectionDollarsPerUOSAdjusted05 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted05, 0),
		gl.ProjectionDollarsPerUOSAdjusted06 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted06, 0),
		gl.ProjectionDollarsPerUOSAdjusted07 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted07, 0),
		gl.ProjectionDollarsPerUOSAdjusted08 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted08, 0),
		gl.ProjectionDollarsPerUOSAdjusted09 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted09, 0),
		gl.ProjectionDollarsPerUOSAdjusted10 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted10, 0),
		gl.ProjectionDollarsPerUOSAdjusted11 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted11, 0),
		gl.ProjectionDollarsPerUOSAdjusted12 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted12, 0),
				
		gl.TargetPercentOfChargeAdjusted01 = ISNULL(gls.TargetPercentOfChargeAdjusted01, 0),
		gl.TargetPercentOfChargeAdjusted02 = ISNULL(gls.TargetPercentOfChargeAdjusted02, 0),
		gl.TargetPercentOfChargeAdjusted03 = ISNULL(gls.TargetPercentOfChargeAdjusted03, 0),
		gl.TargetPercentOfChargeAdjusted04 = ISNULL(gls.TargetPercentOfChargeAdjusted04, 0),
		gl.TargetPercentOfChargeAdjusted05 = ISNULL(gls.TargetPercentOfChargeAdjusted05, 0),
		gl.TargetPercentOfChargeAdjusted06 = ISNULL(gls.TargetPercentOfChargeAdjusted06, 0),
		gl.TargetPercentOfChargeAdjusted07 = ISNULL(gls.TargetPercentOfChargeAdjusted07, 0),
		gl.TargetPercentOfChargeAdjusted08 = ISNULL(gls.TargetPercentOfChargeAdjusted08, 0),
		gl.TargetPercentOfChargeAdjusted09 = ISNULL(gls.TargetPercentOfChargeAdjusted09, 0),
		gl.TargetPercentOfChargeAdjusted10 = ISNULL(gls.TargetPercentOfChargeAdjusted10, 0),
		gl.TargetPercentOfChargeAdjusted11 = ISNULL(gls.TargetPercentOfChargeAdjusted11, 0),
		gl.TargetPercentOfChargeAdjusted12 = ISNULL(gls.TargetPercentOfChargeAdjusted12, 0),

		gl.BudgetPercentOfChargeAdjusted01 = ISNULL(gls.BudgetPercentOfChargeAdjusted01, 0),
		gl.BudgetPercentOfChargeAdjusted02 = ISNULL(gls.BudgetPercentOfChargeAdjusted02, 0),
		gl.BudgetPercentOfChargeAdjusted03 = ISNULL(gls.BudgetPercentOfChargeAdjusted03, 0),
		gl.BudgetPercentOfChargeAdjusted04 = ISNULL(gls.BudgetPercentOfChargeAdjusted04, 0),
		gl.BudgetPercentOfChargeAdjusted05 = ISNULL(gls.BudgetPercentOfChargeAdjusted05, 0),
		gl.BudgetPercentOfChargeAdjusted06 = ISNULL(gls.BudgetPercentOfChargeAdjusted06, 0),
		gl.BudgetPercentOfChargeAdjusted07 = ISNULL(gls.BudgetPercentOfChargeAdjusted07, 0),
		gl.BudgetPercentOfChargeAdjusted08 = ISNULL(gls.BudgetPercentOfChargeAdjusted08, 0),
		gl.BudgetPercentOfChargeAdjusted09 = ISNULL(gls.BudgetPercentOfChargeAdjusted09, 0),
		gl.BudgetPercentOfChargeAdjusted10 = ISNULL(gls.BudgetPercentOfChargeAdjusted10, 0),
		gl.BudgetPercentOfChargeAdjusted11 = ISNULL(gls.BudgetPercentOfChargeAdjusted11, 0),
		gl.BudgetPercentOfChargeAdjusted12 = ISNULL(gls.BudgetPercentOfChargeAdjusted12, 0),

		gl.ProjectionPercentOfChargeAdjusted01 = ISNULL(gls.ProjectionPercentOfChargeAdjusted01, 0),
		gl.ProjectionPercentOfChargeAdjusted02 = ISNULL(gls.ProjectionPercentOfChargeAdjusted02, 0),
		gl.ProjectionPercentOfChargeAdjusted03 = ISNULL(gls.ProjectionPercentOfChargeAdjusted03, 0),
		gl.ProjectionPercentOfChargeAdjusted04 = ISNULL(gls.ProjectionPercentOfChargeAdjusted04, 0),
		gl.ProjectionPercentOfChargeAdjusted05 = ISNULL(gls.ProjectionPercentOfChargeAdjusted05, 0),
		gl.ProjectionPercentOfChargeAdjusted06 = ISNULL(gls.ProjectionPercentOfChargeAdjusted06, 0),
		gl.ProjectionPercentOfChargeAdjusted07 = ISNULL(gls.ProjectionPercentOfChargeAdjusted07, 0),
		gl.ProjectionPercentOfChargeAdjusted08 = ISNULL(gls.ProjectionPercentOfChargeAdjusted08, 0),
		gl.ProjectionPercentOfChargeAdjusted09 = ISNULL(gls.ProjectionPercentOfChargeAdjusted09, 0),
		gl.ProjectionPercentOfChargeAdjusted10 = ISNULL(gls.ProjectionPercentOfChargeAdjusted10, 0),
		gl.ProjectionPercentOfChargeAdjusted11 = ISNULL(gls.ProjectionPercentOfChargeAdjusted11, 0),
		gl.ProjectionPercentOfChargeAdjusted12 = ISNULL(gls.ProjectionPercentOfChargeAdjusted12, 0),

		gl.TargetLockType = ISNULL(gls.TargetLockType, 0),
		gl.TargetLockFlag = ISNULL(gls.TargetLockFlag, 0),
		gl.BudgetLockType = ISNULL(gls.BudgetLockType, 0),
		gl.BudgetLockFlag = ISNULL(gls.BudgetLockFlag, 0),
		gl.ProjectionLockType = ISNULL(gls.ProjectionLockType, 0),
		gl.ProjectionLockFlag = ISNULL(gls.ProjectionLockFlag, 0)
	FROM
		[fp].[GeneralLedger] gl
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID
			-- Need to be a LEFT JOIN to handle cases where there was something new added. In this case, it's new
			-- and would be 0, until adjusted later in the process.
			LEFT JOIN [fp].[GeneralLedgerSnapshot] gls ON gl.GeneralLedgerID = gls.GeneralLedgerID 
	WHERE gl.EntityGroupConfigID = @EntityGroupConfigID
		AND gls.SnapshotID = @SnapshotID
END
GO


---------------------------------------------

-- fp.procResetInitialBenefitsFromSampled
/**************************************************************
** Change History
**************************************************************
** 1	2019-03-08	IP		B-22295		Removed using table variables, small optimizations
** 2 	 2019-03-26  IP  	 B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 3	2019-06-03	PA		D-08525		Updates to ensure query optimizer doesn't timeout
*************************************************************/
CREATE PROCEDURE [fp].[procResetInitialBenefitsFromSampled]
 @EntityGroupConfigID INT,
 @MonthsLoaded INT,
 @UnitTypeIds dbo.SqlInt32ListTableType READONLY,
 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE
AS
BEGIN
	DECLARE @BudgetConfigID INT = (
		SELECT TOP 1 BudgetConfigID 
		FROM fp.BudgetConfig 
		WHERE BudgetConfigGUID = (
			SELECT BudgetConfigGUID
			FROM fp.EntityGroupConfig
			WHERE EntityGroupConfigID = @EntityGroupConfigID))

	CREATE TABLE #UnitTypeIds (Value INT PRIMARY KEY CLUSTERED)
	INSERT INTO #UnitTypeIds (VALUE)
	SELECT Value from @UnitTypeIds

	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
 
;WITH spreadBudget AS (
	SELECT
		BenefitsID,
		SampledBudgetTotal / 12 AS InitialBudget01,
		SampledBudgetTotal / 12 AS InitialBudget02,
		SampledBudgetTotal / 12 AS InitialBudget03,
		SampledBudgetTotal / 12 AS InitialBudget04,
		SampledBudgetTotal / 12 AS InitialBudget05,
		SampledBudgetTotal / 12 AS InitialBudget06,
		SampledBudgetTotal / 12 AS InitialBudget07,
		SampledBudgetTotal / 12 AS InitialBudget08,
		SampledBudgetTotal / 12 AS InitialBudget09,
		SampledBudgetTotal / 12 AS InitialBudget10,
		SampledBudgetTotal / 12 AS InitialBudget11,
		SampledBudgetTotal - (SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + 
		    SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12) AS InitialBudget12
	FROM [fp].[FactBenefits] tbl
	INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = tbl.DepartmentID or ft.DepartmentID is null) 
	WHERE 
		BudgetConfigID = @BudgetConfigID
		AND EntityGroupConfigID = @EntityGroupConfigID
		AND UnitTypeID IN (SELECT value FROM #UnitTypeIds)
   
 ),Totals as (
    SELECT *, NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded) FROM (
	SELECT BenefitsID, 
	   CASE WHEN @MonthsLoaded = 11 THEN ben.SampledProjection12  
			 WHEN @MonthsLoaded = 10 THEN ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 9 THEN ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 8 THEN ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 7 THEN ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 6 THEN ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 5 THEN ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 4 THEN ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 3 THEN ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10  + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 2 THEN ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
			 WHEN @MonthsLoaded = 1 THEN ben.SampledProjection02 + ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12  
		 	 ELSE 0
		END as SampledProjectionTotal
      FROM [fp].[FactBenefits] ben
    WHERE 
    	ben.BudgetConfigID = @BudgetConfigID
		AND ben.EntityGroupConfigID = @EntityGroupConfigID 
		AND ben.UnitTypeID = 34
	)x )     
   
		UPDATE
			ben
		SET
			InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN ben.SampledProjection01 ELSE t.NewValue END,
			InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN ben.SampledProjection02 ELSE t.NewValue END,
			InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN ben.SampledProjection03 ELSE t.NewValue END,
			InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN ben.SampledProjection04 ELSE t.NewValue END,
			InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN ben.SampledProjection05 ELSE t.NewValue END,
			InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN ben.SampledProjection06 ELSE t.NewValue END,
			InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN ben.SampledProjection07 ELSE t.NewValue END,
			InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN ben.SampledProjection08 ELSE t.NewValue END,
			InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN ben.SampledProjection09 ELSE t.NewValue END,
			InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN ben.SampledProjection10 ELSE t.NewValue END,
			InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN ben.SampledProjection11 ELSE t.NewValue END,
			InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN ben.SampledProjection12 ELSE t.NewValue END,
			InitialBudget01 = bdgt.InitialBudget01, 
			InitialBudget02 = bdgt.InitialBudget02, 
			InitialBudget03 = bdgt.InitialBudget03,
			InitialBudget04 = bdgt.InitialBudget04, 
			InitialBudget05 = bdgt.InitialBudget05, 
			InitialBudget06 = bdgt.InitialBudget06, 
			InitialBudget07 = bdgt.InitialBudget07, 
			InitialBudget08 = bdgt.InitialBudget08, 
			InitialBudget09 = bdgt.InitialBudget09, 
			InitialBudget10 = bdgt.InitialBudget10, 
			InitialBudget11 = bdgt.InitialBudget11, 
			InitialBudget12 = bdgt.InitialBudget12
		FROM [fp].[FactBenefits] ben 
		INNER JOIN Totals t on ben.BenefitsID = t.BenefitsID
		INNER JOIN spreadBudget bdgt ON ben.BenefitsID = bdgt.BenefitsID
		WHERE 
			ben.BudgetConfigID = @BudgetConfigID
			AND ben.EntityGroupConfigID  = @EntityGroupConfigID  
END
GO


---------------------------------------------

-- fp.procResetProjectionValuesForRoster
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	03-27-2023	MY			JAZZ-51328	Initial
** 2	01-03-2023  MY			JAZZ-63564	Final Pass Of Fact References (SQL)
*************************************************************/
CREATE   PROC [fp].[procResetProjectionValuesForRoster]
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN

	DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID)
	DECLARE @IsFTEHidden BIT = (SELECT IsFTEHidden FROM [fp].[BudgetConfig] WHERE BudgetConfigGUID = @BudgetConfigGUID)

	EXEC dbo.procSysDropTempTable '#Filter'
	EXEC dbo.procSysDropTempTable '#entityFilter'
	EXEC dbo.procSysDropTempTable '#rosterDimensionality'
	EXEC dbo.procSysDropTempTable '#factStaffingRolledUp'
	
	-- Load up the entities for the selected entity group so we only process what is needed
	SELECT EntityID
	INTO #entityFilter
	FROM fp.EntityGroupConfigMapping egcm
		INNER JOIN fp.EntityGroupConfig egc ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID

	-- Pull the departments from the targeting filter, but then only load up the entities for the given EGC. 
	-- This is unique because we don't have EGC or that concept in roster so rather than passing in 2 different filters.
	SELECT DISTINCT tgt.DepartmentID 
	INTO #Filter 
	FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) tgt
		INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON tgt.DepartmentID = dept.DepartmentID
		INNER JOIN #entityFilter ent ON dept.EntityID = ent.EntityID
 
	IF NOT EXISTS(SELECT 1 FROM #Filter WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #Filter (DepartmentID) 
		SELECT DISTINCT rbbr.DepartmentID 
		FROM [fp].[RosterBudgetBasisResult] rbbr
			INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rbbr.DepartmentID = dept.DepartmentID
			INNER JOIN #entityFilter ent ON dept.EntityID = ent.EntityID
		WHERE BudgetConfigGUID = @BudgetConfigGUID
	END

	-- Note: When transfering roster to Staffing, we don't include EmployeeID
	SELECT DISTINCT
		dept.EntityID,
		rb.DepartmentID,
		rb.JobCodeID,
		rb.PayCodeGroupID
	INTO #rosterDimensionality
	FROM [fp].[RosterBudgetBasisResult] rb
		INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON bc.BudgetConfigGUID = rb.BudgetConfigGUID
		INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rb.DepartmentID = dept.DepartmentID
		INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID
	WHERE 1=1
		AND rb.BudgetConfigGUID = @BudgetConfigGUID

	-- Pull out the staffing data for sampled projection data above variability, we'll put anything coming from roster as 100% fixed.
	SELECT 
		fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID,
		SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01,
		SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02,
		SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03,
		SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04,
		SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05,
		SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06,
		SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07,
		SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08,
		SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09,
		SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10,
		SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11,
		SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12,
		SUM(fs.SampledProjectionHours01) AS SampledProjectionHours01,
		SUM(fs.SampledProjectionHours02) AS SampledProjectionHours02,
		SUM(fs.SampledProjectionHours03) AS SampledProjectionHours03,
		SUM(fs.SampledProjectionHours04) AS SampledProjectionHours04,
		SUM(fs.SampledProjectionHours05) AS SampledProjectionHours05,
		SUM(fs.SampledProjectionHours06) AS SampledProjectionHours06,
		SUM(fs.SampledProjectionHours07) AS SampledProjectionHours07,
		SUM(fs.SampledProjectionHours08) AS SampledProjectionHours08,
		SUM(fs.SampledProjectionHours09) AS SampledProjectionHours09,
		SUM(fs.SampledProjectionHours10) AS SampledProjectionHours10,
		SUM(fs.SampledProjectionHours11) AS SampledProjectionHours11,
		SUM(fs.SampledProjectionHours12) AS SampledProjectionHours12,
		SUM(fs.SampledProjectionFTEs01) AS SampledProjectionFTEs01,
		SUM(fs.SampledProjectionFTEs02) AS SampledProjectionFTEs02,
		SUM(fs.SampledProjectionFTEs03) AS SampledProjectionFTEs03,
		SUM(fs.SampledProjectionFTEs04) AS SampledProjectionFTEs04,
		SUM(fs.SampledProjectionFTEs05) AS SampledProjectionFTEs05,
		SUM(fs.SampledProjectionFTEs06) AS SampledProjectionFTEs06,
		SUM(fs.SampledProjectionFTEs07) AS SampledProjectionFTEs07,
		SUM(fs.SampledProjectionFTEs08) AS SampledProjectionFTEs08,
		SUM(fs.SampledProjectionFTEs09) AS SampledProjectionFTEs09,
		SUM(fs.SampledProjectionFTEs10) AS SampledProjectionFTEs10,
		SUM(fs.SampledProjectionFTEs11) AS SampledProjectionFTEs11,
		SUM(fs.SampledProjectionFTEs12) AS SampledProjectionFTEs12
	INTO #factStaffingRolledUp
	FROM fp.Staffing fs
		INNER JOIN #rosterDimensionality roster ON roster.EntityID = fs.EntityID
			AND roster.DepartmentID = fs.DepartmentID
			AND roster.JobCodeID = fs.JobCodeID
			AND roster.PayCodeGroupID = fs.PayCodeGroupID
	WHERE EntityGroupConfigID = @EntityGroupConfigID
		AND fs.SubsectionID = 3 -- Staffing
	GROUP BY fs.EntityID,
		fs.DepartmentID,
		fs.JobCodeID,
		fs.PayCodeGroupID
	
	IF (@IsDebug = 1)
	BEGIN

		SELECT @BudgetConfigGUID AS '@BudgetConfigGUID', @IsFTEHidden AS '@IsFTEHidden'
		SELECT '#Filter' AS '#Filter', * FROM #Filter
		SELECT '#entityFilter' AS '#entityFilter', * FROM #entityFilter
		SELECT '#rosterDimensionality' AS '#rosterDimensionality', * FROM #rosterDimensionality
		SELECT '#factStaffingRolledUp' AS '#factStaffingRolledUp', * FROM #factStaffingRolledUp

	END ELSE 
	BEGIN

		-- Roster only gets loaded into Fixed so we need to 0 out all of Variable
		UPDATE fs
		SET
			fs.InitialProjectionDollars01 = 0,
			fs.InitialProjectionDollars02 = 0,
			fs.InitialProjectionDollars03 = 0,
			fs.InitialProjectionDollars04 = 0,
			fs.InitialProjectionDollars05 = 0,
			fs.InitialProjectionDollars06 = 0,
			fs.InitialProjectionDollars07 = 0,
			fs.InitialProjectionDollars08 = 0,
			fs.InitialProjectionDollars09 = 0,
			fs.InitialProjectionDollars10 = 0,
			fs.InitialProjectionDollars11 = 0,
			fs.InitialProjectionDollars12 = 0,
			fs.InitialProjectionHours01 = 0,
			fs.InitialProjectionHours02 = 0,
			fs.InitialProjectionHours03 = 0,
			fs.InitialProjectionHours04 = 0,
			fs.InitialProjectionHours05 = 0,
			fs.InitialProjectionHours06 = 0,
			fs.InitialProjectionHours07 = 0,
			fs.InitialProjectionHours08 = 0,
			fs.InitialProjectionHours09 = 0,
			fs.InitialProjectionHours10 = 0,
			fs.InitialProjectionHours11 = 0,
			fs.InitialProjectionHours12 = 0
		FROM fp.Staffing fs
			INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID
				AND fs.DepartmentID = roll.DepartmentID
				AND fs.JobCodeID = roll.JobCodeID
				AND fs.PayCodeGroupID = roll.PayCodeGroupID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND fs.SubsectionID = 3 -- Staffing
			AND fs.VariabilityID = 2 -- Roster only gets loaded into Fixed
		
		-- Update FactStaffing to set InitialProjection for all Unit Types
		IF (@IsFTEHidden = 1)
		BEGIN
			UPDATE fs
			SET
				fs.InitialProjectionDollars01 = roll.SampledProjectionDollars01,
				fs.InitialProjectionDollars02 = roll.SampledProjectionDollars02,
				fs.InitialProjectionDollars03 = roll.SampledProjectionDollars03,
				fs.InitialProjectionDollars04 = roll.SampledProjectionDollars04,
				fs.InitialProjectionDollars05 = roll.SampledProjectionDollars05,
				fs.InitialProjectionDollars06 = roll.SampledProjectionDollars06,
				fs.InitialProjectionDollars07 = roll.SampledProjectionDollars07,
				fs.InitialProjectionDollars08 = roll.SampledProjectionDollars08,
				fs.InitialProjectionDollars09 = roll.SampledProjectionDollars09,
				fs.InitialProjectionDollars10 = roll.SampledProjectionDollars10,
				fs.InitialProjectionDollars11 = roll.SampledProjectionDollars11,
				fs.InitialProjectionDollars12 = roll.SampledProjectionDollars12
			FROM fp.Staffing fs
				INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID
					AND fs.DepartmentID = roll.DepartmentID
					AND fs.JobCodeID = roll.JobCodeID
					AND fs.PayCodeGroupID = roll.PayCodeGroupID
			WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
				AND fs.SubsectionID = 3 -- Staffing
				AND fs.VariabilityID = 1 -- Roster only gets loaded into Fixed
		END ELSE BEGIN
						
			UPDATE fs
			SET
				fs.InitialProjectionDollars01 = roll.SampledProjectionDollars01,
				fs.InitialProjectionDollars02 = roll.SampledProjectionDollars02,
				fs.InitialProjectionDollars03 = roll.SampledProjectionDollars03,
				fs.InitialProjectionDollars04 = roll.SampledProjectionDollars04,
				fs.InitialProjectionDollars05 = roll.SampledProjectionDollars05,
				fs.InitialProjectionDollars06 = roll.SampledProjectionDollars06,
				fs.InitialProjectionDollars07 = roll.SampledProjectionDollars07,
				fs.InitialProjectionDollars08 = roll.SampledProjectionDollars08,
				fs.InitialProjectionDollars09 = roll.SampledProjectionDollars09,
				fs.InitialProjectionDollars10 = roll.SampledProjectionDollars10,
				fs.InitialProjectionDollars11 = roll.SampledProjectionDollars11,
				fs.InitialProjectionDollars12 = roll.SampledProjectionDollars12,
				fs.InitialProjectionHours01 = roll.SampledProjectionHours01,
				fs.InitialProjectionHours02 = roll.SampledProjectionHours02,
				fs.InitialProjectionHours03 = roll.SampledProjectionHours03,
				fs.InitialProjectionHours04 = roll.SampledProjectionHours04,
				fs.InitialProjectionHours05 = roll.SampledProjectionHours05,
				fs.InitialProjectionHours06 = roll.SampledProjectionHours06,
				fs.InitialProjectionHours07 = roll.SampledProjectionHours07,
				fs.InitialProjectionHours08 = roll.SampledProjectionHours08,
				fs.InitialProjectionHours09 = roll.SampledProjectionHours09,
				fs.InitialProjectionHours10 = roll.SampledProjectionHours10,
				fs.InitialProjectionHours11 = roll.SampledProjectionHours11,
				fs.InitialProjectionHours12 = roll.SampledProjectionHours12,
				fs.InitialProjectionFTEs01 = roll.SampledProjectionFTEs01,
				fs.InitialProjectionFTEs02 = roll.SampledProjectionFTEs02,
				fs.InitialProjectionFTEs03 = roll.SampledProjectionFTEs03,
				fs.InitialProjectionFTEs04 = roll.SampledProjectionFTEs04,
				fs.InitialProjectionFTEs05 = roll.SampledProjectionFTEs05,
				fs.InitialProjectionFTEs06 = roll.SampledProjectionFTEs06,
				fs.InitialProjectionFTEs07 = roll.SampledProjectionFTEs07,
				fs.InitialProjectionFTEs08 = roll.SampledProjectionFTEs08,
				fs.InitialProjectionFTEs09 = roll.SampledProjectionFTEs09,
				fs.InitialProjectionFTEs10 = roll.SampledProjectionFTEs10,
				fs.InitialProjectionFTEs11 = roll.SampledProjectionFTEs11,
				fs.InitialProjectionFTEs12 = roll.SampledProjectionFTEs12
			FROM fp.Staffing fs
				INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID
					AND fs.DepartmentID = roll.DepartmentID
					AND fs.JobCodeID = roll.JobCodeID
					AND fs.PayCodeGroupID = roll.PayCodeGroupID
			WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
				AND fs.SubsectionID = 3 -- Staffing
				AND fs.VariabilityID = 1 -- Roster only gets loaded into Fixed

		END		

		UPDATE swr
		SET
			swr.InitialProjection01 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars01 / NULLIF(roll.SampledProjectionHours01, 0), 0) END,
			swr.InitialProjection02 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars02 / NULLIF(roll.SampledProjectionHours02, 0), 0) END,
			swr.InitialProjection03 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars03 / NULLIF(roll.SampledProjectionHours03, 0), 0) END,
			swr.InitialProjection04 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars04 / NULLIF(roll.SampledProjectionHours04, 0), 0) END,
			swr.InitialProjection05 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars05 / NULLIF(roll.SampledProjectionHours05, 0), 0) END,
			swr.InitialProjection06 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars06 / NULLIF(roll.SampledProjectionHours06, 0), 0) END,
			swr.InitialProjection07 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars07 / NULLIF(roll.SampledProjectionHours07, 0), 0) END,
			swr.InitialProjection08 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars08 / NULLIF(roll.SampledProjectionHours08, 0), 0) END,
			swr.InitialProjection09 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars09 / NULLIF(roll.SampledProjectionHours09, 0), 0) END,
			swr.InitialProjection10 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars10 / NULLIF(roll.SampledProjectionHours10, 0), 0) END,
			swr.InitialProjection11 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars11 / NULLIF(roll.SampledProjectionHours11, 0), 0) END,
			swr.InitialProjection12 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars12 / NULLIF(roll.SampledProjectionHours12, 0), 0) END
		FROM fp.StaffingWageRate swr
			INNER JOIN fp.Staffing fs ON fs.StaffingWageRateID = swr.StaffingWageRateID
			INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID
				AND fs.DepartmentID = roll.DepartmentID
				AND fs.JobCodeID = roll.JobCodeID
				AND fs.PayCodeGroupID = roll.PayCodeGroupID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND fs.SubsectionID = 3 -- Staffing
	END
END
GO


---------------------------------------------

-- fp.procResetReimbursementGeneralLedger
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2023-03-08  VZ      JAZZ-57724		Initial
*************************************************************/
CREATE PROCEDURE [fp].[procResetReimbursementGeneralLedger]
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY 
AS
BEGIN
	CREATE TABLE #FilteringTable (
		EntityID INT,
		INDEX ix_1 NONCLUSTERED (EntityID)
	)
	
	INSERT INTO #FilteringTable (EntityID)
	SELECT src.EntityID
	FROM @SourceDimensionality src
		INNER JOIN fw.DimDepartment dept ON src.DepartmentID = dept.DepartmentID
	UNION
	SELECT d.EntityID
	FROM fw.DimDepartment d
		INNER JOIN @SourceDimensionality sd
			ON sd.EntityID = d.EntityID
	WHERE sd.DepartmentID IS NULL  -- filter rows, where particular DepartmentID is set as specification of EntityID 
	
	DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable)
	
	if(@isFilterPresent = 0)
		INSERT INTO #FilteringTable (EntityID) VALUES (NULL)
	
	UPDATE tbl
	SET
		tbl.BudgetAdjustedNetAsPercentOfCharge01 = tbl.InitialBudgetNetAsPercentOfCharge01, tbl.BudgetAdjustedNetAsPercentOfCharge02 = tbl.InitialBudgetNetAsPercentOfCharge02, tbl.BudgetAdjustedNetAsPercentOfCharge03 = tbl.InitialBudgetNetAsPercentOfCharge03,
		tbl.BudgetAdjustedNetAsPercentOfCharge04 = tbl.InitialBudgetNetAsPercentOfCharge04, tbl.BudgetAdjustedNetAsPercentOfCharge05 = tbl.InitialBudgetNetAsPercentOfCharge05, tbl.BudgetAdjustedNetAsPercentOfCharge06 = tbl.InitialBudgetNetAsPercentOfCharge06,
		tbl.BudgetAdjustedNetAsPercentOfCharge07 = tbl.InitialBudgetNetAsPercentOfCharge07, tbl.BudgetAdjustedNetAsPercentOfCharge08 = tbl.InitialBudgetNetAsPercentOfCharge08, tbl.BudgetAdjustedNetAsPercentOfCharge09 = tbl.InitialBudgetNetAsPercentOfCharge09,
		tbl.BudgetAdjustedNetAsPercentOfCharge10 = tbl.InitialBudgetNetAsPercentOfCharge10, tbl.BudgetAdjustedNetAsPercentOfCharge11 = tbl.InitialBudgetNetAsPercentOfCharge11, tbl.BudgetAdjustedNetAsPercentOfCharge12 = tbl.InitialBudgetNetAsPercentOfCharge12,

		tbl.TargetAdjustedNetAsPercentOfCharge01 = tbl.InitialBudgetNetAsPercentOfCharge01, tbl.TargetAdjustedNetAsPercentOfCharge02 = tbl.InitialBudgetNetAsPercentOfCharge02, tbl.TargetAdjustedNetAsPercentOfCharge03 = tbl.InitialBudgetNetAsPercentOfCharge03,
		tbl.TargetAdjustedNetAsPercentOfCharge04 = tbl.InitialBudgetNetAsPercentOfCharge04, tbl.TargetAdjustedNetAsPercentOfCharge05 = tbl.InitialBudgetNetAsPercentOfCharge05, tbl.TargetAdjustedNetAsPercentOfCharge06 = tbl.InitialBudgetNetAsPercentOfCharge06,
		tbl.TargetAdjustedNetAsPercentOfCharge07 = tbl.InitialBudgetNetAsPercentOfCharge07, tbl.TargetAdjustedNetAsPercentOfCharge08 = tbl.InitialBudgetNetAsPercentOfCharge08, tbl.TargetAdjustedNetAsPercentOfCharge09 = tbl.InitialBudgetNetAsPercentOfCharge09,
		tbl.TargetAdjustedNetAsPercentOfCharge10 = tbl.InitialBudgetNetAsPercentOfCharge10, tbl.TargetAdjustedNetAsPercentOfCharge11 = tbl.InitialBudgetNetAsPercentOfCharge11, tbl.TargetAdjustedNetAsPercentOfCharge12 = tbl.InitialBudgetNetAsPercentOfCharge12,

		tbl.ProjectionAdjustedNetAsPercentOfCharge01 = tbl.InitialProjectionNetAsPercentOfCharge01, tbl.ProjectionAdjustedNetAsPercentOfCharge02 = tbl.InitialProjectionNetAsPercentOfCharge02, tbl.ProjectionAdjustedNetAsPercentOfCharge03 = tbl.InitialProjectionNetAsPercentOfCharge03,
		tbl.ProjectionAdjustedNetAsPercentOfCharge04 = tbl.InitialProjectionNetAsPercentOfCharge04, tbl.ProjectionAdjustedNetAsPercentOfCharge05 = tbl.InitialProjectionNetAsPercentOfCharge05, tbl.ProjectionAdjustedNetAsPercentOfCharge06 = tbl.InitialProjectionNetAsPercentOfCharge06,
		tbl.ProjectionAdjustedNetAsPercentOfCharge07 = tbl.InitialProjectionNetAsPercentOfCharge07, tbl.ProjectionAdjustedNetAsPercentOfCharge08 = tbl.InitialProjectionNetAsPercentOfCharge08, tbl.ProjectionAdjustedNetAsPercentOfCharge09 = tbl.InitialProjectionNetAsPercentOfCharge09,
		tbl.ProjectionAdjustedNetAsPercentOfCharge10 = tbl.InitialProjectionNetAsPercentOfCharge10, tbl.ProjectionAdjustedNetAsPercentOfCharge11 = tbl.InitialProjectionNetAsPercentOfCharge11, tbl.ProjectionAdjustedNetAsPercentOfCharge12 = tbl.InitialProjectionNetAsPercentOfCharge12,
	
		tbl.BudgetLockType = 0, tbl.BudgetLockFlag = 0,
		tbl.TargetLockType = 0, tbl.TargetLockFlag = 0,
		tbl.ProjectionLockType = 0, tbl.ProjectionLockFlag = 0
	FROM [fp].[ReimbursementGeneralLedger] tbl
		INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = tbl.EntityID)
	WHERE tbl.EntityGroupConfigID = @EntityGroupConfigID
END
GO


---------------------------------------------

-- fp.procResetStatisticsManager
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2021-03-03  NN  	Jazz-466	Remove null joins on dept
*************************************************************/
CREATE PROCEDURE [fp].[procResetStatisticsManager]
	@BudgetConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN	
	IF OBJECT_ID('tempdb..##tmpResetStatisticsItems') IS NOT NULL DROP TABLE #tmpResetStatisticsItems

	CREATE TABLE #tmpResetStatisticsItems (StatisticsID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactStatistics] WITH (READUNCOMMITTED)
		WHERE BudgetConfigID = @BudgetConfigID	
	END
	
	
	INSERT INTO #tmpResetStatisticsItems (StatisticsID)
	SELECT StatisticsID
	FROM [fp].[FactStatistics] data
	INNER JOIN #FilterByDepartment ft on ft.DepartmentID = data.DepartmentID
	WHERE data.BudgetConfigID = @BudgetConfigID
	
	UPDATE mgr
    SET
        mgr.AdjustedValue01 = admin.AdjustedValue01,
        mgr.AdjustedValue02 = admin.AdjustedValue02,
        mgr.AdjustedValue03 = admin.AdjustedValue03,
        mgr.AdjustedValue04 = admin.AdjustedValue04,
        mgr.AdjustedValue05 = admin.AdjustedValue05,
        mgr.AdjustedValue06 = admin.AdjustedValue06,
        mgr.AdjustedValue07 = admin.AdjustedValue07,
        mgr.AdjustedValue08 = admin.AdjustedValue08,
        mgr.AdjustedValue09 = admin.AdjustedValue09,
        mgr.AdjustedValue10 = admin.AdjustedValue10,
        mgr.AdjustedValue11 = admin.AdjustedValue11,
        mgr.AdjustedValue12 = admin.AdjustedValue12,
        mgr.LockType = admin.LockType,
        mgr.LockFlag = admin.LockFlag
    FROM [fp].[FactStatisticsBudget] mgr
        INNER JOIN [fp].[FactStatistics] fgl ON mgr.StatisticsID = fgl.StatisticsID
        INNER JOIN [fp].[FactStatisticsBudget] admin ON admin.StatisticsID = mgr.StatisticsID
		INNER JOIN #tmpResetStatisticsItems filter ON fgl.StatisticsID = filter.StatisticsID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
        AND mgr.LockType <> 3
        AND admin.BudgetPhaseID = 2
        AND mgr.BudgetPhaseID = 3
        AND (
            mgr.AdjustedValue01 != admin.AdjustedValue01 OR 
            mgr.AdjustedValue02 != admin.AdjustedValue02 OR 
            mgr.AdjustedValue03 != admin.AdjustedValue03 OR 
            mgr.AdjustedValue04 != admin.AdjustedValue04 OR 
            mgr.AdjustedValue05 != admin.AdjustedValue05 OR 
            mgr.AdjustedValue06 != admin.AdjustedValue06 OR 
            mgr.AdjustedValue07 != admin.AdjustedValue07 OR 
            mgr.AdjustedValue08 != admin.AdjustedValue08 OR 
            mgr.AdjustedValue09 != admin.AdjustedValue09 OR 
            mgr.AdjustedValue10 != admin.AdjustedValue10 OR 
            mgr.AdjustedValue11 != admin.AdjustedValue11 OR 
            mgr.AdjustedValue12 != admin.AdjustedValue12)
END
GO


---------------------------------------------

-- fp.procResetVariablePatientActivityGLBudgetData
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-05-19  MY      JAZZ-36661		Add Option Recompile to Inserts
** 2	2022-08-16  BW	    JAZZ-41928		Add reset logic for projection, put behind flag
** 3 	2023-08-09  BW		JAZZ-58199	    Data model restructure for GL
*************************************************************/
CREATE   PROCEDURE [fp].[procResetVariablePatientActivityGLBudgetData]
    @EntityGroupConfigID INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
  BEGIN

	CREATE TABLE #filterTable (GeneralLedgerID INT PRIMARY KEY CLUSTERED)
	
	DECLARE @IsProjectionFlexingEnabled bit
	SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) 
	FROM fp.SystemSetting
	WHERE Name = 'Is Baseline And Projection PAF Enabled' 
	
	IF EXISTS (SELECT 1 FROM @SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
		CREATE TABLE #filterByDepartment (DepartmentID INT PRIMARY KEY CLUSTERED)
	
		INSERT INTO #filterByDepartment (DepartmentID)
		SELECT DepartmentID FROM [fp].[funcGetSourceDimensionalityAsTable](@SourceDimensionality)
		
		INSERT INTO #filterTable (GeneralLedgerID)
		SELECT DISTINCT GeneralLedgerID
		FROM [fp].[GeneralLedger] fgl
			INNER JOIN #filterByDepartment filter ON fgl.DepartmentID = filter.DepartmentID
			INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON fgl.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts
			INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu 
				ON fgl.BudgetConfigID = rvu.BudgetConfigID
				AND fgl.DepartmentID = rvu.DepartmentID
				AND fgl.AccountID = rvu.AccountID
			INNER JOIN [fp].[EntityGroupConfig] egc ON fgl.EntityGroupConfigID = egc.EntityGroupConfigID
			LEFT JOIN [fp].[FlexConfigMapping] map
            	ON fgl.DepartmentID = map.DepartmentID
                AND fgl.AccountID = map.GLAccountID
                AND fgl.EntityGroupConfigID = map.EntityGroupConfigID
			LEFT JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc
			 ON fgl.DepartmentID = fc.DepartmentID
			      AND fgl.AccountID = fc.AccountID
			      AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE 
			fgl.EntityGroupConfigID = @EntityGroupConfigID
			AND fgl.VariabilityID = 2
			AND map.FlexingTypeID IS NULL
        	AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL)	
			option (recompile)		
        	
	END
	ELSE BEGIN
	
		INSERT INTO #filterTable (GeneralLedgerID)
		SELECT DISTINCT GeneralLedgerID
		FROM [fp].[GeneralLedger] fgl
			INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON fgl.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts
			INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu 
				ON fgl.BudgetConfigID = rvu.BudgetConfigID
				AND fgl.DepartmentID = rvu.DepartmentID
				AND fgl.AccountID = rvu.AccountID
			INNER JOIN [fp].[EntityGroupConfig] egc ON fgl.EntityGroupConfigID = egc.EntityGroupConfigID
			LEFT JOIN [fp].[FlexConfigMapping] map
            	ON fgl.DepartmentID = map.DepartmentID
                AND fgl.AccountID = map.GLAccountID
                AND fgl.EntityGroupConfigID = map.EntityGroupConfigID
			LEFT JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc
			 ON fgl.DepartmentID = fc.DepartmentID
			      AND fgl.AccountID = fc.AccountID
			      AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE 
			fgl.EntityGroupConfigID = @EntityGroupConfigID
			AND fgl.VariabilityID = 2
			AND map.FlexingTypeID IS NULL
        	AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL) 	
			option (recompile)		       	
	
	END

    -- update the budget data
    UPDATE gl
    SET
        [TargetAdjusted01] = [InitialBudget01],
        [TargetAdjusted02] = [InitialBudget02],
        [TargetAdjusted03] = [InitialBudget03],
        [TargetAdjusted04] = [InitialBudget04],
        [TargetAdjusted05] = [InitialBudget05],
        [TargetAdjusted06] = [InitialBudget06],
        [TargetAdjusted07] = [InitialBudget07],
        [TargetAdjusted08] = [InitialBudget08],
        [TargetAdjusted09] = [InitialBudget09],
        [TargetAdjusted10] = [InitialBudget10],
        [TargetAdjusted11] = [InitialBudget11],
        [TargetAdjusted12] = [InitialBudget12]
    FROM [fp].[GeneralLedger] gl
    	INNER JOIN #filterTable filter ON filter.GeneralLedgerID = gl.GeneralLedgerID

	IF(@IsProjectionFlexingEnabled = 1)
	BEGIN 
		UPDATE gl
		SET
			[ProjectionAdjusted01] = [InitialProjection01],
			[ProjectionAdjusted02] = [InitialProjection02],
			[ProjectionAdjusted03] = [InitialProjection03],
			[ProjectionAdjusted04] = [InitialProjection04],
			[ProjectionAdjusted05] = [InitialProjection05],
			[ProjectionAdjusted06] = [InitialProjection06],
			[ProjectionAdjusted07] = [InitialProjection07],
			[ProjectionAdjusted08] = [InitialProjection08],
			[ProjectionAdjusted09] = [InitialProjection09],
			[ProjectionAdjusted10] = [InitialProjection10],
			[ProjectionAdjusted11] = [InitialProjection11],
			[ProjectionAdjusted12] = [InitialProjection12]
		FROM [fp].[GeneralLedger] gl
			INNER JOIN #filterTable filter ON gl.GeneralLedgerID = filter.GeneralLedgerID
	END

  END
GO


---------------------------------------------

-- fp.procResetVariablePatientActivityStaffingBudgetData
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-05-19  MY      JAZZ-36661		Add Option Recompile to Inserts
** 2	2022-07-20  MD	    JAZZ-38981		Add reset logic for projection, put behind flag
** 3	2023-11-01  MY      JAZZ-61705		Support PAF for the new data model - Staffing
*************************************************************/
CREATE   PROCEDURE [fp].[procResetVariablePatientActivityStaffingBudgetData]
    @EntityGroupConfigID INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
  BEGIN
  
  	CREATE TABLE #filterTable (StaffingID INT PRIMARY KEY CLUSTERED)

	DECLARE @IsProjectionFlexingEnabled bit

	SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) 
	FROM fp.SystemSetting
	WHERE Name = 'Is Baseline And Projection PAF Enabled' 
	
	IF EXISTS (SELECT 1 FROM @SourceDimensionality WHERE DepartmentID IS NOT NULL)
	BEGIN
		
		CREATE TABLE #filterByDepartment (DepartmentID INT PRIMARY KEY CLUSTERED)
	
		INSERT INTO #filterByDepartment (DepartmentID)
		SELECT DepartmentID FROM [fp].[funcGetSourceDimensionalityAsTable](@SourceDimensionality)
		
		INSERT INTO #filterTable (StaffingID)
		SELECT DISTINCT StaffingID
		FROM [fp].[Staffing] fs
			INNER JOIN #filterByDepartment filter ON fs.DepartmentID = filter.DepartmentID
			INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu
				ON fs.BudgetConfigID = rvu.BudgetConfigID
				AND fs.DepartmentID = rvu.DepartmentID
				AND fs.JobCodeID = rvu.JobCodeID
				AND fs.PayCodeGroupID = rvu.PayCodeGroupID
				AND 34 = rvu.UnitTypeID
			INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID
			LEFT JOIN [fp].[FlexConfigMapping] map
			 ON fs.DepartmentID = map.DepartmentID
			      AND fs.JobCodeID = map.PRJobCodeID
			      AND fs.EntityGroupConfigID = map.EntityGroupConfigID
			LEFT JOIN (
			         SELECT
			                EntityGroupConfigGUID,
			                DepartmentID,
			                JobCodeID,
			                FlexMethodID
			         FROM [fp].[viewStaffingExpenseFlexingConfig] fc) fc
			 ON fs.DepartmentID = fc.DepartmentID
			      AND fs.JobCodeID = fc.JobCodeID
			      AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
	    WHERE fs.VariabilityID = 2
	        AND fs.EntityGroupConfigID = @EntityGroupConfigID
	        AND map.FlexingTypeID IS NULL
	        AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL)		
			option (recompile)		
		
	END
	ELSE BEGIN
	
		INSERT INTO #filterTable (StaffingID)
		SELECT DISTINCT StaffingID
		FROM [fp].[Staffing] fs
			INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu
				ON fs.BudgetConfigID = rvu.BudgetConfigID
				AND fs.DepartmentID = rvu.DepartmentID
				AND fs.JobCodeID = rvu.JobCodeID
				AND fs.PayCodeGroupID = rvu.PayCodeGroupID
				AND 34 = rvu.UnitTypeID
			INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID
			LEFT JOIN [fp].[FlexConfigMapping] map
			 ON fs.DepartmentID = map.DepartmentID
			      AND fs.JobCodeID = map.PRJobCodeID
			      AND fs.EntityGroupConfigID = map.EntityGroupConfigID
			LEFT JOIN (
			         SELECT
			                EntityGroupConfigGUID,
			                DepartmentID,
			                JobCodeID,
			                FlexMethodID
			         FROM [fp].[viewStaffingExpenseFlexingConfig] fc) fc
			 ON fs.DepartmentID = fc.DepartmentID
			      AND fs.JobCodeID = fc.JobCodeID
			      AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
	    WHERE fs.VariabilityID = 2
	        AND fs.EntityGroupConfigID = @EntityGroupConfigID
	        AND map.FlexingTypeID IS NULL
	        AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL)	
			option (recompile)
	
	END
  
    IF(@IsProjectionFlexingEnabled = 1)
	BEGIN 
		UPDATE fs
		SET
			[TargetAdjustedDollars01] = [InitialBudgetDollars01],
			[TargetAdjustedDollars02] = [InitialBudgetDollars02],
			[TargetAdjustedDollars03] = [InitialBudgetDollars03],
			[TargetAdjustedDollars04] = [InitialBudgetDollars04],
			[TargetAdjustedDollars05] = [InitialBudgetDollars05],
			[TargetAdjustedDollars06] = [InitialBudgetDollars06],
			[TargetAdjustedDollars07] = [InitialBudgetDollars07],
			[TargetAdjustedDollars08] = [InitialBudgetDollars08],
			[TargetAdjustedDollars09] = [InitialBudgetDollars09],
			[TargetAdjustedDollars10] = [InitialBudgetDollars10],
			[TargetAdjustedDollars11] = [InitialBudgetDollars11],
			[TargetAdjustedDollars12] = [InitialBudgetDollars12],
			[ProjectionAdjustedDollars01] = [InitialProjectionDollars01],
			[ProjectionAdjustedDollars02] = [InitialProjectionDollars02],
			[ProjectionAdjustedDollars03] = [InitialProjectionDollars03],
			[ProjectionAdjustedDollars04] = [InitialProjectionDollars04],
			[ProjectionAdjustedDollars05] = [InitialProjectionDollars05],
			[ProjectionAdjustedDollars06] = [InitialProjectionDollars06],
			[ProjectionAdjustedDollars07] = [InitialProjectionDollars07],
			[ProjectionAdjustedDollars08] = [InitialProjectionDollars08],
			[ProjectionAdjustedDollars09] = [InitialProjectionDollars09],
			[ProjectionAdjustedDollars10] = [InitialProjectionDollars10],
			[ProjectionAdjustedDollars11] = [InitialProjectionDollars11],
			[ProjectionAdjustedDollars12] = [InitialProjectionDollars12]
		FROM [fp].[Staffing] fs
			INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID
	END ELSE
	BEGIN
		UPDATE fs
		SET
			[TargetAdjustedDollars01] = [InitialBudgetDollars01],
			[TargetAdjustedDollars02] = [InitialBudgetDollars02],
			[TargetAdjustedDollars03] = [InitialBudgetDollars03],
			[TargetAdjustedDollars04] = [InitialBudgetDollars04],
			[TargetAdjustedDollars05] = [InitialBudgetDollars05],
			[TargetAdjustedDollars06] = [InitialBudgetDollars06],
			[TargetAdjustedDollars07] = [InitialBudgetDollars07],
			[TargetAdjustedDollars08] = [InitialBudgetDollars08],
			[TargetAdjustedDollars09] = [InitialBudgetDollars09],
			[TargetAdjustedDollars10] = [InitialBudgetDollars10],
			[TargetAdjustedDollars11] = [InitialBudgetDollars11],
			[TargetAdjustedDollars12] = [InitialBudgetDollars12]
		FROM [fp].[Staffing] fs
			INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID
	END
	
  END
GO


---------------------------------------------

-- fp.procRevenueByChargeDollarsFlexConfigPopulation
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2017-06-12  IP      B-19913		APE Data Refresh - Flex Mappings, add parameter to process particular departments
** 2    2018-07-03  IP      TK-59678	fix case when @SourceDimensionality is empty
** 3    2018-09-25  GF      E-02313		Simplify source dimensionality to only department
** 4	2019-03-08	IP		B-22295		Removed using table variables, small optimizations
** 5	2021-03-12	BK  	Jazz-16331	Don't include crosswalked dimensionality if Dollars are stored in fp.FactChargeVolumeDollars
** 6	2021-06-06	MY  	JAZZ-34224	Fix proc to properly populate when using new crosswalk
** 7	2023-04-06	MD  	JAZZ-52587	Update to use new CV data structure
** 8	2023-04-13	BW		JAZZ-51383	Remove IsDollarsRemovedFromCharges
** 9	2023-05-16	MY		JAZZ-54812	Missed FactChargeVolume Reference
*************************************************************/
CREATE   PROCEDURE [fp].[procRevenueByChargeDollarsFlexConfigPopulation]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN
 	DECLARE @BudgetConfigID INT,
			@EntityGroupConfigID INT,
			@ChargeCodeBudget INT = 5,
			@FlexTypeID INT = 4;
	
	SELECT  @BudgetConfigID = bc.BudgetConfigID, 
			@EntityGroupConfigID = egc.EntityGroupConfigID 
	FROM [fp].[EntityGroupConfig] egc
		INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
	
	IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable;
	IF OBJECT_ID('tempdb..#flexMap') IS NOT NULL DROP TABLE #flexMap;

	CREATE TABLE #FilteringTable (DepartmentID INT, INDEX ix_1 NONCLUSTERED (DepartmentID))
	CREATE TABLE #flexMap (DepartmentID int NOT NULL, GLAccountID int NOT NULL);
 	
	-- Get Targeting
	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 BEGIN
		INSERT INTO #FilteringTable (DepartmentID) 
		SELECT DISTINCT DepartmentID FROM fp.ChargeVolume WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	
	ELSE BEGIN
		INSERT INTO #FilteringTable (DepartmentID)
		SELECT DepartmentID
		FROM @SourceDimensionality
	END
	
	-- In this case we are using the new crosswalk logic which only looks at the configuration table.
	-- We populate the flex config mapping still, but can pull straight from the configuration table itself for this purpose.
	-- We leverage this still so we don't have to add additional checks everywhere we are checking if something is flexed/crosswalked or not
	-- https://confluence.sdt.local/display/DD/Charge+Dollar+To+General+Ledger+Crosswalk++-+4
	INSERT INTO #flexMap(DepartmentID, GLAccountID)
	SELECT DISTINCT xwalk.DepartmentID, AccountID AS GLAccountID
	FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration xwalk
		INNER JOIN #FilteringTable ft on ft.DepartmentID = xwalk.DepartmentID
	WHERE xwalk.EntityGroupConfigID = @EntityGroupConfigID			
		
	IF (@IsDebug = 1)
	BEGIN
		SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.FlexingTypeID 
		FROM [fp].[FlexConfigMapping] fcm
			INNER JOIN #FilteringTable ft on ft.DepartmentID = fcm.DepartmentID   
		WHERE EntityGroupConfigID = @EntityGroupConfigID 
			AND FlexingTypeID = @FlexTypeID
	END ELSE 
	BEGIN
		;WITH TRG AS (
			SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.FlexingTypeID 
			FROM [fp].[FlexConfigMapping] fcm
				INNER JOIN #FilteringTable ft on ft.DepartmentID = fcm.DepartmentID   
			WHERE EntityGroupConfigID = @EntityGroupConfigID 
				AND FlexingTypeID = @FlexTypeID
		)
 
		MERGE TRG
		USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID,
					DepartmentID,
					GLAccountID,
					@FlexTypeID AS FlexingTypeID
			FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID and TRG.GLAccountID = SRC.GLAccountID
		WHEN NOT MATCHED BY TARGET THEN
		INSERT VALUES (src.EntityGroupConfigID,src.DepartmentID,src.GLAccountID,src.FlexingTypeID) 
		WHEN NOT MATCHED BY SOURCE THEN DELETE;
	END	
 
 END
GO


---------------------------------------------

-- fp.procRevenueByStatisticsFlexConfigPopulation
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2017-06-12  IP      B-19913		APE Data Refresh - Flex Mappings, add parameter to process particular departments
** 2    2018-07-03  IP      TK-59678	fix case when @SourceDimensionality is empty
** 3    2018-09-11  apukii  TK-62350	fixed typo in code
** 4    2018-09-25  GF      E-02313		Simplify source dimensionality to only department
** 5	2019-03-08	IP		B-22295		Removed using table variables, small optimizations
** 6    2021-03-26  NT      JAZZ-14122  Simplify code to remove null joins
** 7 	2023-02-06  MY	    JAZZ-48980  Update flexing to support x-department flexing
** 8 	2023-05-01  MY	    JAZZ-54277  Flex Config Mapping is not taking handling Cross Department Flexing properly
** 9 	2023-08-01  MY	    JAZZ-58153  Update to new structure
*************************************************************/
CREATE   PROCEDURE [fp].[procRevenueByStatisticsFlexConfigPopulation]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER	,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN
 	DECLARE @BudgetConfigID INT,
			@EntityGroupConfigID INT;
	
	SET @BudgetConfigID = (SELECT bc.BudgetConfigID 
						   FROM [fp].[EntityGroupConfig] egc
						   	INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
						   WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	
	CREATE TABLE #flexMap (
                    DepartmentID INT NOT NULL,
                    GLAccountID INT NOT NULL,
	                StatAccountID INT NOT NULL,
	                SourceDepartmentID INT NOT NULL
                );
 	
	IF OBJECT_ID('tempdb..#FilterFGL') IS NOT NULL DROP TABLE #FilterFGL
    IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable
		
	CREATE TABLE #FilterFGL (DepartmentID int, AccountID int, BudgetConfigID int)
  
	CREATE TABLE #FilteringTable (
		DepartmentID INT,
		INDEX ix_1 NONCLUSTERED (DepartmentID)
	)
	
	IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 
	BEGIN
		-- In the event targeting is empty, populate all departments that currently are in GL for the selected config
		INSERT INTO #FilteringTable
		SELECT DISTINCT DepartmentID
		FROM [fp].[PrimaryStatisticsConfig]
		WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
			AND IsRevenue = 1
	END ELSE BEGIN
		INSERT INTO #FilteringTable (DepartmentID)
		SELECT DepartmentID
		FROM @SourceDimensionality
	END
	
	-- Build a list of Department / Revenue Account combinations
	-- Only department/account combinations in GL are populated in the fp.FlexConfigMapping table. New records will be added as new dimensionality is imported in.
	INSERT INTO #FilterFGL (DepartmentID, AccountID, BudgetConfigID)
	SELECT fgl.DepartmentID,fgl.AccountID,fgl.BudgetConfigID 
	FROM [fp].[GeneralLedger] fgl
		INNER JOIN #FilteringTable SD on SD.DepartmentID = fgl.DepartmentID
	WHERE 
		fgl.VariabilityID = 2 -- Variable Only (used for filtering the data down)
		and fgl.BudgetConfigID = @BudgetConfigID
		and fgl.APEModelSectionID = 1 -- Revenue
 
	-- Populate all overrides for the revenue accounts. Overrides ignore traditional logic and override anything set at the department level.
	INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, nso.AccountID AS StatAccountID, stat.DepartmentID
	FROM [fp].[FactStatistics] stat
		INNER JOIN #FilterFGL fgl ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[RevenueFlexingOverrideConfig] ns ON ns.DepartmentID = fgl.DepartmentID AND ns.AccountID = fgl.AccountID
		INNER JOIN [fp].[RevenueFlexingOverrideConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID
	WHERE  ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND ns.FlexMethodID IN (
			3, -- Statistic Accounts By Patient Class
			4  -- Total Statistic Accounts
		)
	
	-- Process department level configuration changes that are not overriden. We also will exclude Department/Account combos
	-- that have multiple source departments here as that is handled in the statement below.
	-- Aka: Process the Department/Account combinations that have primary stats of "Same as Department" in the Primary Stat Config
	INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, stat.DepartmentID
	FROM #FilterFGL fgl
		INNER JOIN [fw].[DimAccount] a ON fgl.AccountID = a.AccountID
		INNER JOIN [fp].[FactStatistics] stat ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
		INNER JOIN [fp].[RevenueExpenseFlexingConfig] ns ON ns.DepartmentID = fgl.DepartmentID AND fsc.EntityGroupConfigGUID =  ns.EntityGroupConfigGUID
		LEFT JOIN [fp].[RevenueFlexingOverrideConfig] OVR ON OVR.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID 
			AND ovr.DepartmentID = stat.DepartmentID
			AND ovr.AccountID = fgl.AccountID
		LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID
	WHERE fsc.IsRevenue = 1
		AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND (
				(
						a.PatientClassID = stat.PatientClassID 
					AND ns.FlexMethodID = 3 -- Statistic Accounts By Patient Class
				) 
				OR 
				(
						ns.FlexMethodID = 4 -- Total Statistic Accounts 
					AND fsc.AccountID = stat.AccountID
				)
			)
		AND ovr.DepartmentID IS NULL -- We only want records that are not overridden
		AND pscsd.DepartmentID IS NULL; --	We want records where there is no source department specified. When no source department is specified, it's the same as the regular department

	-- Process departments with multiple source departments
	INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT fsc.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, pscsd.DepartmentID
	FROM [fp].[PrimaryStatisticsConfig] fsc
		INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID
		INNER JOIN #FilterFGL fgl ON fsc.DepartmentID = fgl.DepartmentID
		INNER JOIN [fw].[DimAccount] a ON fgl.AccountID = a.AccountID
		INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND stat.AccountID = fsc.AccountID AND fgl.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[RevenueExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID AND fsc.EntityGroupConfigGUID =  ns.EntityGroupConfigGUID
		-- Note: we allow departments OUTSIDE of the entity group config for this. We also want to include things out of the department filter
		LEFT JOIN [fp].[RevenueFlexingOverrideConfig] OVR ON OVR.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID 
			AND ovr.DepartmentID = fsc.DepartmentID
			AND ovr.AccountID = fgl.AccountID
	WHERE fsc.IsRevenue = 1
		AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND (
				(
						a.PatientClassID = stat.PatientClassID 
					AND ns.FlexMethodID = 3 -- Statistic Accounts By Patient Class
				) 
				OR 
				(
						ns.FlexMethodID = 4 -- Total Statistic Accounts 
					AND fsc.AccountID = stat.AccountID
				)
			)
		AND ovr.DepartmentID IS NULL -- We only want records that are not overridden

	IF @IsDebug = 1
	BEGIN
		SELECT '#FilteringTable', DepartmentID FROM #FilteringTable
		SELECT '#flexMap', @EntityGroupConfigID AS EntityGroupConfigID, DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID, 2 AS FlexingTypeID FROM #flexMap
	END ELSE
	BEGIN
 
		WITH TRG
		AS (
			SELECT fcm.EntityGroupConfigID,
				fcm.DepartmentID,
				fcm.GLAccountID,
				fcm.StatAccountID,
				fcm.FlexingTypeID,
				fcm.SourceDepartmentID
			FROM [fp].[FlexConfigMapping] fcm
				INNER JOIN #FilteringTable SD ON SD.DepartmentID = fcm.DepartmentID 	
			WHERE EntityGroupConfigID = @EntityGroupConfigID 
				AND FlexingTypeID = 2 -- Revenue
		)
		MERGE TRG
		USING (
			SELECT @EntityGroupConfigID AS EntityGroupConfigID,
				  DepartmentID,
				  GLAccountID,
				  StatAccountID,
				  2 AS FlexingTypeID, -- Revenue
				  SourceDepartmentID
			FROM #flexMap
		) AS Src ON TRG.DepartmentID = SRC.DepartmentID 
			AND TRG.GLAccountID = SRC.GLAccountID 
			AND TRG.StatAccountID = SRC.StatAccountID
			AND TRG.SourceDepartmentID = SRC.SourceDepartmentID
		WHEN NOT MATCHED BY TARGET THEN
		INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.GLAccountID, src.StatAccountID, src.FlexingTypeID, src.SourceDepartmentID) 
		WHEN NOT MATCHED BY SOURCE THEN DELETE;

	END
 
 END
GO


---------------------------------------------

-- fp.procRunBudgetEngine
CREATE   PROCEDURE fp.procRunBudgetEngine
	@BudgetConfigID INT = 0 -- If it's 0, we'll set it to the active	
AS
BEGIN

	IF (@BudgetConfigID = 0)
	BEGIN
		SELECT @BudgetConfigID = BudgetConfigID FROM fp.BudgetConfig WHERE IsActive = 1 AND IsEngineDisabled = 0;
	END
	
	IF (@BudgetConfigID IS NOT NULL)
	BEGIN
		-- Requests must be done outside of the proc and in a seperate migration to avoid transction weirdness.
		
		DECLARE @AssemblyQualifiedName varchar(1024);
		SET @AssemblyQualifiedName = 'Strata.CS.Jazz.ABB.Tasks.APEngineTask, Strata.CS.Jazz.ABB';
		 
		--This will be xml if your task context is in xml. In this example, the context is in json
		DECLARE @json VARCHAR(1000) = '<CONTEXTXML><BUDGETCONFIGID>' + CAST(@BudgetConfigID AS NVARCHAR(100)) + '</BUDGETCONFIGID></CONTEXTXML>';
		
		DECLARE @statusCode INT;
		EXEC dbo.procCreateTask
			@taskTypeName = @AssemblyQualifiedName,
			@contextXML = @json,
			@userName = 'HangfireMigration',
			@taskSource = 'Migration',
			@statusCode = @statusCode;
		  
		--We get back http status code
		IF (@statusCode < 200 OR @statusCode > 299)
		BEGIN
		    -- Task Creation failed
			RAISERROR ('Task Creation failed', 50, 0);
		END
	END

END
GO


---------------------------------------------

-- fp.procRunBudgetTargetSplitUpgrade
CREATE PROCEDURE fp.procRunBudgetTargetSplitUpgrade
	@BudgetConfigID INT
AS
BEGIN
	
	IF EXISTS (
		SELECT TOP 1 1 FROM [fp].[StatisticsAdjustment] adj
			INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID
		)
	BEGIN
		PRINT 'The upgrade has already been completed for this budget'
		RETURN;
	END
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'AdjustmentGrouping_PreSplitUpgrade'))
		DROP TABLE [bak].[AdjustmentGrouping_PreSplitUpgrade]
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAdjustment_PreSplitUpgrade'))
		DROP TABLE [bak].[StatisticsAdjustment_PreSplitUpgrade]
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAdjustmentRate_PreSplitUpgrade'))
		DROP TABLE [bak].[StatisticsAdjustmentRate_PreSplitUpgrade]
	
	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAdjustmentImport_PreSplitUpgrade'))
		DROP TABLE [bak].[StatisticsAdjustmentImport_PreSplitUpgrade]

	IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAddProviderAdjustment_PreSplitUpgrade'))
		DROP TABLE [bak].[StatisticsAddProviderAdjustment_PreSplitUpgrade]
	
	SELECT * INTO [bak].[AdjustmentGrouping_PreSplitUpgrade] FROM [fp].[AdjustmentGrouping]
	SELECT * INTO [bak].[StatisticsAdjustment_PreSplitUpgrade] FROM [fp].[StatisticsAdjustment]
	SELECT * INTO [bak].[StatisticsAdjustmentRate_PreSplitUpgrade] FROM [fp].[StatisticsAdjustmentRate]
	SELECT * INTO [bak].[StatisticsAdjustmentImport_PreSplitUpgrade] FROM [fp].[StatisticsAdjustmentImport]
	SELECT * INTO [bak].[StatisticsAddProviderAdjustment_PreSplitUpgrade] FROM [fp].[StatisticAddProviderAdjustment]

	EXEC fp.procBudgetTargetSplitUpgrade_Statistics @BudgetConfigID
	
END
GO


---------------------------------------------

-- fp.procSampleBenefitRates_InitialAndSampled
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2019-02-12	MY		TK-74715	Moved Benefits Rate Sampling from code to Proc
** 2	2019-11-12	MY		B-24221 	Removed FF for Benefits Rate Sampling
** 3	2020-03-31	LR		B-24089 	Removed check for null within join conditions
*************************************************************/
CREATE PROCEDURE [fp].[procSampleBenefitRates_InitialAndSampled]
		@EntityGroupConfigID INT, 
		@BudgetConfigID INT,	
		@AccountID INT, 
		@BenefitsValueTotalType INT, 
		@BenefitsValueRateType INT, 
		@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE BudgetConfigID = @BudgetConfigID	
	END	
	
		
	-- This is using the new logic for sampling benefit rates, we cannot independently sample rates the way we are doing. Rates are always calculated using the 
	-- int data, and this cannot ever be calculated (well for flexing's sake) using anything else. The old logic was taking the initial values which is basically taking the post flexed
	-- staffing dollars / post flexed staffing X for example which we don't want.
	-- IMPORTANT NOTE: This is behind a feature flag because this will cause numbers to change so we want to make sure that numbers don't change for clients mid-budget.

	UPDATE fb SET 
		SampledBudget01 = CASE WHEN COALESCE(driver.SampledBudget01, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget01, 0) / NULLIF(driver.SampledBudget01, 0), 0) END,
		SampledBudget02 = CASE WHEN COALESCE(driver.SampledBudget02, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget02, 0) / NULLIF(driver.SampledBudget02, 0), 0) END,
		SampledBudget03 = CASE WHEN COALESCE(driver.SampledBudget03, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget03, 0) / NULLIF(driver.SampledBudget03, 0), 0) END,
		SampledBudget04 = CASE WHEN COALESCE(driver.SampledBudget04, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget04, 0) / NULLIF(driver.SampledBudget04, 0), 0) END,
		SampledBudget05 = CASE WHEN COALESCE(driver.SampledBudget05, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget05, 0) / NULLIF(driver.SampledBudget05, 0), 0) END,
		SampledBudget06 = CASE WHEN COALESCE(driver.SampledBudget06, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget06, 0) / NULLIF(driver.SampledBudget06, 0), 0) END,
		SampledBudget07 = CASE WHEN COALESCE(driver.SampledBudget07, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget07, 0) / NULLIF(driver.SampledBudget07, 0), 0) END,
		SampledBudget08 = CASE WHEN COALESCE(driver.SampledBudget08, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget08, 0) / NULLIF(driver.SampledBudget08, 0), 0) END,
		SampledBudget09 = CASE WHEN COALESCE(driver.SampledBudget09, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget09, 0) / NULLIF(driver.SampledBudget09, 0), 0) END,
		SampledBudget10 = CASE WHEN COALESCE(driver.SampledBudget10, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget10, 0) / NULLIF(driver.SampledBudget10, 0), 0) END,
		SampledBudget11 = CASE WHEN COALESCE(driver.SampledBudget11, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget11, 0) / NULLIF(driver.SampledBudget11, 0), 0) END,
		SampledBudget12 = CASE WHEN COALESCE(driver.SampledBudget12, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget12, 0) / NULLIF(driver.SampledBudget12, 0), 0) END,
		SampledProjection01 = CASE WHEN COALESCE(driver.SampledProjection01, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection01, 0) / NULLIF(driver.SampledProjection01, 0), 0) END,
		SampledProjection02 = CASE WHEN COALESCE(driver.SampledProjection02, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection02, 0) / NULLIF(driver.SampledProjection02, 0), 0) END,
		SampledProjection03 = CASE WHEN COALESCE(driver.SampledProjection03, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection03, 0) / NULLIF(driver.SampledProjection03, 0), 0) END,
		SampledProjection04 = CASE WHEN COALESCE(driver.SampledProjection04, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection04, 0) / NULLIF(driver.SampledProjection04, 0), 0) END,
		SampledProjection05 = CASE WHEN COALESCE(driver.SampledProjection05, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection05, 0) / NULLIF(driver.SampledProjection05, 0), 0) END,
		SampledProjection06 = CASE WHEN COALESCE(driver.SampledProjection06, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection06, 0) / NULLIF(driver.SampledProjection06, 0), 0) END,
		SampledProjection07 = CASE WHEN COALESCE(driver.SampledProjection07, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection07, 0) / NULLIF(driver.SampledProjection07, 0), 0) END,
		SampledProjection08 = CASE WHEN COALESCE(driver.SampledProjection08, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection08, 0) / NULLIF(driver.SampledProjection08, 0), 0) END,
		SampledProjection09 = CASE WHEN COALESCE(driver.SampledProjection09, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection09, 0) / NULLIF(driver.SampledProjection09, 0), 0) END,
		SampledProjection10 = CASE WHEN COALESCE(driver.SampledProjection10, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection10, 0) / NULLIF(driver.SampledProjection10, 0), 0) END,
		SampledProjection11 = CASE WHEN COALESCE(driver.SampledProjection11, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection11, 0) / NULLIF(driver.SampledProjection11, 0), 0) END,
		SampledProjection12 = CASE WHEN COALESCE(driver.SampledProjection12, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection12, 0) / NULLIF(driver.SampledProjection12, 0), 0) END        
	FROM fp.FactBenefits fb 
		INNER JOIN 
			(SELECT SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
				 SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
				 DepartmentID
			 FROM fp.FactBenefits WHERE EntityGroupConfigID = @EntityGroupConfigID AND UnitTypeID = 34 AND AccountID = @AccountID) dollars
			ON fb.DepartmentID = dollars.DepartmentID 
		INNER JOIN 
			(SELECT SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
				 SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
				 DepartmentID
			 FROM fp.FactBenefits WHERE EntityGroupConfigID = @EntityGroupConfigID AND UnitTypeID = @BenefitsValueTotalType AND AccountID = @AccountID) driver
			ON fb.DepartmentID = driver.DepartmentID 
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fb.DepartmentID)
	WHERE 
		fb.BudgetConfigID = @BudgetConfigID                   
		and fb.EntityGroupConfigID = @EntityGroupConfigID
		and fb.AccountID = @AccountID
		AND fb.UnitTypeID = @BenefitsValueRateType
		
	-- Copy the sampled rates to the initial rates
	UPDATE fb SET 
		InitialBudget01 = SampledBudget01,
		InitialBudget02 = SampledBudget02,
		InitialBudget03 = SampledBudget03,
		InitialBudget04 = SampledBudget04,
		InitialBudget05 = SampledBudget05,
		InitialBudget06 = SampledBudget06,
		InitialBudget07 = SampledBudget07,
		InitialBudget08 = SampledBudget08,
		InitialBudget09 = SampledBudget09,
		InitialBudget10 = SampledBudget10,
		InitialBudget11 = SampledBudget11,
		InitialBudget12 = SampledBudget12,
		InitialProjection01 = SampledProjection01,
		InitialProjection02 = SampledProjection02,
		InitialProjection03 = SampledProjection03,
		InitialProjection04 = SampledProjection04,
		InitialProjection05 = SampledProjection05,
		InitialProjection06 = SampledProjection06,
		InitialProjection07 = SampledProjection07,
		InitialProjection08 = SampledProjection08,
		InitialProjection09 = SampledProjection09,
		InitialProjection10 = SampledProjection10,
		InitialProjection11 = SampledProjection11,
		InitialProjection12 = SampledProjection12        
	FROM fp.FactBenefits fb 
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fb.DepartmentID)
	WHERE 
		fb.BudgetConfigID = @BudgetConfigID                   
		AND fb.EntityGroupConfigID = @EntityGroupConfigID
		AND fb.AccountID = @AccountID
		AND fb.UnitTypeID = @BenefitsValueRateType
		

END
GO


---------------------------------------------

-- fp.procSampleBenefitsBudgetData
CREATE PROCEDURE [fp].[procSampleBenefitsBudgetData]
@EntityGroupConfigID int
AS
BEGIN

	-- update the budget data
	INSERT INTO [fp].[FactBenefitsBudget]([BenefitsID], [BudgetPhaseID], 
					[AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], 
					[FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
	SELECT [BenefitsID], [BudgetPhaseID],
		   [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], 
		   [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12]
	FROM [fp].[FactBenefits] fs
		 CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID)
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0
	
END
GO


---------------------------------------------

-- fp.procSampleBenefitsClearData
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author			WI			Description
** 1		2021-02-24		lrenadesouza	JAZZ-12907	Added rolling deletes for all tables 
** 2		2023-04-18		mdeboer			JAZZ-53496	Remove adjustment delete logic
** 3		2023-07-05		mdeboer			JAZZ-55672	Add remove config logic
***************************************************************/
CREATE   PROCEDURE [fp].[procSampleBenefitsClearData]
	@BudgetConfigGUID uniqueidentifier,	
	@EntityGroupConfigID int,
	@IsRemoveConfig BIT = 0
AS
BEGIN
	DECLARE @ChunkCount INT;
	DECLARE @r INT;
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END

	CREATE TABLE #BenefitsToDelete (BenefitsID INT)

	IF @IsRemoveConfig = 1
	BEGIN
		INSERT #BenefitsToDelete with (tablock) (BenefitsID)
		SELECT BenefitsID FROM fp.FactBenefits
		WHERE EntityGroupConfigID = @EntityGroupConfigID 
	END
	ELSE
	BEGIN
		INSERT #BenefitsToDelete with (tablock) (BenefitsID)
		SELECT BenefitsID FROM fp.FactBenefits
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) bch FROM [fp].[BenefitsChangeHistory] bch INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bch.BenefitsID WHERE fb.EntityGroupConfigID = @EntityGroupConfigID;
	   SET @r = @@ROWCOUNT;	 
	   COMMIT TRANSACTION;
	END
	
	-- delete existing data (have to do value tables first so that we still have EntityGroupConfigID)
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) bb 
			FROM [fp].[FactBenefitsBudget] bb 
			INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bb.BenefitsID 
			INNER JOIN #BenefitsToDelete btd on bb.BenefitsID = btd.BenefitsID	
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) bb 
			FROM [fp].[FactBenefitsProjection] bb 
			INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bb.BenefitsID 
			INNER JOIN #BenefitsToDelete btd on bb.BenefitsID = btd.BenefitsID	
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) bb 
			FROM [fp].[FactBenefitsHistory] bb 
			INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bb.BenefitsID 
			INNER JOIN #BenefitsToDelete btd on bb.BenefitsID = btd.BenefitsID	
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) fb
			FROM [fp].[FactBenefits] fb			
			INNER JOIN #BenefitsToDelete btd on fb.BenefitsID = btd.BenefitsID
			WHERE fb.EntityGroupConfigID = @EntityGroupConfigID;
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
END;
GO


---------------------------------------------

-- fp.procSampleBenefitsDimensionality
CREATE PROCEDURE [fp].[procSampleBenefitsDimensionality]
	@BudgetConfigID int,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint
AS
BEGIN

	INSERT INTO [fp].[FactBenefits]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID], [FlexMethodID])
	SELECT
		DISTINCT
		@BudgetConfigID,
		@EntityGroupConfigID,
		dept.EntityID,
		gl.DepartmentID, 
		gl.AccountID,
		acc.OBDollarsFinancialReportingID,
		ut.UnitTypeID,
		0 AS FlexMethodID
	FROM
		[int].[FactGL] gl 
		INNER JOIN [fw].[DimDepartment] dept ON gl.DepartmentID = dept.DepartmentID
		INNER JOIN [fw].[DimAccount] acc on gl.AccountID = acc.AccountID 
		INNER JOIN [fp].[ModelSectionMap] msm ON msm.OBModelSectionName = acc.OBModelSectionName
		INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
        INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		LEFT JOIN (
				SELECT DISTINCT DepartmentID, AccountID 
				FROM [fp].[FactBenefits] 
				WHERE EntityGroupConfigID = @EntityGroupConfigID
				AND IsNew = 1
			) ben
			ON gl.DepartmentID = ben.DepartmentID
			AND gl.AccountID = ben.AccountID
		CROSS APPLY (VALUES (34),(144),(169),(170),(171)) ut(UnitTypeID)		
	WHERE 
		((gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeclassID = @SourceTimeClassID)  -- baseline
		 OR (gl.FiscalYearID = @CurrentFiscalYearID)  		                                -- projection (current year actuals)
		 OR (gl.FiscalYearID = @CurrentFiscalYearID - 1 AND gl.TimeClassID = 1))  		  -- prior year, actual & budget
		AND gl.IsDeleted = 0
		AND gl.FiscalMonthID != 0
		AND acc.OBDollarsFinancialReportingID != 0
        AND egc.EntityGroupConfigID = @EntityGroupConfigID
		AND msm.APEModelSectionID = 5
		AND ben.DepartmentID IS NULL

END
GO


---------------------------------------------

-- fp.procSampleBenefitsFTEDriverValues
/**************************************************************
** Change History
** CID  Date		Author	     WI			Description
** 1    2019-02-14	IP      B-22020     Added AccountID as CSV
** 2    2019-03-26  IP      B-22466     Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 3    2019-06-02  MY      TK-74658    Removing remaining table variable functions
** 4    2020-03-31  LR      B-24089     Removed check for null within join conditions
** 5    2022-08-31	BW      JAZZ-41678  Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
** 6    2023-10-31	BK      JAZZ-62801  Update for staffing restructure
*************************************************************/
CREATE   PROCEDURE [fp].[procSampleBenefitsFTEDriverValues]
 	@EntityGroupConfigID INT,
	@AccountID VARCHAR(MAX),
	@FinancialReportingID INT,
	@TimeClassID INT,
	@FiscalYearID INT,
	@PayrollFilterSql NVARCHAR(MAX),
	@PayrollFilterTempTableSQL VARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 WITH RECOMPILE
 AS
 BEGIN
  
	CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int)
	INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID)
	SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
    -- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID		
	END	
 	
	DECLARE @DynamicSql NVARCHAR(MAX)	
	
	IF object_id('tempdb..#basisIDs') IS NOT NULL 
	BEGIN
		DROP TABLE #basisIDs
	END
	IF object_id('tempdb..#StaffingFtes') IS NOT NULL 
	BEGIN
		DROP TABLE #StaffingFtes
	END
	
 	CREATE TABLE #basisIDs (BenefitsID INT);
 	CREATE TABLE #StaffingFtes (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, BudgetPhaseID INT,
								Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), 
								Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), 
								Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8))
 
 	IF (@TimeClassID = 2)
	BEGIN
	
		set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
				
		INSERT INTO #StaffingFtes
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			CAST(2 as TINYINT),
			SUM(pr.TargetAdjustedHours01) / MAX(wh.Month01) AS Value01,
			SUM(pr.TargetAdjustedHours02) / MAX(wh.Month02) AS Value02,
			SUM(pr.TargetAdjustedHours03) / MAX(wh.Month03) AS Value03,
			SUM(pr.TargetAdjustedHours04) / MAX(wh.Month04) AS Value04,
			SUM(pr.TargetAdjustedHours05) / MAX(wh.Month05) AS Value05,
			SUM(pr.TargetAdjustedHours06) / MAX(wh.Month06) AS Value06,
			SUM(pr.TargetAdjustedHours07) / MAX(wh.Month07) AS Value07,
			SUM(pr.TargetAdjustedHours08) / MAX(wh.Month08) AS Value08,
			SUM(pr.TargetAdjustedHours09) / MAX(wh.Month09) AS Value09,
			SUM(pr.TargetAdjustedHours10) / MAX(wh.Month10) AS Value10,
			SUM(pr.TargetAdjustedHours11) / MAX(wh.Month11) AS Value11,
			SUM(pr.TargetAdjustedHours12) / MAX(wh.Month12) AS Value12
		FROM [fp].[Staffing] pr
			LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID 
			INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
			INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + '
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID)
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND exc.PayCodeGroupID IS NULL
		  AND (ft.BudgetPhaseID IS NULL OR 2 = ft.BudgetPhaseID)		    
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID

		INSERT INTO #StaffingFtes
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			CAST(3 as TINYINT),
			SUM(pr.BudgetAdjustedHours01) / MAX(wh.Month01) AS Value01,
			SUM(pr.BudgetAdjustedHours02) / MAX(wh.Month02) AS Value02,
			SUM(pr.BudgetAdjustedHours03) / MAX(wh.Month03) AS Value03,
			SUM(pr.BudgetAdjustedHours04) / MAX(wh.Month04) AS Value04,
			SUM(pr.BudgetAdjustedHours05) / MAX(wh.Month05) AS Value05,
			SUM(pr.BudgetAdjustedHours06) / MAX(wh.Month06) AS Value06,
			SUM(pr.BudgetAdjustedHours07) / MAX(wh.Month07) AS Value07,
			SUM(pr.BudgetAdjustedHours08) / MAX(wh.Month08) AS Value08,
			SUM(pr.BudgetAdjustedHours09) / MAX(wh.Month09) AS Value09,
			SUM(pr.BudgetAdjustedHours10) / MAX(wh.Month10) AS Value10,
			SUM(pr.BudgetAdjustedHours11) / MAX(wh.Month11) AS Value11,
			SUM(pr.BudgetAdjustedHours12) / MAX(wh.Month12) AS Value12
		FROM [fp].[Staffing] pr
			LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID          
			INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
			INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + '
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND exc.PayCodeGroupID IS NULL
		  AND (ft.BudgetPhaseID IS NULL OR 3 = ft.BudgetPhaseID)		    
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID
					
					
		-- Update Value			
		UPDATE budg
		SET 
			AdjustedValue01 = Value01, AdjustedValue02 = Value02, AdjustedValue03 = Value03, AdjustedValue04 = Value04,
			AdjustedValue05 = Value05, AdjustedValue06 = Value06, AdjustedValue07 = Value07, AdjustedValue08 = Value08,
			AdjustedValue09 = Value09, AdjustedValue10 = Value10, AdjustedValue11 = Value11, AdjustedValue12 = Value12,
			FlexedValue01 = Value01, FlexedValue02 = Value02, FlexedValue03 = Value03, FlexedValue04 = Value04,
			FlexedValue05 = Value05, FlexedValue06 = Value06, FlexedValue07 = Value07, FlexedValue08 = Value08,
			FlexedValue09 = Value09, FlexedValue10 = Value10, FlexedValue11 = Value11, FlexedValue12 = Value12
		FROM [fp].[FactBenefits] benefits
			INNER JOIN [fp].[FactBenefitsBudget] budg ON benefits.BenefitsID = budg.BenefitsID
			INNER JOIN #StaffingFtes staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.BudgetPhaseID = budg.BudgetPhaseID
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		       AND benefits.UnitTypeID = 144
			
		';
	
	END ELSE BEGIN
	
		set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		DECLARE @MonthsLoaded INT	
		SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
		
		INSERT INTO #StaffingFtes
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			CAST(3 as TINYINT),
			SUM(pr.ProjectionAdjustedHours01) / MAX(wh.Month01) AS Value01,
			SUM(pr.ProjectionAdjustedHours02) / MAX(wh.Month02) AS Value02,
			SUM(pr.ProjectionAdjustedHours03) / MAX(wh.Month03) AS Value03,
			SUM(pr.ProjectionAdjustedHours04) / MAX(wh.Month04) AS Value04,
			SUM(pr.ProjectionAdjustedHours05) / MAX(wh.Month05) AS Value05,
			SUM(pr.ProjectionAdjustedHours06) / MAX(wh.Month06) AS Value06,
			SUM(pr.ProjectionAdjustedHours07) / MAX(wh.Month07) AS Value07,
			SUM(pr.ProjectionAdjustedHours08) / MAX(wh.Month08) AS Value08,
			SUM(pr.ProjectionAdjustedHours09) / MAX(wh.Month09) AS Value09,
			SUM(pr.ProjectionAdjustedHours10) / MAX(wh.Month10) AS Value10,
			SUM(pr.ProjectionAdjustedHours11) / MAX(wh.Month11) AS Value11,
			SUM(pr.ProjectionAdjustedHours12) / MAX(wh.Month12) AS Value12
		FROM [fp].[Staffing] pr
			LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID          
			INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
			INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + '
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID			
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND exc.PayCodeGroupID IS NULL
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID
			
		-- Update Value
		UPDATE proj
		SET 
			proj.AdjustedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END,
			proj.AdjustedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END,
			proj.AdjustedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END,
			proj.AdjustedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END,
			proj.AdjustedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END,
			proj.AdjustedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END,
			proj.AdjustedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END,
			proj.AdjustedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END,
			proj.AdjustedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END,
			proj.AdjustedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END,
			proj.AdjustedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END,
			proj.AdjustedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END,
			proj.FlexedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END,
			proj.FlexedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END,
			proj.FlexedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END,
			proj.FlexedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END,
			proj.FlexedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END,
			proj.FlexedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END,
			proj.FlexedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END,
			proj.FlexedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END,
			proj.FlexedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END,
			proj.FlexedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END,
			proj.FlexedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END,
			proj.FlexedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END
		FROM [fp].[FactBenefits] benefits
			INNER JOIN [fp].[FactBenefitsProjection] proj ON benefits.BenefitsID = proj.BenefitsID
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = benefits.DepartmentID /* adding this here so that the BudgetPhase will be respected - once we convert benefits to new structure, this can go away since the filter is applied on #staffingSalaries table */
			INNER JOIN #StaffingFtes staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) /* also remove this when converting benfits */
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		       AND benefits.UnitTypeID = 144
		';
	
	END
	
	EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY',  @SourceDimensionality = @SourceDimensionality;  
 END
GO


---------------------------------------------

-- fp.procSampleBenefitsFTEDriverValues_InitialValue
/**************************************************************
** Change History
** CID  Date		Author    WI			 Description
** 1	2019-02-14  IP		B-22020	 Added AccountID as CSV
** 2 	2019-06-02  MY      TK-74658	 Removing remaining table variable functions
** 3 	2020-03-31  LR      B-24089 	 Removed check for null within join conditions
** 4	2022-08-31  BW		JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
** 5	2023-10-31  BK		JAZZ-62801 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
**************************************************************/
CREATE PROCEDURE [fp].[procSampleBenefitsFTEDriverValues_InitialValue]
 	@EntityGroupConfigID INT,
	@AccountID VARCHAR(MAX),
	@FinancialReportingID INT,
	@TimeClassID INT,
	@FiscalYearID INT,
	@PayrollFilterSql NVARCHAR(MAX),
	@PayrollFilterTempTableSQL VARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
 
 	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID	
	END	
 
 	DECLARE @DynamicSql NVARCHAR(MAX)	

	IF object_id('tempdb..#StaffingFtes') IS NOT NULL 
	BEGIN
		DROP TABLE #StaffingFtes
	END
	
 	CREATE TABLE #StaffingFtes (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, 
								Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), 
								Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), 
								Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8))
 
 	IF (@TimeClassID = 2)
	BEGIN
	
		set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
		INSERT INTO #StaffingFtes
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			SUM(pr.InitialBudgetHours01) / MAX(wh.Month01) AS Value01,
			SUM(pr.InitialBudgetHours02) / MAX(wh.Month02) AS Value02,
			SUM(pr.InitialBudgetHours03) / MAX(wh.Month03) AS Value03,
			SUM(pr.InitialBudgetHours04) / MAX(wh.Month04) AS Value04,
			SUM(pr.InitialBudgetHours05) / MAX(wh.Month05) AS Value05,
			SUM(pr.InitialBudgetHours06) / MAX(wh.Month06) AS Value06,
			SUM(pr.InitialBudgetHours07) / MAX(wh.Month07) AS Value07,
			SUM(pr.InitialBudgetHours08) / MAX(wh.Month08) AS Value08,
			SUM(pr.InitialBudgetHours09) / MAX(wh.Month09) AS Value09,
			SUM(pr.InitialBudgetHours10) / MAX(wh.Month10) AS Value10,
			SUM(pr.InitialBudgetHours11) / MAX(wh.Month11) AS Value11,
			SUM(pr.InitialBudgetHours12) / MAX(wh.Month12) AS Value12
		FROM [fp].[Staffing] pr
			LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID          
			INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
			INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + '
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID)
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND exc.PayCodeGroupID IS NULL
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID
			
		
					
		-- Update Original Value
		UPDATE benefits
		SET 
			InitialBudget01 = Value01, InitialBudget02 = Value02, InitialBudget03 = Value03, InitialBudget04 = Value04,
			InitialBudget05 = Value05, InitialBudget06 = Value06, InitialBudget07 = Value07, InitialBudget08 = Value08,
			InitialBudget09 = Value09, InitialBudget10 = Value10, InitialBudget11 = Value11, InitialBudget12 = Value12
		FROM [fp].[FactBenefits] benefits
			INNER JOIN #StaffingFtes staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		        AND benefits.UnitTypeID = 144
			
		';
	
	END ELSE BEGIN
	
	set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		DECLARE @MonthsLoaded INT	
		SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
		

		INSERT INTO #StaffingFtes
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			SUM(pr.InitialProjectionHours01) / MAX(wh.Month01) AS Value01,
			SUM(pr.InitialProjectionHours02) / MAX(wh.Month02) AS Value02,
			SUM(pr.InitialProjectionHours03) / MAX(wh.Month03) AS Value03,
			SUM(pr.InitialProjectionHours04) / MAX(wh.Month04) AS Value04,
			SUM(pr.InitialProjectionHours05) / MAX(wh.Month05) AS Value05,
			SUM(pr.InitialProjectionHours06) / MAX(wh.Month06) AS Value06,
			SUM(pr.InitialProjectionHours07) / MAX(wh.Month07) AS Value07,
			SUM(pr.InitialProjectionHours08) / MAX(wh.Month08) AS Value08,
			SUM(pr.InitialProjectionHours09) / MAX(wh.Month09) AS Value09,
			SUM(pr.InitialProjectionHours10) / MAX(wh.Month10) AS Value10,
			SUM(pr.InitialProjectionHours11) / MAX(wh.Month11) AS Value11,
			SUM(pr.InitialProjectionHours12) / MAX(wh.Month12) AS Value12
		FROM [fp].[Staffing] pr
			LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID          
			INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
			INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + '
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID				
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND exc.PayCodeGroupID IS NULL			
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID
		
			   
	   -- Update Original Value
		UPDATE benefits
		SET 
			InitialProjection01 = CASE WHEN 1 <=  @MonthsLoaded THEN SampledProjection01 ELSE Value01 END,
			InitialProjection02 = CASE WHEN 2 <=  @MonthsLoaded THEN SampledProjection02 ELSE Value02 END,
			InitialProjection03 = CASE WHEN 3 <=  @MonthsLoaded THEN SampledProjection03 ELSE Value03 END,
			InitialProjection04 = CASE WHEN 4 <=  @MonthsLoaded THEN SampledProjection04 ELSE Value04 END,
			InitialProjection05 = CASE WHEN 5 <=  @MonthsLoaded THEN SampledProjection05 ELSE Value05 END,
			InitialProjection06 = CASE WHEN 6 <=  @MonthsLoaded THEN SampledProjection06 ELSE Value06 END,
			InitialProjection07 = CASE WHEN 7 <=  @MonthsLoaded THEN SampledProjection07 ELSE Value07 END,
			InitialProjection08 = CASE WHEN 8 <=  @MonthsLoaded THEN SampledProjection08 ELSE Value08 END,
			InitialProjection09 = CASE WHEN 9 <=  @MonthsLoaded THEN SampledProjection09 ELSE Value09 END,
			InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE Value10 END,
			InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE Value11 END,
			InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE Value12 END
		FROM [fp].[FactBenefits] benefits
			INNER JOIN #StaffingFtes staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		        AND benefits.UnitTypeID = 144
	   
		';
	END
	
	EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY',  @SourceDimensionality = @SourceDimensionality;
	
 END
GO


---------------------------------------------

-- fp.procSampleBenefitsHistoricalData
CREATE PROCEDURE [fp].[procSampleBenefitsHistoricalData]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
AS
BEGIN

	-- pad all of the data
	INSERT INTO [fp].[FactBenefitsHistory]	([BenefitsID])
	SELECT fb.[BenefitsID]
	FROM [fp].[FactBenefits] fb
	     LEFT JOIN fp.FactBenefitsHistory h ON fb.BenefitsID = h.BenefitsID
	WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.IsNew = 0 AND h.BenefitsID IS NULL


	-- set all of the values for prior year actual
	UPDATE
		fbh
	SET
		PriorYearActualValue01 = ISNULL(Month01, 0),
		PriorYearActualValue02 = ISNULL(Month02, 0),
		PriorYearActualValue03 = ISNULL(Month03, 0),
		PriorYearActualValue04 = ISNULL(Month04, 0),
		PriorYearActualValue05 = ISNULL(Month05, 0),
		PriorYearActualValue06 = ISNULL(Month06, 0),
		PriorYearActualValue07 = ISNULL(Month07, 0),
		PriorYearActualValue08 = ISNULL(Month08, 0),
		PriorYearActualValue09 = ISNULL(Month09, 0),
		PriorYearActualValue10 = ISNULL(Month10, 0),
		PriorYearActualValue11 = ISNULL(Month11, 0),
		PriorYearActualValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactBenefitsHistory] fbh
		INNER JOIN [fp].[FactBenefits] fb ON fb.BenefitsID = fbh.BenefitsID
		INNER JOIN 
		(SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value
		 FROM [int].[FactGL] gl 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID			 
		 WHERE gl.FiscalYearID = (@CurrentFiscalYearID - 1) AND gl.TimeclassID = 1 AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0
		 GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON fb.DepartmentID = pv.DepartmentID
			AND fb.AccountID = pv.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
	WHERE
		fb.EntityGroupConfigID = @EntityGroupConfigID
		AND fb.UnitTypeID = 34


	-- set all of the values for current year actual/annualized
	UPDATE
		fbh
	SET
		ActualYTDValue01 = ISNULL(Month01, 0),
		ActualYTDValue02 = ISNULL(Month02, 0),
		ActualYTDValue03 = ISNULL(Month03, 0),
		ActualYTDValue04 = ISNULL(Month04, 0),
		ActualYTDValue05 = ISNULL(Month05, 0),
		ActualYTDValue06 = ISNULL(Month06, 0),
		ActualYTDValue07 = ISNULL(Month07, 0),
		ActualYTDValue08 = ISNULL(Month08, 0),
		ActualYTDValue09 = ISNULL(Month09, 0),
		ActualYTDValue10 = ISNULL(Month10, 0),
		ActualYTDValue11 = ISNULL(Month11, 0),
		ActualYTDValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactBenefitsHistory] fbh
		INNER JOIN [fp].[FactBenefits] fb ON fb.BenefitsID = fbh.BenefitsID
		INNER JOIN 
		(SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value
		 FROM [int].[FactGL] gl 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID
		 WHERE gl.FiscalYearID = @CurrentFiscalYearID AND gl.TimeclassID = 1 AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded
		 GROUP BY gl.DepartmentID, gl.AccountID,  fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON fb.DepartmentID = pv.DepartmentID
			AND fb.AccountID = pv.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
	WHERE
		fb.EntityGroupConfigID = @EntityGroupConfigID
		AND fb.UnitTypeID = 34

	
	-- set all of the values for current year budget
	UPDATE
		fbh
	SET
		CurrentYearBudget01 = ISNULL(Month01, 0),
		CurrentYearBudget02 = ISNULL(Month02, 0),
		CurrentYearBudget03 = ISNULL(Month03, 0),
		CurrentYearBudget04 = ISNULL(Month04, 0),
		CurrentYearBudget05 = ISNULL(Month05, 0),
		CurrentYearBudget06 = ISNULL(Month06, 0),
		CurrentYearBudget07 = ISNULL(Month07, 0),
		CurrentYearBudget08 = ISNULL(Month08, 0),
		CurrentYearBudget09 = ISNULL(Month09, 0),
		CurrentYearBudget10 = ISNULL(Month10, 0),
		CurrentYearBudget11 = ISNULL(Month11, 0),
		CurrentYearBudget12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactBenefitsHistory] fbh
		INNER JOIN [fp].[FactBenefits] fb ON fb.BenefitsID = fbh.BenefitsID
		INNER JOIN 
		(SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value
		 FROM [int].[FactGL] gl 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID
		 WHERE gl.FiscalYearID = @CurrentFiscalYearID AND gl.TimeclassID = 2 AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0
		 GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON fb.DepartmentID = pv.DepartmentID
			AND fb.AccountID = pv.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
	WHERE
		fb.EntityGroupConfigID = @EntityGroupConfigID
		AND fb.UnitTypeID = 34	
 
 
END
GO


---------------------------------------------

-- fp.procSampleBenefitsHistoricalFTEs
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2022-09-08	BW		JAZZ-41678 	Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
*************************************************************/
CREATE   PROCEDURE fp.procSampleBenefitsHistoricalFTEs
 	@EntityGroupConfigID INT,
	@AccountID INT,
	@FinancialReportingID INT,
	@CurrentYearID INT,
	@MonthsLoaded INT,
	@PayrollFilterSql NVARCHAR(MAX),
	@PayrollFilterTempTableSQL VARCHAR(MAX)
 WITH RECOMPILE
 AS
 BEGIN
	
	DECLARE @PreviousYear INT
	DECLARE @DriverUnitTypeID INT
	DECLARE @SourceUnitTypeID INT
	
	SET @PreviousYear = @CurrentYearID - 1
	SET @SourceUnitTypeID = 51 -- hours
	SET @DriverUnitTypeID = 144 -- ftes
	
	IF object_id('tempdb..#basisIDs') IS NOT NULL 
	BEGIN
		DROP TABLE #basisIDs
	END
	IF object_id('tempdb..#StaffingFtes') IS NOT NULL 
	BEGIN
		DROP TABLE #StaffingFtes
	END
	
 	CREATE TABLE #basisIDs (BenefitsID INT);
 	CREATE TABLE #StaffingFtes (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, UnitTypeID INT, 
								Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), 
								Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), 
								Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8))
  	EXEC [dbo].[procSysDropTempTable] '#jcpcgFilterTable' 	
	CREATE TABLE #jcpcgFilterTable (JobCodeID INT, JobCodeGroupID INT, PayCodeGroupID INT, ProductiveClassID INT )

	EXEC('		' + @PayrollFilterTempTableSQL + '		')
 
		-- PriorYearActual
		EXEC('
		INSERT INTO #StaffingFtes
	    SELECT
			d.EntityID,
		    pr.DepartmentID,
		    ' + @AccountID + ' as AccountID,
		    ' + @FinancialReportingID + ' as FinancialReportingID,
		    ' + @DriverUnitTypeID + ' as UnitTypeID,
			SUM(pr.Month01) / MAX(wh.Month01) AS Value01,
			SUM(pr.Month02) / MAX(wh.Month02) AS Value02,
			SUM(pr.Month03) / MAX(wh.Month03) AS Value03,
			SUM(pr.Month04) / MAX(wh.Month04) AS Value04,
			SUM(pr.Month05) / MAX(wh.Month05) AS Value05,
			SUM(pr.Month06) / MAX(wh.Month06) AS Value06,
			SUM(pr.Month07) / MAX(wh.Month07) AS Value07,
			SUM(pr.Month08) / MAX(wh.Month08) AS Value08,
			SUM(pr.Month09) / MAX(wh.Month09) AS Value09,
			SUM(pr.Month10) / MAX(wh.Month10) AS Value10,
			SUM(pr.Month11) / MAX(wh.Month11) AS Value11,
			SUM(pr.Month12) / MAX(wh.Month12) AS Value12
	    FROM [int].[viewFactStaffingValuesPivoted] pr        
			INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
		    INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID
	       LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pc.PayCodeGroupID = exc.PayCodeGroupID  
		    INNER JOIN [client].[FactWorkingHoursPerMonth] wh 
				ON wh.FiscalYearID = ' + @PreviousYear + ' 
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
		WHERE
		    pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours		
			AND pr.FiscalYearID = ' + @PreviousYear + ' 
			AND pr.TimeClassID = 1
			AND exc.PayCodeGroupID IS NULL
			AND pc.IsHoursIgnored = 0
		    AND ' + @PayrollFilterSql + '
	    GROUP BY
		    pr.DepartmentID,
	        d.EntityID
			
		-- Update Original Value
		UPDATE hist
		SET 
			PriorYearActualValue01 = Value01, PriorYearActualValue02 = Value02, PriorYearActualValue03 = Value03, PriorYearActualValue04 = Value04,
			PriorYearActualValue05 = Value05, PriorYearActualValue06 = Value06, PriorYearActualValue07 = Value07, PriorYearActualValue08 = Value08,
			PriorYearActualValue09 = Value09, PriorYearActualValue10 = Value10, PriorYearActualValue11 = Value11, PriorYearActualValue12 = Value12
		OUTPUT INSERTED.BenefitsID
		INTO #basisIDs(BenefitsID)
		FROM [fp].[FactBenefitsHistory] hist
			INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID
			INNER JOIN #StaffingFtes staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + '
		');
	
	TRUNCATE TABLE #StaffingFtes
	
	-- ActualYTD
		EXEC('
		INSERT INTO #StaffingFtes
	    SELECT
			d.EntityID,
		    pr.DepartmentID,
		    ' + @AccountID + ' as AccountID,
		    ' + @FinancialReportingID + ' as FinancialReportingID,
		    ' + @DriverUnitTypeID + ' as UnitTypeID,
			SUM(pr.Month01) / MAX(wh.Month01) AS Value01,
			SUM(pr.Month02) / MAX(wh.Month02) AS Value02,
			SUM(pr.Month03) / MAX(wh.Month03) AS Value03,
			SUM(pr.Month04) / MAX(wh.Month04) AS Value04,
			SUM(pr.Month05) / MAX(wh.Month05) AS Value05,
			SUM(pr.Month06) / MAX(wh.Month06) AS Value06,
			SUM(pr.Month07) / MAX(wh.Month07) AS Value07,
			SUM(pr.Month08) / MAX(wh.Month08) AS Value08,
			SUM(pr.Month09) / MAX(wh.Month09) AS Value09,
			SUM(pr.Month10) / MAX(wh.Month10) AS Value10,
			SUM(pr.Month11) / MAX(wh.Month11) AS Value11,
			SUM(pr.Month12) / MAX(wh.Month12) AS Value12
	    FROM [int].[viewFactStaffingYTDValuesPivoted] (' + @MonthsLoaded + ') pr
		    INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
		    INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID
	       LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pc.PayCodeGroupID = exc.PayCodeGroupID  
		    INNER JOIN [client].[FactWorkingHoursPerMonth] wh 
				ON wh.FiscalYearID = ' + @CurrentYearID + ' 
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
		WHERE
		    pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours		
			AND pr.FiscalYearID = ' + @CurrentYearID + ' 
			AND pr.TimeClassID = 1
			AND exc.PayCodeGroupID IS NULL
			AND pc.IsHoursIgnored = 0
		    AND ' + @PayrollFilterSql + '
	    GROUP BY
		    pr.DepartmentID,
	        d.EntityID
			
		-- Update Original Value
		UPDATE hist
		SET 
			ActualYTDValue01 = Value01, ActualYTDValue02 = Value02, ActualYTDValue03 = Value03, ActualYTDValue04 = Value04,
			ActualYTDValue05 = Value05, ActualYTDValue06 = Value06, ActualYTDValue07 = Value07, ActualYTDValue08 = Value08,
			ActualYTDValue09 = Value09, ActualYTDValue10 = Value10, ActualYTDValue11 = Value11, ActualYTDValue12 = Value12
		OUTPUT INSERTED.BenefitsID
		INTO #basisIDs(BenefitsID)
		FROM [fp].[FactBenefitsHistory] hist
			INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID
			INNER JOIN #StaffingFtes staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + '
		');

	TRUNCATE TABLE #StaffingFtes

	-- CurrentYearBudget
		EXEC('
		INSERT INTO #StaffingFtes
	    SELECT
			d.EntityID,
		    pr.DepartmentID,
		    ' + @AccountID + ' as AccountID,
		    ' + @FinancialReportingID + ' as FinancialReportingID,
		    ' + @DriverUnitTypeID + ' as UnitTypeID,
			SUM(pr.Month01) / MAX(wh.Month01) AS Value01,
			SUM(pr.Month02) / MAX(wh.Month02) AS Value02,
			SUM(pr.Month03) / MAX(wh.Month03) AS Value03,
			SUM(pr.Month04) / MAX(wh.Month04) AS Value04,
			SUM(pr.Month05) / MAX(wh.Month05) AS Value05,
			SUM(pr.Month06) / MAX(wh.Month06) AS Value06,
			SUM(pr.Month07) / MAX(wh.Month07) AS Value07,
			SUM(pr.Month08) / MAX(wh.Month08) AS Value08,
			SUM(pr.Month09) / MAX(wh.Month09) AS Value09,
			SUM(pr.Month10) / MAX(wh.Month10) AS Value10,
			SUM(pr.Month11) / MAX(wh.Month11) AS Value11,
			SUM(pr.Month12) / MAX(wh.Month12) AS Value12
	    FROM [int].[viewFactStaffingValuesPivoted] pr
		    INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
		    INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID
	       LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pc.PayCodeGroupID = exc.PayCodeGroupID  
		    INNER JOIN [client].[FactWorkingHoursPerMonth] wh 
				ON wh.FiscalYearID = ' + @CurrentYearID + ' 
				AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END)
		WHERE
		    pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours		
			AND pr.FiscalYearID = ' + @CurrentYearID + ' 
			AND pr.TimeClassID = 2
			AND exc.PayCodeGroupID IS NULL
			AND pc.IsHoursIgnored = 0
		    AND ' + @PayrollFilterSql + '
	    GROUP BY
		    pr.DepartmentID,
	        d.EntityID
			
		-- Update Original Value
		UPDATE hist
		SET 
			CurrentYearBudget01 = Value01, CurrentYearBudget02 = Value02, CurrentYearBudget03 = Value03, CurrentYearBudget04 = Value04,
			CurrentYearBudget05 = Value05, CurrentYearBudget06 = Value06, CurrentYearBudget07 = Value07, CurrentYearBudget08 = Value08,
			CurrentYearBudget09 = Value09, CurrentYearBudget10 = Value10, CurrentYearBudget11 = Value11, CurrentYearBudget12 = Value12
		OUTPUT INSERTED.BenefitsID
		INTO #basisIDs(BenefitsID)
		FROM [fp].[FactBenefitsHistory] hist
			INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID
			INNER JOIN #StaffingFtes staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + '
		');
	
 END
GO


---------------------------------------------

-- fp.procSampleBenefitsHistoricalSalaries
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2022-09-07	BW		JAZZ-41678 	Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
*************************************************************/
CREATE   PROCEDURE fp.procSampleBenefitsHistoricalSalaries
 	@EntityGroupConfigID INT,
	@AccountID INT,
	@FinancialReportingID INT,
	@CurrentYearID INT,
	@MonthsLoaded INT,
	@PayrollFilterSql NVARCHAR(MAX),
	@PayrollFilterTempTableSQL VARCHAR(MAX)
 AS
 BEGIN
	
	DECLARE @PreviousYear INT
	DECLARE @DriverUnitTypeID INT
	DECLARE @SourceUnitTypeID INT
	
	SET @PreviousYear = @CurrentYearID - 1
	SET @SourceUnitTypeID = 34 -- dollars
	SET @DriverUnitTypeID = 169 -- salaries
	
	
	IF object_id('tempdb..#basisIDs') IS NOT NULL 
	BEGIN
		DROP TABLE #basisIDs
	END
	IF object_id('tempdb..#StaffingSalaries') IS NOT NULL 
	BEGIN
		DROP TABLE #StaffingSalaries
	END
	
 	CREATE TABLE #basisIDs (BenefitsID INT);
 	CREATE TABLE #StaffingSalaries (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, UnitTypeID INT, 
								Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), 
								Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), 
								Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8))

 	EXEC [dbo].[procSysDropTempTable] '#jcpcgFilterTable' 	
	CREATE TABLE #jcpcgFilterTable (JobCodeID INT, JobCodeGroupID INT, PayCodeGroupID INT, ProductiveClassID INT )

	EXEC('		' + @PayrollFilterTempTableSQL + '		')

		-- PriorYearActual
		EXEC('
		INSERT INTO #StaffingSalaries
	    SELECT
			d.EntityID,
		    pr.DepartmentID,
		    ' + @AccountID + ' as AccountID,
		    ' + @FinancialReportingID + ' as FinancialReportingID,
		    ' + @DriverUnitTypeID + ' as UnitTypeID,
			SUM(pr.Month01) AS Value01,
			SUM(pr.Month02) AS Value02,
			SUM(pr.Month03) AS Value03,
			SUM(pr.Month04) AS Value04,
			SUM(pr.Month05) AS Value05,
			SUM(pr.Month06) AS Value06,
			SUM(pr.Month07) AS Value07,
			SUM(pr.Month08) AS Value08,
			SUM(pr.Month09) AS Value09,
			SUM(pr.Month10) AS Value10,
			SUM(pr.Month11) AS Value11,
			SUM(pr.Month12) AS Value12
	    FROM [int].[viewFactStaffingValuesPivoted] pr
		    INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
		    INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID
		WHERE
		    pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours		
			AND pr.FiscalYearID = ' + @PreviousYear + ' 
			AND pr.TimeClassID = 1
		    AND ' + @PayrollFilterSql + '
	    GROUP BY
		    pr.DepartmentID,
	        d.EntityID
			
		-- Update Original Value
		UPDATE hist
		SET 
			PriorYearActualValue01 = Value01, PriorYearActualValue02 = Value02, PriorYearActualValue03 = Value03, PriorYearActualValue04 = Value04,
			PriorYearActualValue05 = Value05, PriorYearActualValue06 = Value06, PriorYearActualValue07 = Value07, PriorYearActualValue08 = Value08,
			PriorYearActualValue09 = Value09, PriorYearActualValue10 = Value10, PriorYearActualValue11 = Value11, PriorYearActualValue12 = Value12
		OUTPUT INSERTED.BenefitsID
		INTO #basisIDs(BenefitsID)
		FROM [fp].[FactBenefitsHistory] hist
			INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID
			INNER JOIN #StaffingSalaries staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + '
		');
	
	TRUNCATE TABLE #StaffingSalaries
	
	-- ActualYTD
		EXEC('
		INSERT INTO #StaffingSalaries
	    SELECT
			d.EntityID,
		    pr.DepartmentID,
		    ' + @AccountID + ' as AccountID,
		    ' + @FinancialReportingID + ' as FinancialReportingID,
		    ' + @DriverUnitTypeID + ' as UnitTypeID,
			SUM(pr.Month01) AS Value01,
			SUM(pr.Month02) AS Value02,
			SUM(pr.Month03) AS Value03,
			SUM(pr.Month04) AS Value04,
			SUM(pr.Month05) AS Value05,
			SUM(pr.Month06) AS Value06,
			SUM(pr.Month07) AS Value07,
			SUM(pr.Month08) AS Value08,
			SUM(pr.Month09) AS Value09,
			SUM(pr.Month10) AS Value10,
			SUM(pr.Month11) AS Value11,
			SUM(pr.Month12) AS Value12
	    FROM [int].[viewFactStaffingYTDValuesPivoted] (' + @MonthsLoaded + ') pr
		    INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
		    INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID
		WHERE
		    pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours		
			AND pr.FiscalYearID = ' + @CurrentYearID + ' 
			AND pr.TimeClassID = 1
		    AND ' + @PayrollFilterSql + '
	    GROUP BY
		    pr.DepartmentID,
	        d.EntityID
			
		-- Update Original Value
		UPDATE hist
		SET 
			ActualYTDValue01 = Value01, ActualYTDValue02 = Value02, ActualYTDValue03 = Value03, ActualYTDValue04 = Value04,
			ActualYTDValue05 = Value05, ActualYTDValue06 = Value06, ActualYTDValue07 = Value07, ActualYTDValue08 = Value08,
			ActualYTDValue09 = Value09, ActualYTDValue10 = Value10, ActualYTDValue11 = Value11, ActualYTDValue12 = Value12
		OUTPUT INSERTED.BenefitsID
		INTO #basisIDs(BenefitsID)
		FROM [fp].[FactBenefitsHistory] hist
			INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID
			INNER JOIN #StaffingSalaries staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + '
		');

	TRUNCATE TABLE #StaffingSalaries

	-- CurrentYearBudget
		EXEC('
		INSERT INTO #StaffingSalaries
	    SELECT
			d.EntityID,
		    pr.DepartmentID,
		    ' + @AccountID + ' as AccountID,
		    ' + @FinancialReportingID + ' as FinancialReportingID,
		    ' + @DriverUnitTypeID + ' as UnitTypeID,
			SUM(pr.Month01) AS Value01,
			SUM(pr.Month02) AS Value02,
			SUM(pr.Month03) AS Value03,
			SUM(pr.Month04) AS Value04,
			SUM(pr.Month05) AS Value05,
			SUM(pr.Month06) AS Value06,
			SUM(pr.Month07) AS Value07,
			SUM(pr.Month08) AS Value08,
			SUM(pr.Month09) AS Value09,
			SUM(pr.Month10) AS Value10,
			SUM(pr.Month11) AS Value11,
			SUM(pr.Month12) AS Value12
	    FROM [int].[viewFactStaffingValuesPivoted] pr
		    INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID
		    INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID
		WHERE
		    pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours		
			AND pr.FiscalYearID = ' + @CurrentYearID + ' 
			AND pr.TimeClassID = 2
		    AND ' + @PayrollFilterSql + '
	    GROUP BY
		    pr.DepartmentID,
	        d.EntityID
			
		-- Update Original Value
		UPDATE hist
		SET 
			CurrentYearBudget01 = Value01, CurrentYearBudget02 = Value02, CurrentYearBudget03 = Value03, CurrentYearBudget04 = Value04,
			CurrentYearBudget05 = Value05, CurrentYearBudget06 = Value06, CurrentYearBudget07 = Value07, CurrentYearBudget08 = Value08,
			CurrentYearBudget09 = Value09, CurrentYearBudget10 = Value10, CurrentYearBudget11 = Value11, CurrentYearBudget12 = Value12
		OUTPUT INSERTED.BenefitsID
		INTO #basisIDs(BenefitsID)
		FROM [fp].[FactBenefitsHistory] hist
			INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID
			INNER JOIN #StaffingSalaries staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + '
		');
	
 END
GO


---------------------------------------------

-- fp.procSampleBenefitsOriginalBudgetDollars
CREATE PROCEDURE [fp].[procSampleBenefitsOriginalBudgetDollars]
	@BudgetConfigID int,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN

	DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END)

	UPDATE fb SET
		SampledBudget01 = ISNULL(Month01, 0),
		SampledBudget02 = ISNULL(Month02, 0),
		SampledBudget03 = ISNULL(Month03, 0),
		SampledBudget04 = ISNULL(Month04, 0),
		SampledBudget05 = ISNULL(Month05, 0),
		SampledBudget06 = ISNULL(Month06, 0),
		SampledBudget07 = ISNULL(Month07, 0),
		SampledBudget08 = ISNULL(Month08, 0),
		SampledBudget09 = ISNULL(Month09, 0),
		SampledBudget10 = ISNULL(Month10, 0),
		SampledBudget11 = ISNULL(Month11, 0),
		SampledBudget12 = ISNULL(Month12, 0)
	FROM [fp].[FactBenefits] fb INNER JOIN
		(SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value
		 FROM [int].[FactGL] gl 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID		  
		 WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID 
			  AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 
			  AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
		 GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fb.DepartmentID = pv.DepartmentID
			AND fb.AccountID = pv.AccountID
	WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 
			  
	
-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data
	IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) 
	BEGIN
		-- per stackoverflow (per MY)
	    DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
        DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
        DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded)
				
		UPDATE
			fb
		SET
			SampledBudget02 = CASE WHEN @MonthsLoaded >= 2  THEN SampledBudget02 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget03 = CASE WHEN @MonthsLoaded >= 3  THEN SampledBudget03 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget04 = CASE WHEN @MonthsLoaded >= 4  THEN SampledBudget04 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget05 = CASE WHEN @MonthsLoaded >= 5  THEN SampledBudget05 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget06 = CASE WHEN @MonthsLoaded >= 6  THEN SampledBudget06 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget07 = CASE WHEN @MonthsLoaded >= 7  THEN SampledBudget07 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget08 = CASE WHEN @MonthsLoaded >= 8  THEN SampledBudget08 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget09 = CASE WHEN @MonthsLoaded >= 9  THEN SampledBudget09 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget10 = CASE WHEN @MonthsLoaded >= 10 THEN SampledBudget10 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget11 = CASE WHEN @MonthsLoaded >= 11 THEN SampledBudget11 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget12 = CASE WHEN @MonthsLoaded >= 12 THEN SampledBudget12 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END
		FROM [fp].[FactBenefits] fb
		WHERE fb.EntityGroupConfigID = @EntityGroupConfigID	AND fb.UnitTypeID = 34		
      

	END
	
	-- update the initial values to be equal to the sampled values
	UPDATE
		fb
	SET
		InitialBudget01 = SampledBudgetTotal / 12,
		InitialBudget02 = SampledBudgetTotal / 12,
		InitialBudget03 = SampledBudgetTotal / 12,
		InitialBudget04 = SampledBudgetTotal / 12,
		InitialBudget05 = SampledBudgetTotal / 12,
		InitialBudget06 = SampledBudgetTotal / 12,
		InitialBudget07 = SampledBudgetTotal / 12,
		InitialBudget08 = SampledBudgetTotal / 12,
		InitialBudget09 = SampledBudgetTotal / 12,
		InitialBudget10 = SampledBudgetTotal / 12,
		InitialBudget11 = SampledBudgetTotal / 12,
		InitialBudget12 = SampledBudgetTotal - (SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 +
											SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12)
	FROM
		[fp].[FactBenefits] fb
	WHERE
		fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34
END
GO


---------------------------------------------

-- fp.procSampleBenefitsOriginalBudgetDollars_WithNewAnnualization
CREATE   PROCEDURE [fp].[procSampleBenefitsOriginalBudgetDollars_WithNewAnnualization]
	@BudgetConfigID int,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2024-07-24   BK        JAZZ-74600  Create new proc that is used when BudgetConfig FF is on
**************************************************************/

	DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END)

	UPDATE fb SET
		SampledBudget01 = ISNULL(Month01, 0),
		SampledBudget02 = ISNULL(Month02, 0),
		SampledBudget03 = ISNULL(Month03, 0),
		SampledBudget04 = ISNULL(Month04, 0),
		SampledBudget05 = ISNULL(Month05, 0),
		SampledBudget06 = ISNULL(Month06, 0),
		SampledBudget07 = ISNULL(Month07, 0),
		SampledBudget08 = ISNULL(Month08, 0),
		SampledBudget09 = ISNULL(Month09, 0),
		SampledBudget10 = ISNULL(Month10, 0),
		SampledBudget11 = ISNULL(Month11, 0),
		SampledBudget12 = ISNULL(Month12, 0)
	FROM [fp].[FactBenefits] fb INNER JOIN
		(SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value
		 FROM [int].[FactGL] gl 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID		  
		 WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID 
			  AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 
			  AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
		 GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fb.DepartmentID = pv.DepartmentID
			AND fb.AccountID = pv.AccountID
	WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 
			  
	
-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data
	IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) 
	BEGIN
		-- per stackoverflow (per MY)
	    DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)

		DECLARE @IsBudgetLeapYear BIT = (CASE WHEN ((@CurrentFiscalYearID + 1) % 4 = 0 AND (@CurrentFiscalYearID  + 1) % 100 <> 0) OR (@CurrentFiscalYearID + 1) % 400 = 0 THEN 1 ELSE 0 END)  
		DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12)

		DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
		DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded)
                				
		UPDATE
			fb
		SET
			SampledBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12
		FROM [fp].[FactBenefits] fb
		WHERE fb.EntityGroupConfigID = @EntityGroupConfigID	AND fb.UnitTypeID = 34		
      

	END
	ELSE BEGIN
		-- update the initial values to be equal to the sampled values - only if not annualized, since we are doing that above in the same sql stmt
		UPDATE
			fb
		SET
			InitialBudget01 = SampledBudgetTotal / 12,
			InitialBudget02 = SampledBudgetTotal / 12,
			InitialBudget03 = SampledBudgetTotal / 12,
			InitialBudget04 = SampledBudgetTotal / 12,
			InitialBudget05 = SampledBudgetTotal / 12,
			InitialBudget06 = SampledBudgetTotal / 12,
			InitialBudget07 = SampledBudgetTotal / 12,
			InitialBudget08 = SampledBudgetTotal / 12,
			InitialBudget09 = SampledBudgetTotal / 12,
			InitialBudget10 = SampledBudgetTotal / 12,
			InitialBudget11 = SampledBudgetTotal / 12,
			InitialBudget12 = SampledBudgetTotal - (SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 +
												SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12)
		FROM
			[fp].[FactBenefits] fb
		WHERE
			fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34

	END

END
GO


---------------------------------------------

-- fp.procSampleBenefitsOriginalProjectionDollars
CREATE PROCEDURE [fp].[procSampleBenefitsOriginalProjectionDollars]
	@BudgetConfigID int,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN

	UPDATE fb SET
		SampledProjection01 = ISNULL(Month01, 0),
		SampledProjection02 = ISNULL(Month02, 0),
		SampledProjection03 = ISNULL(Month03, 0),
		SampledProjection04 = ISNULL(Month04, 0),
		SampledProjection05 = ISNULL(Month05, 0),
		SampledProjection06 = ISNULL(Month06, 0),
		SampledProjection07 = ISNULL(Month07, 0),
		SampledProjection08 = ISNULL(Month08, 0),
		SampledProjection09 = ISNULL(Month09, 0),
		SampledProjection10 = ISNULL(Month10, 0),
		SampledProjection11 = ISNULL(Month11, 0),
		SampledProjection12 = ISNULL(Month12, 0)
	FROM [fp].[FactBenefits] fb INNER JOIN
		(SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value
		 FROM [int].[FactGL] gl 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID		  
		 WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 
		 AND fm.SortOrder <= @MonthsLoaded
		 GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fb.DepartmentID = pv.DepartmentID
			AND fb.AccountID = pv.AccountID
	WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 

    

	-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	-- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize
	UPDATE
		fb
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END,
		SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END
	FROM
		[fp].[FactBenefits] fb
	WHERE
		fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34

	  -- Get total for months loaded	
    CREATE TABLE #Totals (BenefitsID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8));
		    INSERT INTO #Totals (BenefitsID, SampledProjectionTotal)
		    SELECT BenefitsID, 
			   CASE WHEN @MonthsLoaded = 11 THEN ben.SampledProjection12  
					 WHEN @MonthsLoaded = 10 THEN ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 9 THEN ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 8 THEN ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 7 THEN ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 6 THEN ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 5 THEN ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 4 THEN ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 3 THEN ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10  + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 2 THEN ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12
					 WHEN @MonthsLoaded = 1 THEN ben.SampledProjection02 + ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12  
				 	 ELSE 0
				END
		      FROM [fp].[FactBenefits] ben
		    WHERE ben.EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID = 34
		     
		      
		  UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded)
		   FROM #Totals a
		   
		UPDATE
			ben
		SET
			InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN ben.SampledProjection01 ELSE t.NewValue END,
			InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN ben.SampledProjection02 ELSE t.NewValue END,
			InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN ben.SampledProjection03 ELSE t.NewValue END,
			InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN ben.SampledProjection04 ELSE t.NewValue END,
			InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN ben.SampledProjection05 ELSE t.NewValue END,
			InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN ben.SampledProjection06 ELSE t.NewValue END,
			InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN ben.SampledProjection07 ELSE t.NewValue END,
			InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN ben.SampledProjection08 ELSE t.NewValue END,
			InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN ben.SampledProjection09 ELSE t.NewValue END,
			InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN ben.SampledProjection10 ELSE t.NewValue END,
			InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN ben.SampledProjection11 ELSE t.NewValue END,
			InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN ben.SampledProjection12 ELSE t.NewValue END
		FROM [fp].[FactBenefits] ben INNER JOIN #Totals t on ben.BenefitsID = t.BenefitsID
		WHERE ben.EntityGroupConfigID  = @EntityGroupConfigID 

	
END
GO


---------------------------------------------

-- fp.procSampleBenefitsOriginalProjectionDollars_WithNewAnnualization
CREATE   PROCEDURE [fp].[procSampleBenefitsOriginalProjectionDollars_WithNewAnnualization]
	@BudgetConfigID int,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author    WI          Description
** 1    2024-07-24   BK        JAZZ-74600  Create new proc that is used when BudgetConfig FF is on
** 2    2024-08-07   BK        JAZZ-75213   Add check if using annualization
**************************************************************/

	UPDATE fb SET
		SampledProjection01 = ISNULL(Month01, 0),
		SampledProjection02 = ISNULL(Month02, 0),
		SampledProjection03 = ISNULL(Month03, 0),
		SampledProjection04 = ISNULL(Month04, 0),
		SampledProjection05 = ISNULL(Month05, 0),
		SampledProjection06 = ISNULL(Month06, 0),
		SampledProjection07 = ISNULL(Month07, 0),
		SampledProjection08 = ISNULL(Month08, 0),
		SampledProjection09 = ISNULL(Month09, 0),
		SampledProjection10 = ISNULL(Month10, 0),
		SampledProjection11 = ISNULL(Month11, 0),
		SampledProjection12 = ISNULL(Month12, 0)
	FROM [fp].[FactBenefits] fb INNER JOIN
		(SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value
		 FROM [int].[FactGL] gl 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID		  
		 WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 
		 AND fm.SortOrder <= @MonthsLoaded
		 GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fb.DepartmentID = pv.DepartmentID
			AND fb.AccountID = pv.AccountID
	WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 

    DECLARE @IsLeapYear BIT = (CASE WHEN ( @CurrentFiscalYearID  % 4 = 0 AND  @CurrentFiscalYearID  % 100 <> 0) OR  @CurrentFiscalYearID  % 400 = 0 THEN 1 ELSE 0 END)
    DECLARE @DaysInYear decimal = (SELECT (CASE WHEN @IsLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12)
    DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
    DECLARE @MonthsNotLoaded decimal = 12 - @MonthsLoaded
    DECLARE @DaysRemaining decimal = @DaysInYear - @DaysInMonthsLoaded    
    DECLARE @TimeClassID TINYINT  /* we are passing in Actual for the TimeClass regardless so we need to retrieve the real one here */
    SELECT @TimeClassID = BenefitsTimeClassID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID

IF @CurrentFiscalYearID = @SourceFiscalYearID AND @TimeClassID = 1 BEGIN
	-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	-- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize
	UPDATE
		fb
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection11 END,
		SampledProjection12 =  ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded 
	FROM
		[fp].[FactBenefits] fb
	WHERE
		fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34
END ELSE BEGIN

-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	-- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize
	UPDATE
		fb
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END,
		SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END
	FROM
		[fp].[FactBenefits] fb
	WHERE
		fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34
END
	
		   
	UPDATE
		ben
	SET
			InitialProjection01 = ben.SampledProjection01,
			InitialProjection02 = ben.SampledProjection02,
			InitialProjection03 = ben.SampledProjection03,
			InitialProjection04 = ben.SampledProjection04,
			InitialProjection05 = ben.SampledProjection05,
			InitialProjection06 = ben.SampledProjection06,
			InitialProjection07 = ben.SampledProjection07,
			InitialProjection08 = ben.SampledProjection08,
			InitialProjection09 = ben.SampledProjection09,
			InitialProjection10 = ben.SampledProjection10,
			InitialProjection11 = ben.SampledProjection11,
			InitialProjection12 = ben.SampledProjection12
	FROM [fp].[FactBenefits] ben 
	WHERE ben.EntityGroupConfigID  = @EntityGroupConfigID 

	
END
GO


---------------------------------------------

-- fp.procSampleBenefitsProjectionData
CREATE PROCEDURE [fp].[procSampleBenefitsProjectionData]
@EntityGroupConfigID int
AS
BEGIN

	-- update the budget data
	INSERT INTO [fp].[FactBenefitsProjection]([BenefitsID], [BudgetPhaseID], 
					[AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], 
					[FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12])
	SELECT [BenefitsID], [BudgetPhaseID],
		   [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], 
		   [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12]
		FROM [fp].[FactBenefits] fs
		 CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID)
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0
	
END
GO


---------------------------------------------

-- fp.procSampleBenefitsSalaryDriverValues
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2019-02-14	IP		B-22020		Added AccountID as CSV
** 2 	2019-03-26  IP      B-22466	Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 3 	2019-06-02  MY      TK-74658	Removing remaining table variable functions
** 4 	2020-03-31  LR      B-24089 	Removed check for null within join conditions
** 5	2022-08-31	BW		JAZZ-41678 	Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
** 6	2023-10-31	BK		JAZZ-62801 	Update for staffing restructure
*************************************************************/
CREATE   PROCEDURE [fp].[procSampleBenefitsSalaryDriverValues]
 	@EntityGroupConfigID INT,
	@AccountID VARCHAR(MAX),
	@FinancialReportingID INT,
	@TimeClassID INT,
	@PayrollFilterSql NVARCHAR(MAX),
	@PayrollFilterTempTableSQL VARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 WITH RECOMPILE
 AS
 BEGIN
 
	CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int)
	INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID)
	SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID	
	END	
 
	DECLARE @DynamicSql NVARCHAR(MAX)
	IF object_id('tempdb..#basisIDs') IS NOT NULL 
	BEGIN
		DROP TABLE #basisIDs
	END
	IF object_id('tempdb..#StaffingSalaries') IS NOT NULL 
	BEGIN
		DROP TABLE #StaffingSalaries
	END
	
 	CREATE TABLE #StaffingSalaries (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, BudgetPhaseID INT,
								Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), 
								Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), 
								Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8))
 
 	IF (@TimeClassID = 2)
	BEGIN
		
		set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
				
		INSERT INTO #StaffingSalaries
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			CAST(2 as TINYINT) BudgetPhaseID,
			SUM(pr.TargetAdjustedDollars01) AS Value01,
			SUM(pr.TargetAdjustedDollars02) AS Value02,
			SUM(pr.TargetAdjustedDollars03) AS Value03,
			SUM(pr.TargetAdjustedDollars04) AS Value04,
			SUM(pr.TargetAdjustedDollars05) AS Value05,
			SUM(pr.TargetAdjustedDollars06) AS Value06,
			SUM(pr.TargetAdjustedDollars07) AS Value07,
			SUM(pr.TargetAdjustedDollars08) AS Value08,
			SUM(pr.TargetAdjustedDollars09) AS Value09,
			SUM(pr.TargetAdjustedDollars10) AS Value10,
			SUM(pr.TargetAdjustedDollars11) AS Value11,
			SUM(pr.TargetAdjustedDollars12) AS Value12
		FROM [fp].[Staffing] pr
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID)
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND (2 = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID

		INSERT INTO #StaffingSalaries
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			CAST(3 as TINYINT) BudgetPhaseID,
			SUM(pr.BudgetAdjustedDollars01) AS Value01,
			SUM(pr.BudgetAdjustedDollars02) AS Value02,
			SUM(pr.BudgetAdjustedDollars03) AS Value03,
			SUM(pr.BudgetAdjustedDollars04) AS Value04,
			SUM(pr.BudgetAdjustedDollars05) AS Value05,
			SUM(pr.BudgetAdjustedDollars06) AS Value06,
			SUM(pr.BudgetAdjustedDollars07) AS Value07,
			SUM(pr.BudgetAdjustedDollars08) AS Value08,
			SUM(pr.BudgetAdjustedDollars09) AS Value09,
			SUM(pr.BudgetAdjustedDollars10) AS Value10,
			SUM(pr.BudgetAdjustedDollars11) AS Value11,
			SUM(pr.BudgetAdjustedDollars12) AS Value12
		FROM [fp].[Staffing] pr
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID)
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND (3 = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL)
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID

				
		-- Update Value
		UPDATE budg
		SET 
			AdjustedValue01 = Value01, AdjustedValue02 = Value02, AdjustedValue03 = Value03, AdjustedValue04 = Value04,
			AdjustedValue05 = Value05, AdjustedValue06 = Value06, AdjustedValue07 = Value07, AdjustedValue08 = Value08,
			AdjustedValue09 = Value09, AdjustedValue10 = Value10, AdjustedValue11 = Value11, AdjustedValue12 = Value12,
			FlexedValue01 = Value01, FlexedValue02 = Value02, FlexedValue03 = Value03, FlexedValue04 = Value04,
			FlexedValue05 = Value05, FlexedValue06 = Value06, FlexedValue07 = Value07, FlexedValue08 = Value08,
			FlexedValue09 = Value09, FlexedValue10 = Value10, FlexedValue11 = Value11, FlexedValue12 = Value12
		FROM [fp].[FactBenefits] benefits
			INNER JOIN [fp].[FactBenefitsBudget] budg ON benefits.BenefitsID = budg.BenefitsID
			INNER JOIN #StaffingSalaries staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.BudgetPhaseID = budg.BudgetPhaseID
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		        AND benefits.UnitTypeID = 169
		
		';
	
	END ELSE BEGIN

		declare @i int
	
		set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		DECLARE @ML INT	
		SELECT @ML = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' 
		
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
		
		INSERT INTO #StaffingSalaries
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			CAST(3 as TINYINT) BudgetPhaseID,
			SUM(pr.ProjectionAdjustedDollars01) AS Value01,
			SUM(pr.ProjectionAdjustedDollars02) AS Value02,
			SUM(pr.ProjectionAdjustedDollars03) AS Value03,
			SUM(pr.ProjectionAdjustedDollars04) AS Value04,
			SUM(pr.ProjectionAdjustedDollars05) AS Value05,
			SUM(pr.ProjectionAdjustedDollars06) AS Value06,
			SUM(pr.ProjectionAdjustedDollars07) AS Value07,
			SUM(pr.ProjectionAdjustedDollars08) AS Value08,
			SUM(pr.ProjectionAdjustedDollars09) AS Value09,
			SUM(pr.ProjectionAdjustedDollars10) AS Value10,
			SUM(pr.ProjectionAdjustedDollars11) AS Value11,
			SUM(pr.ProjectionAdjustedDollars12) AS Value12
		FROM [fp].[Staffing] pr
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID
				
		-- Update Value
		UPDATE proj
		SET 
			proj.AdjustedValue01 = CASE WHEN 1 <= @ML THEN InitialProjection01 ELSE Value01 END,
			proj.AdjustedValue02 = CASE WHEN 2 <= @ML THEN InitialProjection02 ELSE Value02 END,
			proj.AdjustedValue03 = CASE WHEN 3 <= @ML THEN InitialProjection03 ELSE Value03 END,
			proj.AdjustedValue04 = CASE WHEN 4 <= @ML THEN InitialProjection04 ELSE Value04 END,
			proj.AdjustedValue05 = CASE WHEN 5 <= @ML THEN InitialProjection05 ELSE Value05 END,
			proj.AdjustedValue06 = CASE WHEN 6 <= @ML THEN InitialProjection06 ELSE Value06 END,
			proj.AdjustedValue07 = CASE WHEN 7 <= @ML THEN InitialProjection07 ELSE Value07 END,
			proj.AdjustedValue08 = CASE WHEN 8 <= @ML THEN InitialProjection08 ELSE Value08 END,
			proj.AdjustedValue09 = CASE WHEN 9 <= @ML THEN InitialProjection09 ELSE Value09 END,
			proj.AdjustedValue10 = CASE WHEN 10 <= @ML THEN InitialProjection10 ELSE Value10 END,
			proj.AdjustedValue11 = CASE WHEN 11 <= @ML THEN InitialProjection11 ELSE Value11 END,
			proj.AdjustedValue12 = CASE WHEN 12 <= @ML THEN InitialProjection12 ELSE Value12 END,
			proj.FlexedValue01 = CASE WHEN 1 <= @ML THEN InitialProjection01 ELSE Value01 END,
			proj.FlexedValue02 = CASE WHEN 2 <= @ML THEN InitialProjection02 ELSE Value02 END,
			proj.FlexedValue03 = CASE WHEN 3 <= @ML THEN InitialProjection03 ELSE Value03 END,
			proj.FlexedValue04 = CASE WHEN 4 <= @ML THEN InitialProjection04 ELSE Value04 END,
			proj.FlexedValue05 = CASE WHEN 5 <= @ML THEN InitialProjection05 ELSE Value05 END,
			proj.FlexedValue06 = CASE WHEN 6 <= @ML THEN InitialProjection06 ELSE Value06 END,
			proj.FlexedValue07 = CASE WHEN 7 <= @ML THEN InitialProjection07 ELSE Value07 END,
			proj.FlexedValue08 = CASE WHEN 8 <= @ML THEN InitialProjection08 ELSE Value08 END,
			proj.FlexedValue09 = CASE WHEN 9 <= @ML THEN InitialProjection09 ELSE Value09 END,
			proj.FlexedValue10 = CASE WHEN 10 <= @ML THEN InitialProjection10 ELSE Value10 END,
			proj.FlexedValue11 = CASE WHEN 11 <= @ML THEN InitialProjection11 ELSE Value11 END,
			proj.FlexedValue12 = CASE WHEN 12 <= @ML THEN InitialProjection12 ELSE Value12 END
		FROM [fp].[FactBenefits] benefits
			INNER JOIN [fp].[FactBenefitsProjection] proj ON benefits.BenefitsID = proj.BenefitsID
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = benefits.DepartmentID /* adding this here so that the BudgetPhase will be respected - once we convert benefits to new structure, this can go away since the filter is applied on #staffingSalaries table */
			INNER JOIN #StaffingSalaries staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
			    AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) /* also remove this when converting benfits */
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' 
		        AND benefits.UnitTypeID = 169			
		
		';
		

	END

	EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY',  @SourceDimensionality = @SourceDimensionality;  

 END
GO


---------------------------------------------

-- fp.procSampleBenefitsSalaryDriverValues_InitialValue
/**************************************************************
** Change History
** CID  Date		Author	WI			Description
** 1	2019-02-14	IP		B-22020		Added AccountID as CSV
** 2 	2019-03-26  IP  	B-22466	    Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 3 	2019-06-02  MY      TK-74658	Removing remaining table variable functions
** 4 	2020-03-31  LR  	B-24089 	Removed check for null within join conditions
** 5	2022-08-31	BW		JAZZ-41678 	Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on
** 6	2023-10-31	BK		JAZZ-62801 	Update for staffing restructure
	 *************************************************************/
CREATE   PROCEDURE [fp].[procSampleBenefitsSalaryDriverValues_InitialValue]
 	@EntityGroupConfigID INT,
	@AccountID VARCHAR(MAX),
	@FinancialReportingID INT,
	@TimeClassID INT,
	@PayrollFilterSql NVARCHAR(MAX),
	@PayrollFilterTempTableSQL VARCHAR(MAX),
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
 AS
 BEGIN
  
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID = @EntityGroupConfigID	
	END	
	
 	DECLARE @DynamicSql NVARCHAR(MAX)	

	IF object_id('tempdb..#StaffingSalaries') IS NOT NULL 
	BEGIN
		DROP TABLE #StaffingSalaries
	END
	
 	CREATE TABLE #StaffingSalaries (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, UnitTypeID INT,
								Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), 
								Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), 
								Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8))
 
 	IF (@TimeClassID = 2)
	BEGIN
	
		set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
		
		INSERT INTO #StaffingSalaries
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			169 as UnitTypeID,
			SUM(pr.InitialBudgetDollars01) AS Value01,
			SUM(pr.InitialBudgetDollars02) AS Value02,
			SUM(pr.InitialBudgetDollars03) AS Value03,
			SUM(pr.InitialBudgetDollars04) AS Value04,
			SUM(pr.InitialBudgetDollars05) AS Value05,
			SUM(pr.InitialBudgetDollars06) AS Value06,
			SUM(pr.InitialBudgetDollars07) AS Value07,
			SUM(pr.InitialBudgetDollars08) AS Value08,
			SUM(pr.InitialBudgetDollars09) AS Value09,
			SUM(pr.InitialBudgetDollars10) AS Value10,
			SUM(pr.InitialBudgetDollars11) AS Value11,
			SUM(pr.InitialBudgetDollars12) AS Value12
		FROM [fp].[Staffing] pr
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID)
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID
			
				
		-- Update Original Value
		UPDATE benefits
		SET 
			InitialBudget01 = Value01, InitialBudget02 = Value02, InitialBudget03 = Value03, InitialBudget04 = Value04,
			InitialBudget05 = Value05, InitialBudget06 = Value06, InitialBudget07 = Value07, InitialBudget08 = Value08,
			InitialBudget09 = Value09, InitialBudget10 = Value10, InitialBudget11 = Value11, InitialBudget12 = Value12
		FROM [fp].[FactBenefits] benefits
			INNER JOIN #StaffingSalaries staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		
		';
	
	END ELSE BEGIN
	
		set @DynamicSql = '
		' + @PayrollFilterTempTableSQL + '
		
		DECLARE @MonthsLoaded INT	
		SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		
		CREATE TABLE #AccountIDs (AccountID int)
		INSERT INTO #AccountIDs (AccountID)
		SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','')
							
		INSERT INTO #StaffingSalaries
		SELECT
			pr.EntityID,
			pr.DepartmentID,
			AccLst.AccountID,
			' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID,
			169 as UnitTypeID,
			SUM(pr.InitialProjectionDollars01) AS Value01,
			SUM(pr.InitialProjectionDollars02) AS Value02,
			SUM(pr.InitialProjectionDollars03) AS Value03,
			SUM(pr.InitialProjectionDollars04) AS Value04,
			SUM(pr.InitialProjectionDollars05) AS Value05,
			SUM(pr.InitialProjectionDollars06) AS Value06,
			SUM(pr.InitialProjectionDollars07) AS Value07,
			SUM(pr.InitialProjectionDollars08) AS Value08,
			SUM(pr.InitialProjectionDollars09) AS Value09,
			SUM(pr.InitialProjectionDollars10) AS Value10,
			SUM(pr.InitialProjectionDollars11) AS Value11,
			SUM(pr.InitialProjectionDollars12) AS Value12
		FROM [fp].[Staffing] pr
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID)
			CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst
		WHERE
			pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
			AND ' + @PayrollFilterSql + '
		GROUP BY
			pr.DepartmentID,
			pr.EntityID,
			AccLst.AccountID

		-- Update Initial Value
		UPDATE benefits
		SET 
			InitialProjection01 = CASE WHEN 1 <=  @MonthsLoaded THEN SampledProjection01 ELSE Value01 END,
			InitialProjection02 = CASE WHEN 2 <=  @MonthsLoaded THEN SampledProjection02 ELSE Value02 END,
			InitialProjection03 = CASE WHEN 3 <=  @MonthsLoaded THEN SampledProjection03 ELSE Value03 END,
			InitialProjection04 = CASE WHEN 4 <=  @MonthsLoaded THEN SampledProjection04 ELSE Value04 END,
			InitialProjection05 = CASE WHEN 5 <=  @MonthsLoaded THEN SampledProjection05 ELSE Value05 END,
			InitialProjection06 = CASE WHEN 6 <=  @MonthsLoaded THEN SampledProjection06 ELSE Value06 END,
			InitialProjection07 = CASE WHEN 7 <=  @MonthsLoaded THEN SampledProjection07 ELSE Value07 END,
			InitialProjection08 = CASE WHEN 8 <=  @MonthsLoaded THEN SampledProjection08 ELSE Value08 END,
			InitialProjection09 = CASE WHEN 9 <=  @MonthsLoaded THEN SampledProjection09 ELSE Value09 END,
			InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE Value10 END,
			InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE Value11 END,
			InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE Value12 END
		FROM [fp].[FactBenefits] benefits
			INNER JOIN #StaffingSalaries staffing ON
				staffing.EntityID = benefits.EntityID
				AND staffing.DepartmentID = benefits.DepartmentID
				AND staffing.AccountID = benefits.AccountID
				AND staffing.FinancialReportingID = benefits.FinancialReportingID
				AND staffing.UnitTypeID = benefits.UnitTypeID
		WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + '
		
		';
	END
	print @DynamicSql
	EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY',  @SourceDimensionality = @SourceDimensionality;  
 END
GO


---------------------------------------------

-- fp.procSampleChargeDollarsToReimbursement
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2022-01-11  MY      JAZZ-31850  Initial
** 2    2022-02-15  BW      JAZZ-33266  Pulling in configuration via Plan Config > Section Setup
** 3    2022-06-15  MY      JAZZ-37901  Create Fix Change History Process for Reimbursement
** 4    2023-01-31  NT      JAZZ-48268  Make change to use the new fp.ChargeVolume (data restructure)
** 5    2023-04-04  BK      JAZZ-50751  Fix wrong column names
** 6    2024-01-11  AO      JAZZ-64530  Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE PROCEDURE [fp].[procSampleChargeDollarsToReimbursement]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	

	DECLARE @IsMedicalSurgicalUsed BIT = 0,
			@IsMsdrgUsed BIT = 0,
			@IsCptUsed BIT = 0,
			@IsUBRevCodeUsed BIT = 0;
			
	IF OBJECT_ID('tempdb..#projectionBasisIDs') IS NOT NULL DROP TABLE #projectionBasisIDs
	IF OBJECT_ID('tempdb..#budgetBasisIDs') IS NOT NULL DROP TABLE #budgetBasisIDs
	CREATE TABLE #budgetBasisIDs (ReimbursementChargesID INT);
	CREATE TABLE #projectionBasisIDs (ReimbursementChargesID INT);

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'PrimaryCPTID'

	SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'UBRevCodeID'
	  	
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE d.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
		
	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
				CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID,  
				sd.PayorID, sd.PayorGroupID, 
				CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
				CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
				CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID,
		
		-- Target
		SUM(cv.TargetDollarsAdjusted01 * sd.BudgetMixPercentage) AS TargetChargeDollars01, SUM(cv.TargetDollarsAdjusted02 * sd.BudgetMixPercentage) AS TargetChargeDollars02, SUM(cv.TargetDollarsAdjusted03 * sd.BudgetMixPercentage) AS TargetChargeDollars03, 
		SUM(cv.TargetDollarsAdjusted04 * sd.BudgetMixPercentage) AS TargetChargeDollars04, SUM(cv.TargetDollarsAdjusted05 * sd.BudgetMixPercentage) AS TargetChargeDollars05, SUM(cv.TargetDollarsAdjusted06 * sd.BudgetMixPercentage) AS TargetChargeDollars06, 
		SUM(cv.TargetDollarsAdjusted07 * sd.BudgetMixPercentage) AS TargetChargeDollars07, SUM(cv.TargetDollarsAdjusted08 * sd.BudgetMixPercentage) AS TargetChargeDollars08, SUM(cv.TargetDollarsAdjusted09 * sd.BudgetMixPercentage) AS TargetChargeDollars09, 
		SUM(cv.TargetDollarsAdjusted10 * sd.BudgetMixPercentage) AS TargetChargeDollars10, SUM(cv.TargetDollarsAdjusted11 * sd.BudgetMixPercentage) AS TargetChargeDollars11, SUM(cv.TargetDollarsAdjusted12 * sd.BudgetMixPercentage) AS TargetChargeDollars12,

		--Budget
		SUM(cv.BudgetDollarsAdjusted01 * sd.BudgetMixPercentage) AS BudgetChargeDollars01, SUM(cv.BudgetDollarsAdjusted02 * sd.BudgetMixPercentage) AS BudgetChargeDollars02, SUM(cv.BudgetDollarsAdjusted03 * sd.BudgetMixPercentage) AS BudgetChargeDollars03, 
		SUM(cv.BudgetDollarsAdjusted04 * sd.BudgetMixPercentage) AS BudgetChargeDollars04, SUM(cv.BudgetDollarsAdjusted05 * sd.BudgetMixPercentage) AS BudgetChargeDollars05, SUM(cv.BudgetDollarsAdjusted06 * sd.BudgetMixPercentage) AS BudgetChargeDollars06, 
		SUM(cv.BudgetDollarsAdjusted07 * sd.BudgetMixPercentage) AS BudgetChargeDollars07, SUM(cv.BudgetDollarsAdjusted08 * sd.BudgetMixPercentage) AS BudgetChargeDollars08, SUM(cv.BudgetDollarsAdjusted09 * sd.BudgetMixPercentage) AS BudgetChargeDollars09, 
		SUM(cv.BudgetDollarsAdjusted10 * sd.BudgetMixPercentage) AS BudgetChargeDollars10, SUM(cv.BudgetDollarsAdjusted11 * sd.BudgetMixPercentage) AS BudgetChargeDollars11, SUM(cv.BudgetDollarsAdjusted12 * sd.BudgetMixPercentage) AS BudgetChargeDollars12,

		-- Projection
		SUM(cv.ProjectionDollarsAdjusted01 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars01, SUM(cv.ProjectionDollarsAdjusted02 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars02, SUM(cv.ProjectionDollarsAdjusted03 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars03, 
		SUM(cv.ProjectionDollarsAdjusted04 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars04, SUM(cv.ProjectionDollarsAdjusted05 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars05, SUM(cv.ProjectionDollarsAdjusted06 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars06, 
		SUM(cv.ProjectionDollarsAdjusted07 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars07, SUM(cv.ProjectionDollarsAdjusted08 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars08, SUM(cv.ProjectionDollarsAdjusted09 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars09, 
		SUM(cv.ProjectionDollarsAdjusted10 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars10, SUM(cv.ProjectionDollarsAdjusted11 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars11, SUM(cv.ProjectionDollarsAdjusted12 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars12
	INTO #factReimbursementCharges
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
		INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
	        AND cv.PatientClassID = sd.PatientClassID
	        AND cv.ServiceLineID = sd.ServiceLineID
			AND cv.AgeCohortID = sd.AgeCohortID
	        AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
	        AND cv.MSDRGID = sd.MSDRGID
	        AND cv.PrimaryCPTID = sd.CPTID
	        AND cv.ServiceProviderID = sd.ProviderID
	        AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
	WHERE cv.BudgetConfigID = @BudgetConfigID
	GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, 			
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END,		
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END, 
		sd.PayorID, sd.PayorGroupID

	-- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup
	INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
		MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID,
		TargetChargeDollars01, TargetChargeDollars02, TargetChargeDollars03, TargetChargeDollars04, TargetChargeDollars05, TargetChargeDollars06,
		TargetChargeDollars07, TargetChargeDollars08, TargetChargeDollars09, TargetChargeDollars10, TargetChargeDollars11, TargetChargeDollars12, 
		BudgetChargeDollars01, BudgetChargeDollars02, BudgetChargeDollars03, BudgetChargeDollars04, BudgetChargeDollars05, BudgetChargeDollars06,
		BudgetChargeDollars07, BudgetChargeDollars08, BudgetChargeDollars09, BudgetChargeDollars10, BudgetChargeDollars11, BudgetChargeDollars12, 
		ProjectionChargeDollars01, ProjectionChargeDollars02, ProjectionChargeDollars03, ProjectionChargeDollars04, ProjectionChargeDollars05, ProjectionChargeDollars06,
		ProjectionChargeDollars07, ProjectionChargeDollars08, ProjectionChargeDollars09, ProjectionChargeDollars10, ProjectionChargeDollars11, ProjectionChargeDollars12)
	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		0 AS PayorID, 0 AS PayorGroupID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID,	
	
	-- Target
		SUM(cv.TargetDollarsAdjusted01) AS TargetChargeDollars01, SUM(cv.TargetDollarsAdjusted02) AS TargetChargeDollars02, SUM(cv.TargetDollarsAdjusted03) AS TargetChargeDollars03, 
		SUM(cv.TargetDollarsAdjusted04) AS TargetChargeDollars04, SUM(cv.TargetDollarsAdjusted05) AS TargetChargeDollars05, SUM(cv.TargetDollarsAdjusted06) AS TargetChargeDollars06, 
		SUM(cv.TargetDollarsAdjusted07) AS TargetChargeDollars07, SUM(cv.TargetDollarsAdjusted08) AS TargetChargeDollars08, SUM(cv.TargetDollarsAdjusted09) AS TargetChargeDollars09, 
		SUM(cv.TargetDollarsAdjusted10) AS TargetChargeDollars10, SUM(cv.TargetDollarsAdjusted11) AS TargetChargeDollars11, SUM(cv.TargetDollarsAdjusted12) AS TargetChargeDollars12,

	--Budget
		SUM(cv.BudgetDollarsAdjusted01) AS BudgetChargeDollars01, SUM(cv.BudgetDollarsAdjusted02) AS BudgetChargeDollars02, SUM(cv.BudgetDollarsAdjusted03) AS BudgetChargeDollars03, 
		SUM(cv.BudgetDollarsAdjusted04) AS BudgetChargeDollars04, SUM(cv.BudgetDollarsAdjusted05) AS BudgetChargeDollars05, SUM(cv.BudgetDollarsAdjusted06) AS BudgetChargeDollars06, 
		SUM(cv.BudgetDollarsAdjusted07) AS BudgetChargeDollars07, SUM(cv.BudgetDollarsAdjusted08) AS BudgetChargeDollars08, SUM(cv.BudgetDollarsAdjusted09) AS BudgetChargeDollars09, 
		SUM(cv.BudgetDollarsAdjusted10) AS BudgetChargeDollars10, SUM(cv.BudgetDollarsAdjusted11) AS BudgetChargeDollars11, SUM(cv.BudgetDollarsAdjusted12) AS BudgetChargeDollars12,

	-- Projection
		SUM(cv.ProjectionDollarsAdjusted01) AS ProjectionChargeDollars01, SUM(cv.ProjectionDollarsAdjusted02) AS ProjectionChargeDollars02, SUM(cv.ProjectionDollarsAdjusted03) AS ProjectionChargeDollars03, 
		SUM(cv.ProjectionDollarsAdjusted04) AS ProjectionChargeDollars04, SUM(cv.ProjectionDollarsAdjusted05) AS ProjectionChargeDollars05, SUM(cv.ProjectionDollarsAdjusted06) AS ProjectionChargeDollars06, 
		SUM(cv.ProjectionDollarsAdjusted07) AS ProjectionChargeDollars07, SUM(cv.ProjectionDollarsAdjusted08) AS ProjectionChargeDollars08, SUM(cv.ProjectionDollarsAdjusted09) AS ProjectionChargeDollars09, 
		SUM(cv.ProjectionDollarsAdjusted10) AS ProjectionChargeDollars10, SUM(cv.ProjectionDollarsAdjusted11) AS ProjectionChargeDollars11, SUM(cv.ProjectionDollarsAdjusted12) AS ProjectionChargeDollars12
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
		LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
	        AND cv.PatientClassID = sd.PatientClassID
	        AND cv.ServiceLineID = sd.ServiceLineID
			AND cv.AgeCohortID = sd.AgeCohortID
	        AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
	        AND cv.MSDRGID = sd.MSDRGID
	        AND cv.PrimaryCPTID = sd.CPTID
	        AND cv.ServiceProviderID = sd.ProviderID
	        AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
	WHERE cv.BudgetConfigID = @BudgetConfigID
		AND sd.EntityID IS NULL
	GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, 			
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END,		
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID],
				[PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID], 
				[TargetChargeDollars01], [TargetChargeDollars02], [TargetChargeDollars03], [TargetChargeDollars04], [TargetChargeDollars05], [TargetChargeDollars06], 
				[TargetChargeDollars07], [TargetChargeDollars08], [TargetChargeDollars09], [TargetChargeDollars10], [TargetChargeDollars11], [TargetChargeDollars12]
				[BudgetChargeDollars01], [BudgetChargeDollars02], [BudgetChargeDollars03], [BudgetChargeDollars04], [BudgetChargeDollars05], [BudgetChargeDollars06], 
				[BudgetChargeDollars07], [BudgetChargeDollars08], [BudgetChargeDollars09], [BudgetChargeDollars10], [BudgetChargeDollars11], [BudgetChargeDollars12]
				[ProjectionChargeDollars01], [ProjectionChargeDollars02], [ProjectionChargeDollars03], [ProjectionChargeDollars04], [ProjectionChargeDollars05], [ProjectionChargeDollars06], 
				[ProjectionChargeDollars07], [ProjectionChargeDollars08], [ProjectionChargeDollars09], [ProjectionChargeDollars10], [ProjectionChargeDollars11], [ProjectionChargeDollars12]
		FROM #factReimbursementCharges
	END ELSE
	BEGIN
		-- Update Target Values
		UPDATE budg
		SET 
			budg.AdjustedChargeDollars01 = tmp.TargetChargeDollars01,
			budg.AdjustedChargeDollars02 = tmp.TargetChargeDollars02,
			budg.AdjustedChargeDollars03 = tmp.TargetChargeDollars03,
			budg.AdjustedChargeDollars04 = tmp.TargetChargeDollars04,
			budg.AdjustedChargeDollars05 = tmp.TargetChargeDollars05,
			budg.AdjustedChargeDollars06 = tmp.TargetChargeDollars06,
			budg.AdjustedChargeDollars07 = tmp.TargetChargeDollars07,
			budg.AdjustedChargeDollars08 = tmp.TargetChargeDollars08,
			budg.AdjustedChargeDollars09 = tmp.TargetChargeDollars09,
			budg.AdjustedChargeDollars10 = tmp.TargetChargeDollars10,
			budg.AdjustedChargeDollars11 = tmp.TargetChargeDollars11,
			budg.AdjustedChargeDollars12 = tmp.TargetChargeDollars12
		OUTPUT 
			INSERTED.ReimbursementChargesID
		INTO
			#budgetBasisIDs (ReimbursementChargesID) 
		FROM fp.FactReimbursementChargesBudget budg
			INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = budg.ReimbursementChargesID
			INNER JOIN #factReimbursementCharges tmp ON 
					fact.BudgetConfigID = tmp.BudgetConfigID  
				AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID  
				AND fact.EntityID = tmp.EntityID  
				AND fact.PatientClassID = tmp.PatientClassID  
				AND fact.ServiceLineID = tmp.ServiceLineID 
				AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID 
				AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID 
				AND fact.MSDRGID = tmp.MSDRGID 
				AND fact.PrimaryCPTID = tmp.PrimaryCPTID 
				AND fact.UBRevCodeID = tmp.UBRevCodeID 
				AND fact.PayorID = tmp.PayorID 
				AND fact.PayorGroupID = tmp.PayorGroupID 
				AND budg.BudgetPhaseID = 2
		WHERE (
				budg.AdjustedChargeDollars01 != tmp.BudgetChargeDollars01 OR
				budg.AdjustedChargeDollars02 != tmp.BudgetChargeDollars02 OR
				budg.AdjustedChargeDollars03 != tmp.BudgetChargeDollars03 OR
				budg.AdjustedChargeDollars04 != tmp.BudgetChargeDollars04 OR
				budg.AdjustedChargeDollars05 != tmp.BudgetChargeDollars05 OR
				budg.AdjustedChargeDollars06 != tmp.BudgetChargeDollars06 OR
				budg.AdjustedChargeDollars07 != tmp.BudgetChargeDollars07 OR
				budg.AdjustedChargeDollars08 != tmp.BudgetChargeDollars08 OR
				budg.AdjustedChargeDollars09 != tmp.BudgetChargeDollars09 OR
				budg.AdjustedChargeDollars10 != tmp.BudgetChargeDollars10 OR
				budg.AdjustedChargeDollars11 != tmp.BudgetChargeDollars11 OR
				budg.AdjustedChargeDollars12 != tmp.BudgetChargeDollars12
			  )

		-- Update Budget Values
		UPDATE budg
		SET 
			budg.AdjustedChargeDollars01 = tmp.BudgetChargeDollars01,
			budg.AdjustedChargeDollars02 = tmp.BudgetChargeDollars02,
			budg.AdjustedChargeDollars03 = tmp.BudgetChargeDollars03,
			budg.AdjustedChargeDollars04 = tmp.BudgetChargeDollars04,
			budg.AdjustedChargeDollars05 = tmp.BudgetChargeDollars05,
			budg.AdjustedChargeDollars06 = tmp.BudgetChargeDollars06,
			budg.AdjustedChargeDollars07 = tmp.BudgetChargeDollars07,
			budg.AdjustedChargeDollars08 = tmp.BudgetChargeDollars08,
			budg.AdjustedChargeDollars09 = tmp.BudgetChargeDollars09,
			budg.AdjustedChargeDollars10 = tmp.BudgetChargeDollars10,
			budg.AdjustedChargeDollars11 = tmp.BudgetChargeDollars11,
			budg.AdjustedChargeDollars12 = tmp.BudgetChargeDollars12
		OUTPUT 
			INSERTED.ReimbursementChargesID
		INTO
			#budgetBasisIDs (ReimbursementChargesID) 
		FROM fp.FactReimbursementChargesBudget budg
			INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = budg.ReimbursementChargesID
			INNER JOIN #factReimbursementCharges tmp ON 
					fact.BudgetConfigID = tmp.BudgetConfigID  
				AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID  
				AND fact.EntityID = tmp.EntityID  
				AND fact.PatientClassID = tmp.PatientClassID  
				AND fact.ServiceLineID = tmp.ServiceLineID 
				AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID 
				AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID 
				AND fact.MSDRGID = tmp.MSDRGID 
				AND fact.PrimaryCPTID = tmp.PrimaryCPTID 
				AND fact.UBRevCodeID = tmp.UBRevCodeID 
				AND fact.PayorID = tmp.PayorID 
				AND fact.PayorGroupID = tmp.PayorGroupID 
				AND budg.BudgetPhaseID = 3
		WHERE (
				budg.AdjustedChargeDollars01 != tmp.BudgetChargeDollars01 OR
				budg.AdjustedChargeDollars02 != tmp.BudgetChargeDollars02 OR
				budg.AdjustedChargeDollars03 != tmp.BudgetChargeDollars03 OR
				budg.AdjustedChargeDollars04 != tmp.BudgetChargeDollars04 OR
				budg.AdjustedChargeDollars05 != tmp.BudgetChargeDollars05 OR
				budg.AdjustedChargeDollars06 != tmp.BudgetChargeDollars06 OR
				budg.AdjustedChargeDollars07 != tmp.BudgetChargeDollars07 OR
				budg.AdjustedChargeDollars08 != tmp.BudgetChargeDollars08 OR
				budg.AdjustedChargeDollars09 != tmp.BudgetChargeDollars09 OR
				budg.AdjustedChargeDollars10 != tmp.BudgetChargeDollars10 OR
				budg.AdjustedChargeDollars11 != tmp.BudgetChargeDollars11 OR
				budg.AdjustedChargeDollars12 != tmp.BudgetChargeDollars12
			  )

		-- Update Projection Values
		UPDATE proj
		SET 
			proj.AdjustedChargeDollars01 = tmp.ProjectionChargeDollars01,
			proj.AdjustedChargeDollars02 = tmp.ProjectionChargeDollars02,
			proj.AdjustedChargeDollars03 = tmp.ProjectionChargeDollars03,
			proj.AdjustedChargeDollars04 = tmp.ProjectionChargeDollars04,
			proj.AdjustedChargeDollars05 = tmp.ProjectionChargeDollars05,
			proj.AdjustedChargeDollars06 = tmp.ProjectionChargeDollars06,
			proj.AdjustedChargeDollars07 = tmp.ProjectionChargeDollars07,
			proj.AdjustedChargeDollars08 = tmp.ProjectionChargeDollars08,
			proj.AdjustedChargeDollars09 = tmp.ProjectionChargeDollars09,
			proj.AdjustedChargeDollars10 = tmp.ProjectionChargeDollars10,
			proj.AdjustedChargeDollars11 = tmp.ProjectionChargeDollars11,
			proj.AdjustedChargeDollars12 = tmp.ProjectionChargeDollars12
		OUTPUT 
			INSERTED.ReimbursementChargesID
		INTO
			#projectionBasisIDs (ReimbursementChargesID) 
		FROM fp.FactReimbursementChargesProjection proj
			INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = proj.ReimbursementChargesID
			INNER JOIN #factReimbursementCharges tmp ON 
					fact.BudgetConfigID = tmp.BudgetConfigID  
				AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID  
				AND fact.EntityID = tmp.EntityID  
				AND fact.PatientClassID = tmp.PatientClassID  
				AND fact.ServiceLineID = tmp.ServiceLineID 
				AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID 
				AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID 
				AND fact.MSDRGID = tmp.MSDRGID 
				AND fact.PrimaryCPTID = tmp.PrimaryCPTID 
				AND fact.UBRevCodeID = tmp.UBRevCodeID 
				AND fact.PayorID = tmp.PayorID 
				AND fact.PayorGroupID = tmp.PayorGroupID 
				--AND proj.BudgetPhaseID = 2
		WHERE (
				proj.AdjustedChargeDollars01 != tmp.ProjectionChargeDollars01 OR
				proj.AdjustedChargeDollars02 != tmp.ProjectionChargeDollars02 OR
				proj.AdjustedChargeDollars03 != tmp.ProjectionChargeDollars03 OR
				proj.AdjustedChargeDollars04 != tmp.ProjectionChargeDollars04 OR
				proj.AdjustedChargeDollars05 != tmp.ProjectionChargeDollars05 OR
				proj.AdjustedChargeDollars06 != tmp.ProjectionChargeDollars06 OR
				proj.AdjustedChargeDollars07 != tmp.ProjectionChargeDollars07 OR
				proj.AdjustedChargeDollars08 != tmp.ProjectionChargeDollars08 OR
				proj.AdjustedChargeDollars09 != tmp.ProjectionChargeDollars09 OR
				proj.AdjustedChargeDollars10 != tmp.ProjectionChargeDollars10 OR
				proj.AdjustedChargeDollars11 != tmp.ProjectionChargeDollars11 OR
				proj.AdjustedChargeDollars12 != tmp.ProjectionChargeDollars12
			  )

		-- Find out what was changed. We can cross apply all 12 months in this case because months are on rows. If we change
		-- projection to only update the months not loaded, we'll want to update this. Unlike other procs that are similar,
		-- we don't care about the value because when we fix the change history, we take the stored rate in the change history
		-- times the volume in the DB, we don't actually care what the value was we flexed to like in the past.
		SELECT DISTINCT ReimbursementChargesID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID
		FROM #budgetBasisIDs
			CROSS JOIN fw.DimFiscalMonth m
		WHERE m.FiscalMonthID != 0
		UNION ALL
		SELECT DISTINCT ReimbursementChargesID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(12 as tinyint) AS TimeClassID
		FROM #projectionBasisIDs
			CROSS JOIN fw.DimFiscalMonth m
		WHERE m.FiscalMonthID != 0

	END
END
GO


---------------------------------------------

-- fp.procSampleChargeDollarsToReimbursement_History
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author WI          Description
** 1    2022-01-11  MY     JAZZ-31850  Initial
** 2    2022-02-15  BW     JAZZ-33266  Pulling in configuration via Plan Config > Section Setup
** 3    2023-01-26  NT     JAZZ-48268  Make change to use the new fp.ChargeVolume (data restructure)
** 4    2023-04-03  BK     JAZZ-50751  Fix bad column names
** 5    2024-01-11  AO     JAZZ-64530  Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE   PROCEDURE [fp].[procSampleChargeDollarsToReimbursement_History]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	

	DECLARE @IsMedicalSurgicalUsed BIT = 0,
			@IsMsdrgUsed BIT = 0,
			@IsCptUsed BIT = 0,
			@IsUBRevCodeUsed BIT = 0;

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'PrimaryCPTID'

	SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'UBRevCodeID'
	  
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges;
	

	CREATE TABLE #factReimbursementCharges (BudgetConfigID INT, EntityGroupConfigID INT, EntityID INT, PatientClassID INT, ServiceLineID INT, ServiceLineRollupID INT, 
				MedicalSurgicalID INT, PayorID INT, PayorGroupID INT, MSDRGID INT, PrimaryCPTID INT, UBRevCodeID INT, 
				ActualYTDDollarValue01 DECIMAL(19,8), ActualYTDDollarValue02 DECIMAL(19,8), ActualYTDDollarValue03 DECIMAL(19,8), ActualYTDDollarValue04 DECIMAL(19,8), ActualYTDDollarValue05 DECIMAL(19,8), ActualYTDDollarValue06 DECIMAL(19,8),
				ActualYTDDollarValue07 DECIMAL(19,8), ActualYTDDollarValue08 DECIMAL(19,8), ActualYTDDollarValue09 DECIMAL(19,8), ActualYTDDollarValue10 DECIMAL(19,8), ActualYTDDollarValue11 DECIMAL(19,8), ActualYTDDollarValue12 DECIMAL(19,8),
				
				PriorYearActualDollarValue01 DECIMAL(19,8), PriorYearActualDollarValue02 DECIMAL(19,8), PriorYearActualDollarValue03 DECIMAL(19,8), PriorYearActualDollarValue04 DECIMAL(19,8), PriorYearActualDollarValue05 DECIMAL(19,8), PriorYearActualDollarValue06 DECIMAL(19,8),
				PriorYearActualDollarValue07 DECIMAL(19,8), PriorYearActualDollarValue08 DECIMAL(19,8), PriorYearActualDollarValue09 DECIMAL(19,8), PriorYearActualDollarValue10 DECIMAL(19,8), PriorYearActualDollarValue11 DECIMAL(19,8), PriorYearActualDollarValue12 DECIMAL(19,8),
				
				CurrentYearBudgetDollar01 DECIMAL(19,8), CurrentYearBudgetDollar02 DECIMAL(19,8), CurrentYearBudgetDollar03 DECIMAL(19,8), CurrentYearBudgetDollar04 DECIMAL(19,8), CurrentYearBudgetDollar05 DECIMAL(19,8), CurrentYearBudgetDollar06 DECIMAL(19,8),
				CurrentYearBudgetDollar07 DECIMAL(19,8), CurrentYearBudgetDollar08 DECIMAL(19,8), CurrentYearBudgetDollar09 DECIMAL(19,8), CurrentYearBudgetDollar10 DECIMAL(19,8), CurrentYearBudgetDollar11 DECIMAL(19,8), CurrentYearBudgetDollar12 DECIMAL(19,8),
			
	);


	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE d.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 

	END
		
	INSERT INTO #factReimbursementCharges
	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
				CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID,  
				sd.PayorID, sd.PayorGroupID, 
				CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
				CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
				CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID,	
		
		-- Current Year Actuals
		SUM(hist.ActualYTDDollarValue01 * sd.ActualYTDMixPercentage) AS ActualYTDValue01, SUM(hist.ActualYTDDollarValue02 * sd.ActualYTDMixPercentage) AS ActualYTDValue02, SUM(hist.ActualYTDDollarValue03 * sd.ActualYTDMixPercentage) AS ActualYTDValue03, 
		SUM(hist.ActualYTDDollarValue04 * sd.ActualYTDMixPercentage) AS ActualYTDValue04, SUM(hist.ActualYTDDollarValue05 * sd.ActualYTDMixPercentage) AS ActualYTDValue05, SUM(hist.ActualYTDDollarValue06 * sd.ActualYTDMixPercentage) AS ActualYTDValue06, 
		SUM(hist.ActualYTDDollarValue07 * sd.ActualYTDMixPercentage) AS ActualYTDValue07, SUM(hist.ActualYTDDollarValue08 * sd.ActualYTDMixPercentage) AS ActualYTDValue08, SUM(hist.ActualYTDDollarValue09 * sd.ActualYTDMixPercentage) AS ActualYTDValue09, 
		SUM(hist.ActualYTDDollarValue10 * sd.ActualYTDMixPercentage) AS ActualYTDValue10, SUM(hist.ActualYTDDollarValue11 * sd.ActualYTDMixPercentage) AS ActualYTDValue11, SUM(hist.ActualYTDDollarValue12 * sd.ActualYTDMixPercentage) AS ActualYTDValue12,
		
		-- Prior Year Actuals
		SUM(hist.PriorYearActualDollarValue01 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue01, SUM(hist.PriorYearActualDollarValue02 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue02, SUM(hist.PriorYearActualDollarValue03 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue03, 
		SUM(hist.PriorYearActualDollarValue04 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue04, SUM(hist.PriorYearActualDollarValue05 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue05, SUM(hist.PriorYearActualDollarValue06 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue06, 
		SUM(hist.PriorYearActualDollarValue07 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue07, SUM(hist.PriorYearActualDollarValue08 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue08, SUM(hist.PriorYearActualDollarValue09 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue09, 
		SUM(hist.PriorYearActualDollarValue10 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue10, SUM(hist.PriorYearActualDollarValue11 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue11, SUM(hist.PriorYearActualDollarValue12 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue12,
				
		-- Current Year Budget
		SUM(hist.CurrentYearBudgetDollar01 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue01, SUM(hist.CurrentYearBudgetDollar02 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue02, SUM(hist.CurrentYearBudgetDollar03 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue03, 
		SUM(hist.CurrentYearBudgetDollar04 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue04, SUM(hist.CurrentYearBudgetDollar05 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue05, SUM(hist.CurrentYearBudgetDollar06 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue06, 
		SUM(hist.CurrentYearBudgetDollar07 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue07, SUM(hist.CurrentYearBudgetDollar08 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue08, SUM(hist.CurrentYearBudgetDollar09 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue09, 
		SUM(hist.CurrentYearBudgetDollar10 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue10, SUM(hist.CurrentYearBudgetDollar11 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue11, SUM(hist.CurrentYearBudgetDollar12 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue12
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
		INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID
		INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
	        AND cv.PatientClassID = sd.PatientClassID
	        AND cv.ServiceLineID = sd.ServiceLineID
			AND cv.AgeCohortID = sd.AgeCohortID
	        AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
	        AND cv.MSDRGID = sd.MSDRGID
	        AND cv.PrimaryCPTID = sd.CPTID
	        AND cv.ServiceProviderID = sd.ProviderID
	        AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
	WHERE cv.BudgetConfigID = @BudgetConfigID
	GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, 			
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END,		
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END, 
		sd.PayorID, sd.PayorGroupID

	-- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup
	INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
		MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, 
		ActualYTDDollarValue01, ActualYTDDollarValue02, ActualYTDDollarValue03, ActualYTDDollarValue04, ActualYTDDollarValue05, ActualYTDDollarValue06,
		ActualYTDDollarValue07, ActualYTDDollarValue08, ActualYTDDollarValue09, ActualYTDDollarValue10, ActualYTDDollarValue11, ActualYTDDollarValue12, 		
		PriorYearActualDollarValue01, PriorYearActualDollarValue02, PriorYearActualDollarValue03, PriorYearActualDollarValue04, PriorYearActualDollarValue05, PriorYearActualDollarValue06,
		PriorYearActualDollarValue07, PriorYearActualDollarValue08, PriorYearActualDollarValue09, PriorYearActualDollarValue10, PriorYearActualDollarValue11, PriorYearActualDollarValue12, 		
		CurrentYearBudgetDollar01, CurrentYearBudgetDollar02, CurrentYearBudgetDollar03, CurrentYearBudgetDollar04, CurrentYearBudgetDollar05, CurrentYearBudgetDollar06,
		CurrentYearBudgetDollar07, CurrentYearBudgetDollar08, CurrentYearBudgetDollar09, CurrentYearBudgetDollar10, CurrentYearBudgetDollar11, CurrentYearBudgetDollar12)
	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
			CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID,  
			0 AS PayorID, 0 AS PayorGroupID, 
			CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
			CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
			CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID,		
		
		-- Current Year Actuals
		SUM(hist.ActualYTDDollarValue01), SUM(hist.ActualYTDDollarValue02), SUM(hist.ActualYTDDollarValue03), 
		SUM(hist.ActualYTDDollarValue04), SUM(hist.ActualYTDDollarValue05), SUM(hist.ActualYTDDollarValue06), 
		SUM(hist.ActualYTDDollarValue07), SUM(hist.ActualYTDDollarValue08), SUM(hist.ActualYTDDollarValue09), 
		SUM(hist.ActualYTDDollarValue10), SUM(hist.ActualYTDDollarValue11), SUM(hist.ActualYTDDollarValue12),
		
		-- Prior Year Actuals
		SUM(hist.PriorYearActualDollarValue01), SUM(hist.PriorYearActualDollarValue02), SUM(hist.PriorYearActualDollarValue03), 
		SUM(hist.PriorYearActualDollarValue04), SUM(hist.PriorYearActualDollarValue05), SUM(hist.PriorYearActualDollarValue06), 
		SUM(hist.PriorYearActualDollarValue07), SUM(hist.PriorYearActualDollarValue08), SUM(hist.PriorYearActualDollarValue09), 
		SUM(hist.PriorYearActualDollarValue10), SUM(hist.PriorYearActualDollarValue11), SUM(hist.PriorYearActualDollarValue12),
				
		-- Current Year Budget
		SUM(hist.CurrentYearBudgetDollar01), SUM(hist.CurrentYearBudgetDollar02), SUM(hist.CurrentYearBudgetDollar03), 
		SUM(hist.CurrentYearBudgetDollar04), SUM(hist.CurrentYearBudgetDollar05), SUM(hist.CurrentYearBudgetDollar06), 
		SUM(hist.CurrentYearBudgetDollar07), SUM(hist.CurrentYearBudgetDollar08), SUM(hist.CurrentYearBudgetDollar09), 
		SUM(hist.CurrentYearBudgetDollar10), SUM(hist.CurrentYearBudgetDollar11), SUM(hist.CurrentYearBudgetDollar12)
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
		INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID
		LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
	        AND cv.PatientClassID = sd.PatientClassID
	        AND cv.ServiceLineID = sd.ServiceLineID
			AND cv.AgeCohortID = sd.AgeCohortID
	        AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
	        AND cv.MSDRGID = sd.MSDRGID
	        AND cv.PrimaryCPTID = sd.CPTID
	        AND cv.ServiceProviderID = sd.ProviderID
	        AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
	WHERE cv.BudgetConfigID = @BudgetConfigID
		AND sd.EntityID IS NULL
	GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, 			
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END,		
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID],
				[PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID],
				[ActualYTDDollarValue01], [ActualYTDDollarValue02], [ActualYTDDollarValue03], [ActualYTDDollarValue04], [ActualYTDDollarValue05], [ActualYTDDollarValue06], 
				[ActualYTDDollarValue07], [ActualYTDDollarValue08], [ActualYTDDollarValue09], [ActualYTDDollarValue10], [ActualYTDDollarValue11], [ActualYTDDollarValue12],
				[PriorYearActualDollarValue01], [PriorYearActualDollarValue02], [PriorYearActualDollarValue03], [PriorYearActualDollarValue04], [PriorYearActualDollarValue05], [PriorYearActualDollarValue06], 
				[PriorYearActualDollarValue07], [PriorYearActualDollarValue08], [PriorYearActualDollarValue09], [PriorYearActualDollarValue10], [PriorYearActualDollarValue11], [PriorYearActualDollarValue12],
				[CurrentYearBudgetDollar01], [CurrentYearBudgetDollar02], [CurrentYearBudgetDollar03], [CurrentYearBudgetDollar04], [CurrentYearBudgetDollar05], [CurrentYearBudgetDollar06], 
				[CurrentYearBudgetDollar07], [CurrentYearBudgetDollar08], [CurrentYearBudgetDollar09], [CurrentYearBudgetDollar10], [CurrentYearBudgetDollar11], [CurrentYearBudgetDollar12]
		FROM #factReimbursementCharges
	END ELSE
	BEGIN
		-- Update History Values
		UPDATE hist
		SET 
			hist.ActualYTDChargeDollars01 = tmp.ActualYTDDollarValue01,
			hist.ActualYTDChargeDollars02 = tmp.ActualYTDDollarValue02,
			hist.ActualYTDChargeDollars03 = tmp.ActualYTDDollarValue03,
			hist.ActualYTDChargeDollars04 = tmp.ActualYTDDollarValue04,
			hist.ActualYTDChargeDollars05 = tmp.ActualYTDDollarValue05,
			hist.ActualYTDChargeDollars06 = tmp.ActualYTDDollarValue06,
			hist.ActualYTDChargeDollars07 = tmp.ActualYTDDollarValue07,
			hist.ActualYTDChargeDollars08 = tmp.ActualYTDDollarValue08,
			hist.ActualYTDChargeDollars09 = tmp.ActualYTDDollarValue09,
			hist.ActualYTDChargeDollars10 = tmp.ActualYTDDollarValue10,
			hist.ActualYTDChargeDollars11 = tmp.ActualYTDDollarValue11,
			hist.ActualYTDChargeDollars12 = tmp.ActualYTDDollarValue12,

			hist.PriorYearActualChargeDollars01 = tmp.PriorYearActualDollarValue01,
			hist.PriorYearActualChargeDollars02 = tmp.PriorYearActualDollarValue02,
			hist.PriorYearActualChargeDollars03 = tmp.PriorYearActualDollarValue03,
			hist.PriorYearActualChargeDollars04 = tmp.PriorYearActualDollarValue04,
			hist.PriorYearActualChargeDollars05 = tmp.PriorYearActualDollarValue05,
			hist.PriorYearActualChargeDollars06 = tmp.PriorYearActualDollarValue06,
			hist.PriorYearActualChargeDollars07 = tmp.PriorYearActualDollarValue07,
			hist.PriorYearActualChargeDollars08 = tmp.PriorYearActualDollarValue08,
			hist.PriorYearActualChargeDollars09 = tmp.PriorYearActualDollarValue09,
			hist.PriorYearActualChargeDollars10 = tmp.PriorYearActualDollarValue10,
			hist.PriorYearActualChargeDollars11 = tmp.PriorYearActualDollarValue11,
			hist.PriorYearActualChargeDollars12 = tmp.PriorYearActualDollarValue12,

			hist.CurrentYearBudgetChargeDollars01 = tmp.CurrentYearBudgetDollar01,
			hist.CurrentYearBudgetChargeDollars02 = tmp.CurrentYearBudgetDollar02,
			hist.CurrentYearBudgetChargeDollars03 = tmp.CurrentYearBudgetDollar03,
			hist.CurrentYearBudgetChargeDollars04 = tmp.CurrentYearBudgetDollar04,
			hist.CurrentYearBudgetChargeDollars05 = tmp.CurrentYearBudgetDollar05,
			hist.CurrentYearBudgetChargeDollars06 = tmp.CurrentYearBudgetDollar06,
			hist.CurrentYearBudgetChargeDollars07 = tmp.CurrentYearBudgetDollar07,
			hist.CurrentYearBudgetChargeDollars08 = tmp.CurrentYearBudgetDollar08,
			hist.CurrentYearBudgetChargeDollars09 = tmp.CurrentYearBudgetDollar09,
			hist.CurrentYearBudgetChargeDollars10 = tmp.CurrentYearBudgetDollar10,
			hist.CurrentYearBudgetChargeDollars11 = tmp.CurrentYearBudgetDollar11,
			hist.CurrentYearBudgetChargeDollars12 = tmp.CurrentYearBudgetDollar12
		FROM fp.FactReimbursementChargesHistory hist
			INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = hist.ReimbursementChargesID
			INNER JOIN #factReimbursementCharges tmp ON 
					fact.BudgetConfigID = tmp.BudgetConfigID  
				AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID  
				AND fact.EntityID = tmp.EntityID  
				AND fact.PatientClassID = tmp.PatientClassID  
				AND fact.ServiceLineID = tmp.ServiceLineID 
				AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID 
				AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID 
				AND fact.MSDRGID = tmp.MSDRGID 
				AND fact.PrimaryCPTID = tmp.PrimaryCPTID 
				AND fact.UBRevCodeID = tmp.UBRevCodeID 
				AND fact.PayorID = tmp.PayorID 
				AND fact.PayorGroupID = tmp.PayorGroupID 
		WHERE (
				hist.ActualYTDChargeDollars01 != tmp.ActualYTDDollarValue01 OR
				hist.ActualYTDChargeDollars02 != tmp.ActualYTDDollarValue02 OR
				hist.ActualYTDChargeDollars03 != tmp.ActualYTDDollarValue03 OR
				hist.ActualYTDChargeDollars04 != tmp.ActualYTDDollarValue04 OR
				hist.ActualYTDChargeDollars05 != tmp.ActualYTDDollarValue05 OR
				hist.ActualYTDChargeDollars06 != tmp.ActualYTDDollarValue06 OR
				hist.ActualYTDChargeDollars07 != tmp.ActualYTDDollarValue07 OR
				hist.ActualYTDChargeDollars08 != tmp.ActualYTDDollarValue08 OR
				hist.ActualYTDChargeDollars09 != tmp.ActualYTDDollarValue09 OR
				hist.ActualYTDChargeDollars10 != tmp.ActualYTDDollarValue10 OR
				hist.ActualYTDChargeDollars11 != tmp.ActualYTDDollarValue11 OR
				hist.ActualYTDChargeDollars12 != tmp.ActualYTDDollarValue12 OR
				hist.PriorYearActualChargeDollars01 != tmp.PriorYearActualDollarValue01 OR
				hist.PriorYearActualChargeDollars02 != tmp.PriorYearActualDollarValue02 OR
				hist.PriorYearActualChargeDollars03 != tmp.PriorYearActualDollarValue03 OR
				hist.PriorYearActualChargeDollars04 != tmp.PriorYearActualDollarValue04 OR
				hist.PriorYearActualChargeDollars05 != tmp.PriorYearActualDollarValue05 OR
				hist.PriorYearActualChargeDollars06 != tmp.PriorYearActualDollarValue06 OR
				hist.PriorYearActualChargeDollars07 != tmp.PriorYearActualDollarValue07 OR
				hist.PriorYearActualChargeDollars08 != tmp.PriorYearActualDollarValue08 OR
				hist.PriorYearActualChargeDollars09 != tmp.PriorYearActualDollarValue09 OR
				hist.PriorYearActualChargeDollars10 != tmp.PriorYearActualDollarValue10 OR
				hist.PriorYearActualChargeDollars11 != tmp.PriorYearActualDollarValue11 OR
				hist.PriorYearActualChargeDollars12 != tmp.PriorYearActualDollarValue12 OR
				hist.CurrentYearBudgetChargeDollars01 != tmp.CurrentYearBudgetDollar01 OR
				hist.CurrentYearBudgetChargeDollars02 != tmp.CurrentYearBudgetDollar02 OR
				hist.CurrentYearBudgetChargeDollars03 != tmp.CurrentYearBudgetDollar03 OR
				hist.CurrentYearBudgetChargeDollars04 != tmp.CurrentYearBudgetDollar04 OR
				hist.CurrentYearBudgetChargeDollars05 != tmp.CurrentYearBudgetDollar05 OR
				hist.CurrentYearBudgetChargeDollars06 != tmp.CurrentYearBudgetDollar06 OR
				hist.CurrentYearBudgetChargeDollars07 != tmp.CurrentYearBudgetDollar07 OR
				hist.CurrentYearBudgetChargeDollars08 != tmp.CurrentYearBudgetDollar08 OR
				hist.CurrentYearBudgetChargeDollars09 != tmp.CurrentYearBudgetDollar09 OR
				hist.CurrentYearBudgetChargeDollars10 != tmp.CurrentYearBudgetDollar10 OR
				hist.CurrentYearBudgetChargeDollars11 != tmp.CurrentYearBudgetDollar11 OR
				hist.CurrentYearBudgetChargeDollars12 != tmp.CurrentYearBudgetDollar12
			  )
	END
END
GO


---------------------------------------------

-- fp.procSampleChargeDollarsToReimbursement_Initial
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author WI          Description
** 1    2022-01-11  MY     JAZZ-31850  Initial
** 2    2022-02-15  BW     JAZZ-33266  Pulling in configuration via Plan Config > Section Setup
** 3    2022-06-06  MD     JAZZ-37249  Making charge temp table dimensionality unique
** 4    2023-01-31  NT     JAZZ-48268  Make change to use the new fp.ChargeVolume (data restructure)
** 5    2023-04-04  BK     JAZZ-50751  Fix wrong column names
** 6    2024-01-11	AO     JAZZ-64530  Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE   PROCEDURE [fp].[procSampleChargeDollarsToReimbursement_Initial]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	

	DECLARE @IsMedicalSurgicalUsed BIT = 0,
			@IsMsdrgUsed BIT = 0,
			@IsCptUsed BIT = 0,
			@IsUBRevCodeUsed BIT = 0;

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'PrimaryCPTID'

	SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss 
		 INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID 
	  AND ss.PlanSectionID = 7 -- Reimbursement 
	  AND ss.SubSectionID = 6 -- Reimbursement - Charges 
	  AND ss.LevelID = 'UBRevCodeID'
	  
	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges;
	IF OBJECT_ID('tempdb..#reimbursementTargeting') IS NOT NULL DROP TABLE #reimbursementTargeting;
	
	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ChargeVolumeDepartments (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE d.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END

	CREATE TABLE #factReimbursementCharges (
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		EntityID INT,
		PatientClassID INT,
		ServiceLineID INT,
		ServiceLineRollupID INT,
		MedicalSurgicalID INT,
		PayorID INT,
		PayorGroupID INT,
		MSDRGID INT,
		PrimaryCPTID INT,
		UBRevCodeID INT,
		InitialBudgetChargeDollars01 DECIMAL (19,8), InitialBudgetChargeDollars02 DECIMAL (19,8), InitialBudgetChargeDollars03 DECIMAL (19,8), 
		InitialBudgetChargeDollars04 DECIMAL (19,8), InitialBudgetChargeDollars05 DECIMAL (19,8), InitialBudgetChargeDollars06 DECIMAL (19,8),
		InitialBudgetChargeDollars07 DECIMAL (19,8), InitialBudgetChargeDollars08 DECIMAL (19,8), InitialBudgetChargeDollars09 DECIMAL (19,8), 
		InitialBudgetChargeDollars10 DECIMAL (19,8), InitialBudgetChargeDollars11 DECIMAL (19,8), InitialBudgetChargeDollars12 DECIMAL (19,8)
	)

	SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
		CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID
	INTO #reimbursementTargeting
	FROM fp.ChargeVolume cv 
		INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
		INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
	WHERE cv.BudgetConfigID = @BudgetConfigID
		
	INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
	MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, InitialBudgetChargeDollars01, InitialBudgetChargeDollars02, InitialBudgetChargeDollars03, InitialBudgetChargeDollars04, InitialBudgetChargeDollars05, InitialBudgetChargeDollars06,
	InitialBudgetChargeDollars07, InitialBudgetChargeDollars08, InitialBudgetChargeDollars09, InitialBudgetChargeDollars10, InitialBudgetChargeDollars11, InitialBudgetChargeDollars12)
	SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
			MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID,
			SUM(InitialBudgetChargeDollars01) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars02) as InitialBudgetChargeDollars01,
			SUM(InitialBudgetChargeDollars03) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars04) as InitialBudgetChargeDollars01,
			SUM(InitialBudgetChargeDollars05) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars06) as InitialBudgetChargeDollars01,
			SUM(InitialBudgetChargeDollars07) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars08) as InitialBudgetChargeDollars01,
			SUM(InitialBudgetChargeDollars09) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars10) as InitialBudgetChargeDollars01,
			SUM(InitialBudgetChargeDollars11) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars12) as InitialBudgetChargeDollars01
	FROM (
		-- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well.
		SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
				CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, sd.PayorID, sd.PayorGroupID, 
				CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
				CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
				CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID,		
			-- Initial Budget
			SUM(cv.InitialBudgetDollars01 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars01, SUM(cv.InitialBudgetDollars02 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars02, SUM(cv.InitialBudgetDollars03 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars03, 
			SUM(cv.InitialBudgetDollars04 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars04, SUM(cv.InitialBudgetDollars05 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars05, SUM(cv.InitialBudgetDollars06 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars06, 
			SUM(cv.InitialBudgetDollars07 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars07, SUM(cv.InitialBudgetDollars08 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars08, SUM(cv.InitialBudgetDollars09 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars09, 
			SUM(cv.InitialBudgetDollars10 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars10, SUM(cv.InitialBudgetDollars11 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars11, SUM(cv.InitialBudgetDollars12 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars12
		FROM fp.ChargeVolume cv 
			INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
			INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
			INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
				AND cv.PatientClassID = sd.PatientClassID
				AND cv.ServiceLineID = sd.ServiceLineID
				AND cv.AgeCohortID = sd.AgeCohortID
				AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
				AND cv.MSDRGID = sd.MSDRGID
				AND cv.PrimaryCPTID = sd.CPTID
				AND cv.ServiceProviderID = sd.ProviderID
				AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
		WHERE cv.BudgetConfigID = @BudgetConfigID
		GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, 
			CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, 
			CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, 			
			CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END,		
			CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END, 
			sd.PayorID, sd.PayorGroupID

		UNION

		-- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup
		SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, 
			CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
			0 AS PayorID, 0 AS PayorGroupID, 
			CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, 
			CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID,
			CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID,		
			-- Initial Budget
			SUM(cv.InitialBudgetDollars01) AS InitialBudgetChargeDollars01, SUM(cv.InitialBudgetDollars02) AS InitialBudgetChargeDollars02, SUM(cv.InitialBudgetDollars03) AS InitialBudgetChargeDollars03, 
			SUM(cv.InitialBudgetDollars04) AS InitialBudgetChargeDollars04, SUM(cv.InitialBudgetDollars05) AS InitialBudgetChargeDollars05, SUM(cv.InitialBudgetDollars06) AS InitialBudgetChargeDollars06, 
			SUM(cv.InitialBudgetDollars07) AS InitialBudgetChargeDollars07, SUM(cv.InitialBudgetDollars08) AS InitialBudgetChargeDollars08, SUM(cv.InitialBudgetDollars09) AS InitialBudgetChargeDollars09, 
			SUM(cv.InitialBudgetDollars10) AS InitialBudgetChargeDollars10, SUM(cv.InitialBudgetDollars11) AS InitialBudgetChargeDollars11, SUM(cv.InitialBudgetDollars12) AS InitialBudgetChargeDollars12
		FROM fp.ChargeVolume cv 
			INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID
			INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID
			INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID
			LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID 
				AND cv.PatientClassID = sd.PatientClassID
				AND cv.ServiceLineID = sd.ServiceLineID
				AND cv.AgeCohortID = sd.AgeCohortID
				AND cv.MedicalSurgicalID = sd.MedicalSurgicalID
				AND cv.MSDRGID = sd.MSDRGID
				AND cv.PrimaryCPTID = sd.CPTID
				AND cv.ServiceProviderID = sd.ProviderID
				AND cv.EntityGroupConfigID = sd.EntityGroupConfigID
		WHERE cv.BudgetConfigID = @BudgetConfigID
			AND sd.EntityID IS NULL
		GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, 
			CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, 
			CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, 			
			CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END,		
			CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END
		) t
		GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, 
			MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID],
				[PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID],
				[InitialBudgetChargeDollars01], [InitialBudgetChargeDollars02], [InitialBudgetChargeDollars03], [InitialBudgetChargeDollars04], [InitialBudgetChargeDollars05], [InitialBudgetChargeDollars06], 
				[InitialBudgetChargeDollars07], [InitialBudgetChargeDollars08], [InitialBudgetChargeDollars09], [InitialBudgetChargeDollars10], [InitialBudgetChargeDollars11], [InitialBudgetChargeDollars12]
		FROM #factReimbursementCharges
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID],
				fact.[PayorID], fact.[PayorGroupID], fact.[MSDRGID], fact.[PrimaryCPTID], fact.[UBRevCodeID],
				[InitialBudgetChargeDollars01], [InitialBudgetChargeDollars02], [InitialBudgetChargeDollars03], [InitialBudgetChargeDollars04], [InitialBudgetChargeDollars05], [InitialBudgetChargeDollars06], 
				[InitialBudgetChargeDollars07], [InitialBudgetChargeDollars08], [InitialBudgetChargeDollars09], [InitialBudgetChargeDollars10], [InitialBudgetChargeDollars11], [InitialBudgetChargeDollars12]
			FROM [fp].[FactReimbursementCharges] fact  
				INNER JOIN #reimbursementTargeting targeting ON
					fact.BudgetConfigID = targeting.BudgetConfigID
					AND fact.EntityGroupConfigID = targeting.EntityGroupConfigID
					AND fact.EntityID = targeting.EntityID
					AND fact.PatientClassID = targeting.PatientClassID
					AND fact.ServiceLineID = targeting.ServiceLineID
					AND fact.ServiceLineRollupID = targeting.ServiceLineRollupID
					AND fact.MedicalSurgicalID = targeting.MedicalSurgicalID
					AND fact.MSDRGID = targeting.MSDRGID
					AND fact.PrimaryCPTID = targeting.PrimaryCPTID
					AND fact.UBRevCodeID = targeting.UBRevCodeID
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  
  
		MERGE TGT AS target  
		USING #factReimbursementCharges AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.PrimaryCPTID = src.PrimaryCPTID 
			AND target.UBRevCodeID = src.UBRevCodeID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN MATCHED AND (
							target.InitialBudgetChargeDollars01 <> src.InitialBudgetChargeDollars01 OR
							target.InitialBudgetChargeDollars02 <> src.InitialBudgetChargeDollars02 OR
							target.InitialBudgetChargeDollars03 <> src.InitialBudgetChargeDollars03 OR
							target.InitialBudgetChargeDollars04 <> src.InitialBudgetChargeDollars04 OR
							target.InitialBudgetChargeDollars05 <> src.InitialBudgetChargeDollars05 OR
							target.InitialBudgetChargeDollars06 <> src.InitialBudgetChargeDollars06 OR
							target.InitialBudgetChargeDollars07 <> src.InitialBudgetChargeDollars07 OR
							target.InitialBudgetChargeDollars08 <> src.InitialBudgetChargeDollars08 OR
							target.InitialBudgetChargeDollars09 <> src.InitialBudgetChargeDollars09 OR
							target.InitialBudgetChargeDollars10 <> src.InitialBudgetChargeDollars10 OR
							target.InitialBudgetChargeDollars11 <> src.InitialBudgetChargeDollars11 OR
							target.InitialBudgetChargeDollars12 <> src.InitialBudgetChargeDollars12
						 )
		THEN  
			UPDATE SET target.InitialBudgetChargeDollars01 = src.InitialBudgetChargeDollars01,
					   target.InitialBudgetChargeDollars02 = src.InitialBudgetChargeDollars02,
					   target.InitialBudgetChargeDollars03 = src.InitialBudgetChargeDollars03,
					   target.InitialBudgetChargeDollars04 = src.InitialBudgetChargeDollars04,
					   target.InitialBudgetChargeDollars05 = src.InitialBudgetChargeDollars05,
					   target.InitialBudgetChargeDollars06 = src.InitialBudgetChargeDollars06,
					   target.InitialBudgetChargeDollars07 = src.InitialBudgetChargeDollars07,
					   target.InitialBudgetChargeDollars08 = src.InitialBudgetChargeDollars08,
					   target.InitialBudgetChargeDollars09 = src.InitialBudgetChargeDollars09,
					   target.InitialBudgetChargeDollars10 = src.InitialBudgetChargeDollars10,
					   target.InitialBudgetChargeDollars11 = src.InitialBudgetChargeDollars11,
					   target.InitialBudgetChargeDollars12 = src.InitialBudgetChargeDollars12;
		
	END
END
GO


---------------------------------------------

-- fp.procSampleChargeMaster
CREATE PROCEDURE [fp].[procSampleChargeMaster]
	@BudgetConfigID INT,
	@SourceFiscalYearID SMALLINT,
	@SourceTimeClassID TINYINT,
	@IsEntityUsed BIT,
	@IsPatientClassUsed BIT
AS
BEGIN
	
	-- Note: The charge master is at the budget level, not the entity (well it can be, but we can't rely on
	-- entityId being in the data set. 
	
	DELETE FROM fp.FactChargeMaster WHERE BudgetConfigID = @BudgetConfigID

		
	DECLARE @CurrentFiscalYearID INT;
	SET @CurrentFiscalYearID = (Select (FiscalYearID - 1) as CurrentYear from fp.BudgetConfig where BudgetConfigID = @BudgetConfigID);
	DECLARE @monthsLoaded NVARCHAR(100);
	SET @monthsLoaded = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 'AND fm.SortOrder <= bc.MonthsLoaded' ELSE '' END);
	
	DECLARE @SelectStatement NVARCHAR(MAX),
			@GroupByStatement NVARCHAR(MAX);
			
	SET @SelectStatement = (CASE WHEN @IsEntityUsed = 1 THEN 'EntityID, ' ELSE '0 As EntityID, ' END + 
	         				CASE WHEN @IsPatientClassUsed = 1 THEN 'PatientClassID, ' ELSE '0 As PatientClassID, ' END);
							
	SET @GroupByStatement =(CASE WHEN @IsEntityUsed = 1 THEN ', EntityID' ELSE '' END + 
	         				CASE WHEN @IsPatientClassUsed = 1 THEN ', PatientClassID' ELSE '' END);
	
	EXEC('

	INSERT INTO fp.FactChargeMaster (BudgetConfigID, BaselineChargeRate, ChargeRate1, ChargeCodeID, EntityID, PatientClassID, TimeClassID)
	SELECT  ' + @BudgetConfigID + ' AS BudgetConfigID,
	        CASE WHEN SUM(ISNULL(Units, 0)) = 0 THEN 0 ELSE SUM(ISNULL(Dollars, 0)) / SUM(ISNULL(Units, 0)) END AS BaselineChargeRate,
	        CASE WHEN SUM(ISNULL(Units, 0)) = 0 THEN 0 ELSE SUM(ISNULL(Dollars, 0)) / SUM(ISNULL(Units, 0)) END AS ChargeRate1,
	        ChargeCodeID,
			' + @SelectStatement + 
			 'PaddedTimeClassID
	FROM    ( SELECT    md.EntityID ,
	                    f.FiscalYearID ,
	                    f.FiscalMonthID ,
	                    TimeClassID ,
	                    PatientClassID ,
	                    ChargeCodeID ,
	                    ut.Name AS UnitTypeName ,
	                    Value
	            FROM      [int].[FactCDM] f
	                    INNER JOIN [fw].[DimUnitType] ut ON f.UnitTypeID = ut.UnitTypeID
						INNER JOIN [fw].[DimFiscalMonth] fm ON f.FiscalMonthID = fm.FiscalMonthID
	                    INNER JOIN [fw].[DimDepartment] md ON md.DepartmentID = f.DepartmentID
						INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = ' + @BudgetConfigID + '
	            WHERE     IsDeleted = 0 
	                    AND f.FiscalYearID = ' + @SourceFiscalYearID + '
	                    AND f.TimeClassID = ' + @SourceTimeClassID + '
						' + @monthsLoaded + '
	        ) AS data PIVOT
	( SUM(Value) FOR UnitTypeName IN ( [Dollars], [Units] ) ) AS pvt
		CROSS APPLY (VALUES (2),(12)) tc(PaddedTimeClassID)
	GROUP BY ChargeCodeID, PaddedTimeClassID' + @GroupByStatement);
		
END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeBudgetData
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1   2023-01-31   NT     JAZZ-48268   Make change to use the new fp.ChargeVolume (data restructure)
*************************************************************/
CREATE PROCEDURE [fp].[procSampleChargeVolumeBudgetData]
	@EntityGroupConfigID int
AS
BEGIN

	UPDATE
			cv
		SET
			TargetAdjusted01 = InitialBudget01,
			TargetAdjusted02 = InitialBudget02,
			TargetAdjusted03 = InitialBudget03,
			TargetAdjusted04 = InitialBudget04,
			TargetAdjusted05 = InitialBudget05,
			TargetAdjusted06 = InitialBudget06,
			TargetAdjusted07 = InitialBudget07,
			TargetAdjusted08 = InitialBudget08,
			TargetAdjusted09 = InitialBudget09,
			TargetAdjusted10 = InitialBudget10,
			TargetAdjusted11 = InitialBudget11,
			TargetAdjusted12 = InitialBudget12,
			BudgetAdjusted01 = InitialBudget01,
			BudgetAdjusted02 = InitialBudget02,
			BudgetAdjusted03 = InitialBudget03,
			BudgetAdjusted04 = InitialBudget04,
			BudgetAdjusted05 = InitialBudget05,
			BudgetAdjusted06 = InitialBudget06,
			BudgetAdjusted07 = InitialBudget07,
			BudgetAdjusted08 = InitialBudget08,
			BudgetAdjusted09 = InitialBudget09,
			BudgetAdjusted10 = InitialBudget10,
			BudgetAdjusted11 = InitialBudget11,
			BudgetAdjusted12 = InitialBudget12
		FROM [fp].[ChargeVolume] cv
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID 
		  AND cv.UnitTypeID = 145
		  AND IsNew = 0
END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeClearData
/*************************************************************
** Change History
**************************************************************
** CID		Date		Author	    WI				Description
** 1		2021-03-02	LR			JAZZ-12907		Fixing FactChargeVolume deletes for KeepAdjustments = 0 
** 2		2021-03-24	LR			JAZZ-16329		Including delete for ChargeVolumeDollars tables
** 3        2023-01-26	NT			JAZZ-48268		Replace by new fp.ChargeVolume table for data re-structure and delete only what will be sampled by left joining to the source				
** 4        2023-06-30	MD			JAZZ-55672		Remove adjustment delete logic, add remove entity config logic		
** 5		2024-01-29	MY			JAZZ-65493		1Plan sampled historical data isn't updated in FP tables if import table data is changed
** 6		2024-09-06	MZ			JAZZ-75639		Referencing to @BudgetConfigGUID when querying fp.SectionSetup table.
***************************************************************/
CREATE   PROCEDURE [fp].[procSampleChargeVolumeClearData]
	@EntityGroupConfigID INT,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@IsRemoveConfig BIT = 0
AS
BEGIN

	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END
	DECLARE @r INT;
 	DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID)

	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
			SELECT *
			FROM fp.SectionSetup ss
								INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
								WHERE IsHidden = 1 AND bc.BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0
				)
			THEN CAST(1 AS BIT)
			ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
			SELECT *
			FROM fp.SectionSetup ss
								INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
								WHERE IsHidden = 1 AND bc.BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0
				)
			THEN CAST(1 AS BIT)
			ELSE CAST(0 AS BIT) END;

	/*Create temp table that will contain ChargeVolumeID not matching the source data from int.FactCDM. These are the ones that will be deleted. 
	  Rest will be have their values reset to 0 to be sampled */
	CREATE TABLE #ChargeVolumeToDelete (ChargeVolumeID INT)

	IF @IsRemoveConfig = 1
	BEGIN
		INSERT #ChargeVolumeToDelete with (tablock) (ChargeVolumeID)
		SELECT ChargeVolumeID FROM fp.ChargeVolume
		WHERE EntityGroupConfigID = @EntityGroupConfigID 
	END
	ELSE
	BEGIN
		INSERT #ChargeVolumeToDelete with (tablock) (ChargeVolumeID) 
		SELECT ChargeVolumeID 
		FROM 
			(SELECT DISTINCT ChargeVolumeID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID
			 FROM [fp].[ChargeVolume] 
			 WHERE EntityGroupConfigID = @EntityGroupConfigID 
			  AND IsNew = 0
			 ) dest
		LEFT JOIN 
			(SELECT DISTINCT
				dept.EntityID, 
				cv.DepartmentID, 
				cv.ServiceLineID,
				cv.PatientClassID,
				CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cv.AgeCohortID END AS AgeCohortID,
				CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cv.MedicalSurgicalID END AS MedicalSurgicalID,
				cv.ChargeCodeID
			FROM [int].[FactCDM] cv
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cv.FiscalMonthID
			INNER JOIN [fw].[DimDepartment] dept ON cv.DepartmentID = dept.DepartmentID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 
				((cv.FiscalYearID = @SourceFiscalYearID AND cv.TimeclassID = @SourceTimeClassID)  -- baseline
					OR (cv.FiscalYearID = @CurrentFiscalYearID)  		                          -- projection (current year actuals)
					OR (cv.FiscalYearID = @CurrentFiscalYearID - 1 AND cv.TimeClassID = 1))  	  -- prior year, actual & budget
				AND cv.IsDeleted = 0
				AND cv.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
			) src
		 ON src.DepartmentID = dest.DepartmentID
		AND src.ServiceLineID = dest.ServiceLineID
		AND src.PatientClassID = dest.PatientClassID
		AND src.AgeCohortID = dest.AgeCohortID
		AND src.MedicalSurgicalID = dest.MedicalSurgicalID
		AND src.ChargeCodeID = dest.ChargeCodeID
		WHERE src.DepartmentID IS NULL
	END

	CREATE INDEX IX_1 on #ChargeVolumeToDelete(ChargeVolumeID)	
		
	SET @r = 1;	 
	-- We need to wipe the history so that the adjustments can be re-applied aferwards
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) cvch FROM [fp].[ChargeVolumeChangeHistory] cvch INNER JOIN [fp].[ChargeVolume] cv on cv.ChargeVolumeID = cvch.ChargeVolumeID WHERE EntityGroupConfigID = @EntityGroupConfigID;
	   SET @r = @@ROWCOUNT;	 
	   COMMIT TRANSACTION;
	END

	/*delete data matching that of #ChargeVolumeToDelete */
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) cvh FROM [fp].[ChargeVolumeHistory] cvh INNER JOIN #ChargeVolumeToDelete tt on cvh.ChargeVolumeID=tt.ChargeVolumeID
	   SET @r = @@ROWCOUNT;	 
	   COMMIT TRANSACTION;
	END
	
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION
		DELETE  TOP (@ChunkCount) fcv FROM [fp].[ChargeVolume] fcv INNER JOIN #ChargeVolumeToDelete tt on fcv.ChargeVolumeID=tt.ChargeVolumeID;
		SET @r = @@ROWCOUNT;
		COMMIT TRANSACTION;
	END

	IF @IsRemoveConfig = 0
	BEGIN
		UPDATE cv
		SET
			SampledBudget01 = 0,
			SampledBudget02 = 0,
			SampledBudget03 = 0,
			SampledBudget04 = 0,
			SampledBudget05 = 0,
			SampledBudget06 = 0,
			SampledBudget07 = 0,
			SampledBudget08 = 0,
			SampledBudget09 = 0,
			SampledBudget10 = 0,
			SampledBudget11 = 0,
			SampledBudget12 = 0,
			SampledProjection01 = 0,
			SampledProjection02 = 0,
			SampledProjection03 = 0,
			SampledProjection04 = 0,
			SampledProjection05 = 0,
			SampledProjection06 = 0,
			SampledProjection07 = 0,
			SampledProjection08 = 0,
			SampledProjection09 = 0,
			SampledProjection10 = 0,
			SampledProjection11 = 0,
			SampledProjection12 = 0,
			InitialBudget01 = 0,
			InitialBudget02 = 0,
			InitialBudget03 = 0,
			InitialBudget04 = 0,
			InitialBudget05 = 0,
			InitialBudget06 = 0,
			InitialBudget07 = 0,
			InitialBudget08 = 0,
			InitialBudget09 = 0,
			InitialBudget10 = 0,
			InitialBudget11 = 0,
			InitialBudget12 = 0,
			InitialProjection01 = 0,
			InitialProjection02 = 0,
			InitialProjection03 = 0,
			InitialProjection04 = 0,
			InitialProjection05 = 0,
			InitialProjection06 = 0,
			InitialProjection07 = 0,
			InitialProjection08 = 0,
			InitialProjection09 = 0,
			InitialProjection10 = 0,
			InitialProjection11 = 0,
			InitialProjection12 = 0,
			TargetAdjusted01 = 0,
			TargetAdjusted02 = 0,
			TargetAdjusted03 = 0,
			TargetAdjusted04 = 0,
			TargetAdjusted05 = 0,
			TargetAdjusted06 = 0,
			TargetAdjusted07 = 0,
			TargetAdjusted08 = 0,
			TargetAdjusted09 = 0,
			TargetAdjusted10 = 0,
			TargetAdjusted11 = 0,
			TargetAdjusted12 = 0,
			BudgetAdjusted01 = 0,
			BudgetAdjusted02 = 0,
			BudgetAdjusted03 = 0,
			BudgetAdjusted04 = 0,
			BudgetAdjusted05 = 0,
			BudgetAdjusted06 = 0,
			BudgetAdjusted07 = 0,
			BudgetAdjusted08 = 0,
			BudgetAdjusted09 = 0,
			BudgetAdjusted10 = 0,
			BudgetAdjusted11 = 0,
			BudgetAdjusted12 = 0,
			ProjectionAdjusted01 = 0,
			ProjectionAdjusted02 = 0,
			ProjectionAdjusted03 = 0,
			ProjectionAdjusted04 = 0,
			ProjectionAdjusted05 = 0,
			ProjectionAdjusted06 = 0,
			ProjectionAdjusted07 = 0,
			ProjectionAdjusted08 = 0,
			ProjectionAdjusted09 = 0,
			ProjectionAdjusted10 = 0,
			ProjectionAdjusted11 = 0,
			ProjectionAdjusted12 = 0,
			InitialBudgetDollars01 = 0,
			InitialBudgetDollars02 = 0,
			InitialBudgetDollars03 = 0,
			InitialBudgetDollars04 = 0,
			InitialBudgetDollars05 = 0,
			InitialBudgetDollars06 = 0,
			InitialBudgetDollars07 = 0,
			InitialBudgetDollars08 = 0,
			InitialBudgetDollars09 = 0,
			InitialBudgetDollars10 = 0,
			InitialBudgetDollars11 = 0,
			InitialBudgetDollars12 = 0,
			InitialProjectionDollars01 = 0,
			InitialProjectionDollars02 = 0,
			InitialProjectionDollars03 = 0,
			InitialProjectionDollars04 = 0,
			InitialProjectionDollars05 = 0,
			InitialProjectionDollars06 = 0,
			InitialProjectionDollars07 = 0,
			InitialProjectionDollars08 = 0,
			InitialProjectionDollars09 = 0,
			InitialProjectionDollars10 = 0,
			InitialProjectionDollars11 = 0,
			InitialProjectionDollars12 = 0,
			BudgetPrice01 = 0,
			BudgetPrice02 = 0,
			BudgetPrice03 = 0,
			BudgetPrice04 = 0,
			BudgetPrice05 = 0,
			BudgetPrice06 = 0,
			BudgetPrice07 = 0,
			BudgetPrice08 = 0,
			BudgetPrice09 = 0,
			BudgetPrice10 = 0,
			BudgetPrice11 = 0,
			BudgetPrice12 = 0,
			TargetPrice01 = 0,
			TargetPrice02 = 0,
			TargetPrice03 = 0,
			TargetPrice04 = 0,
			TargetPrice05 = 0,
			TargetPrice06 = 0,
			TargetPrice07 = 0,
			TargetPrice08 = 0,
			TargetPrice09 = 0,
			TargetPrice10 = 0,
			TargetPrice11 = 0,
			TargetPrice12 = 0,
			ProjectionPrice01 = 0,
			ProjectionPrice02 = 0,
			ProjectionPrice03 = 0,
			ProjectionPrice04 = 0,
			ProjectionPrice05 = 0,
			ProjectionPrice06 = 0,
			ProjectionPrice07 = 0,
			ProjectionPrice08 = 0,
			ProjectionPrice09 = 0,
			ProjectionPrice10 = 0,
			ProjectionPrice11 = 0,
			ProjectionPrice12 = 0
		FROM
			[fp].[ChargeVolume] cv	                
		WHERE  cv.EntityGroupConfigID = @EntityGroupConfigID

		UPDATE hist
		SET
			[ActualYTDValue01] = 0,
			[ActualYTDValue02] = 0,
			[ActualYTDValue03] = 0,
			[ActualYTDValue04] = 0,
			[ActualYTDValue05] = 0,
			[ActualYTDValue06] = 0,
			[ActualYTDValue07] = 0,
			[ActualYTDValue08] = 0,
			[ActualYTDValue09] = 0,
			[ActualYTDValue10] = 0,
			[ActualYTDValue11] = 0,
			[ActualYTDValue12] = 0,
			[PriorYearActualValue01] = 0,
			[PriorYearActualValue02] = 0,
			[PriorYearActualValue03] = 0,
			[PriorYearActualValue04] = 0,
			[PriorYearActualValue05] = 0,
			[PriorYearActualValue06] = 0,
			[PriorYearActualValue07] = 0,
			[PriorYearActualValue08] = 0,
			[PriorYearActualValue09] = 0,
			[PriorYearActualValue10] = 0,
			[PriorYearActualValue11] = 0,
			[PriorYearActualValue12] = 0,
			[CurrentYearBudget01] = 0,
			[CurrentYearBudget02] = 0,
			[CurrentYearBudget03] = 0,
			[CurrentYearBudget04] = 0,
			[CurrentYearBudget05] = 0,
			[CurrentYearBudget06] = 0,
			[CurrentYearBudget07] = 0,
			[CurrentYearBudget08] = 0,
			[CurrentYearBudget09] = 0,
			[CurrentYearBudget10] = 0,
			[CurrentYearBudget11] = 0,
			[CurrentYearBudget12] = 0,
			[ActualYTDDollarValue01] = 0,
			[ActualYTDDollarValue02] = 0,
			[ActualYTDDollarValue03] = 0,
			[ActualYTDDollarValue04] = 0,
			[ActualYTDDollarValue05] = 0,
			[ActualYTDDollarValue06] = 0,
			[ActualYTDDollarValue07] = 0,
			[ActualYTDDollarValue08] = 0,
			[ActualYTDDollarValue09] = 0,
			[ActualYTDDollarValue10] = 0,
			[ActualYTDDollarValue11] = 0,
			[ActualYTDDollarValue12] = 0,
			[PriorYearActualDollarValue01] = 0,
			[PriorYearActualDollarValue02] = 0,
			[PriorYearActualDollarValue03] = 0,
			[PriorYearActualDollarValue04] = 0,
			[PriorYearActualDollarValue05] = 0,
			[PriorYearActualDollarValue06] = 0,
			[PriorYearActualDollarValue07] = 0,
			[PriorYearActualDollarValue08] = 0,
			[PriorYearActualDollarValue09] = 0,
			[PriorYearActualDollarValue10] = 0,
			[PriorYearActualDollarValue11] = 0,
			[PriorYearActualDollarValue12] = 0,
			[CurrentYearBudgetDollar01] = 0,
			[CurrentYearBudgetDollar02] = 0,
			[CurrentYearBudgetDollar03] = 0,
			[CurrentYearBudgetDollar04] = 0,
			[CurrentYearBudgetDollar05] = 0,
			[CurrentYearBudgetDollar06] = 0,
			[CurrentYearBudgetDollar07] = 0,
			[CurrentYearBudgetDollar08] = 0,
			[CurrentYearBudgetDollar09] = 0,
			[CurrentYearBudgetDollar10] = 0,
			[CurrentYearBudgetDollar11] = 0,
			[CurrentYearBudgetDollar12] = 0
		FROM [fp].[ChargeVolumeHistory] hist	
			INNER JOIN [fp].[ChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
	END
END;
GO


---------------------------------------------

-- fp.procSampleChargeVolumeDimensionality
CREATE   PROCEDURE [fp].[procSampleChargeVolumeDimensionality]
	@BudgetConfigID int,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** 1	2021-08-24	NT		JAZZ-24593	Pad data for UnitType 34 (Dollars) only when IsDollarsRemovedFromCharges parameter is false
	** 2	2022-12-12  DM		JAZZ-46455   Samplimg of Age Cohort and Medical/Surgical is linked to Section Setup
	** 3   2023-01-26   NT     JAZZ-48268   Make change to sample charge volume dimensionality into the new fp.ChargeVolume (data restructure)
	** 4   2024-09-03   BW     JAZZ-75631   Fix for duplicate key insert
	*************************************************************/

	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	INSERT INTO [fp].[ChargeVolume]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID], [ServiceEntityID])
	SELECT DISTINCT
		@BudgetConfigID,
		@EntityGroupConfigID,
		cdm.EntityID,
		cdm.DepartmentID,
		cdm.ServiceLineID,
		cdm.PatientClassID,
		cdm.AgeCohortID,  
		cdm.MedicalSurgicalID,  
		cdm.ChargeCodeID,
		UnitTypeID,
		cdm.ServiceEntityID
	FROM(
		SELECT 
		dept.EntityID,  -- TO BE REPLACED WITH int.FactCDM.EntityID when available
		cdm.DepartmentID, 
		cdm.ServiceLineID,
		cdm.PatientClassID,
		CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID,
		CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,
		cdm.ChargeCodeID,
		145 AS UnitTypeID,
		dept.EntityID as ServiceEntityID,
		cdm.IsDeleted,
		cdm.FiscalMonthID
		FROM [int].[FactCDM] cdm 
		INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
		INNER JOIN [fw].[DimDepartment] dept ON cdm.DepartmentID = dept.DepartmentID
		WHERE 
			((cdm.FiscalYearID = @SourceFiscalYearID AND cdm.TimeclassID = @SourceTimeClassID)		-- baseline
			OR (cdm.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
			OR (cdm.FiscalYearID = @CurrentFiscalYearID - 1 AND cdm.TimeClassID = 1))  				-- prior year, actual & budget
			AND cdm.IsDeleted = 0
			AND cdm.FiscalMonthID != 0				 
		 ) cdm
		INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = cdm.EntityID
		INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		LEFT JOIN (
				-- Check for existing dimensionality so we only insert needed dimensionality
				SELECT Distinct DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID
				FROM [fp].[ChargeVolume]
				WHERE EntityGroupConfigID = @EntityGroupConfigID
			) existing
		ON cdm.DepartmentID = existing.DepartmentID
		AND cdm.ServiceLineID = existing.ServiceLineID
		AND cdm.PatientClassID = existing.PatientClassID
		AND cdm.AgeCohortID = existing.AgeCohortID
		AND cdm.MedicalSurgicalID = existing.MedicalSurgicalID
		AND cdm.ChargeCodeID = existing.ChargeCodeID
	WHERE 
		 egc.EntityGroupConfigID = @EntityGroupConfigID
		AND existing.DepartmentID IS NULL
		AND cdm.IsDeleted = 0
		AND cdm.FiscalMonthID != 0
END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeDollarsHistory
CREATE   PROCEDURE [fp].[procSampleChargeVolumeDollarsHistory]
 	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
 AS
 BEGIN
    /**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID Date        Author  WI         Description
	 ** 1 	2021-08-24  NT  	JAZZ-24593 Populate ChargeVolume Dollars Historical Data
	 ** 2	2022-12-12	DM	JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
	 ** 3   2023-01-31   NT JAZZ-48268  Make change to use the new fp.ChargeVolume (data restructure)
	 *************************************************************/
	 
	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	-- set all of the values for current year actual/annualized
	--Update actual dollars
	UPDATE
		cvh
	SET
		ActualYTDDollarValue01 = ISNULL(Month01, 0),
		ActualYTDDollarValue02 = ISNULL(Month02, 0),
		ActualYTDDollarValue03 = ISNULL(Month03, 0),
		ActualYTDDollarValue04 = ISNULL(Month04, 0),
		ActualYTDDollarValue05 = ISNULL(Month05, 0),
		ActualYTDDollarValue06 = ISNULL(Month06, 0),
		ActualYTDDollarValue07 = ISNULL(Month07, 0),
		ActualYTDDollarValue08 = ISNULL(Month08, 0),
		ActualYTDDollarValue09 = ISNULL(Month09, 0),
		ActualYTDDollarValue10 = ISNULL(Month10, 0),
		ActualYTDDollarValue11 = ISNULL(Month11, 0),
		ActualYTDDollarValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolumeHistory] cvh
		INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID
		INNER JOIN 
		(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,   
					cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value
				 FROM [int].[FactCDM] cdm 
				 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
				 WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded AND cdm.UnitTypeID IN (34) --dollars
				 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			 ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
			AND cv.UnitTypeID = 145 --dollars and units are on the same row with UnitTypeID = 145. we will get rid of UnitTypeID eventually
	WHERE
		cv.EntityGroupConfigID = @EntityGroupConfigID

	--Update Prior Year Dollars		
	UPDATE
		cvh
	SET
		PriorYearActualDollarValue01 = ISNULL(Month01, 0),
		PriorYearActualDollarValue02 = ISNULL(Month02, 0),
		PriorYearActualDollarValue03 = ISNULL(Month03, 0),
		PriorYearActualDollarValue04 = ISNULL(Month04, 0),
		PriorYearActualDollarValue05 = ISNULL(Month05, 0),
		PriorYearActualDollarValue06 = ISNULL(Month06, 0),
		PriorYearActualDollarValue07 = ISNULL(Month07, 0),
		PriorYearActualDollarValue08 = ISNULL(Month08, 0),
		PriorYearActualDollarValue09 = ISNULL(Month09, 0),
		PriorYearActualDollarValue10 = ISNULL(Month10, 0),
		PriorYearActualDollarValue11 = ISNULL(Month11, 0),
		PriorYearActualDollarValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolumeHistory] cvh
		INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID
		INNER JOIN 
		(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,   
					cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value
				 FROM [int].[FactCDM] cdm 
				 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
				 WHERE cdm.FiscalYearID = @CurrentFiscalYearID - 1 AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 
				   AND cdm.UnitTypeID IN (34)
				 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
			AND cv.UnitTypeID = 145 --dollars and units are on the same row with UnitTypeID = 145. we will get rid of UnitTypeID eventually
	WHERE
		cv.EntityGroupConfigID = @EntityGroupConfigID

	--Update CYB dollars
	UPDATE
		cvh
	SET
		CurrentYearBudgetDollar01 = ISNULL(Month01, 0),
		CurrentYearBudgetDollar02 = ISNULL(Month02, 0),
		CurrentYearBudgetDollar03 = ISNULL(Month03, 0),
		CurrentYearBudgetDollar04 = ISNULL(Month04, 0),
		CurrentYearBudgetDollar05 = ISNULL(Month05, 0),
		CurrentYearBudgetDollar06 = ISNULL(Month06, 0),
		CurrentYearBudgetDollar07 = ISNULL(Month07, 0),
		CurrentYearBudgetDollar08 = ISNULL(Month08, 0),
		CurrentYearBudgetDollar09 = ISNULL(Month09, 0),
		CurrentYearBudgetDollar10 = ISNULL(Month10, 0),
		CurrentYearBudgetDollar11 = ISNULL(Month11, 0),
		CurrentYearBudgetDollar12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolumeHistory] cvh
		INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID
		INNER JOIN 
		(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,   
					cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value
				 FROM [int].[FactCDM] cdm 
				 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
				 WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 2 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 
				  AND cdm.UnitTypeID IN (34) --dollars
				 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			 ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
			AND cv.UnitTypeID = 145 --dollars and units are on the same row with UnitTypeID = 145. we will get rid of UnitTypeID eventually
	WHERE
		cv.EntityGroupConfigID = @EntityGroupConfigID
	
END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeHistoricalData
CREATE   PROCEDURE [fp].[procSampleChargeVolumeHistoricalData]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** 1	2021-08-24	NT		JAZZ-24593	Pad data for Unit Type 34 (Dollars) only when IsDollarsRemovedFromCharge flag is false
	** 2	2022-12-12	DM		JAZZ-46455  Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
	** 3   2023-01-31   NT     JAZZ-48268  Make change to use the new fp.ChargeVolume (data restructure)
	*************************************************************/

	-- Reset all values to 0 
	UPDATE
		cvh
	SET
		PriorYearActualValue01 = 0,
		PriorYearActualValue02 = 0,
		PriorYearActualValue03 = 0,
		PriorYearActualValue04 = 0,
		PriorYearActualValue05 = 0,
		PriorYearActualValue06 = 0,
		PriorYearActualValue07 = 0,
		PriorYearActualValue08 = 0,
		PriorYearActualValue09 = 0,
		PriorYearActualValue10 = 0,
		PriorYearActualValue11 = 0,
		PriorYearActualValue12 = 0,
		ActualYTDValue01 = 0,
		ActualYTDValue02 = 0,
		ActualYTDValue03 = 0,
		ActualYTDValue04 = 0,
		ActualYTDValue05 = 0,
		ActualYTDValue06 = 0,
		ActualYTDValue07 = 0,
		ActualYTDValue08 = 0,
		ActualYTDValue09 = 0,
		ActualYTDValue10 = 0,
		ActualYTDValue11 = 0,
		ActualYTDValue12 = 0,
		CurrentYearBudget01 = 0,
		CurrentYearBudget02 = 0,
		CurrentYearBudget03 = 0,
		CurrentYearBudget04 = 0,
		CurrentYearBudget05 = 0,
		CurrentYearBudget06 = 0,
		CurrentYearBudget07 = 0,
		CurrentYearBudget08 = 0,
		CurrentYearBudget09 = 0,
		CurrentYearBudget10 = 0,
		CurrentYearBudget11 = 0,
		CurrentYearBudget12 = 0
	FROM
		[fp].[ChargeVolumeHistory] cvh
	INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID
	WHERE cv.EntityGroupConfigID = @EntityGroupConfigID

	-- Add any new records as needed
	INSERT INTO [fp].[ChargeVolumeHistory]	([ChargeVolumeID])
	SELECT cv.ChargeVolumeID
	FROM [fp].[ChargeVolume] cv
	LEFT JOIN [fp].[ChargeVolumeHistory] cvh
	 ON cv.ChargeVolumeID = cvh.ChargeVolumeID
	WHERE cv.EntityGroupConfigID = @EntityGroupConfigID 
	  AND cvh.ChargeVolumeID IS NULL
	
	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	-- set all of the UNITs for current year actual/annualized
	UPDATE
		cvh
	SET
		ActualYTDValue01 = ISNULL(Month01, 0),
		ActualYTDValue02 = ISNULL(Month02, 0),
		ActualYTDValue03 = ISNULL(Month03, 0),
		ActualYTDValue04 = ISNULL(Month04, 0),
		ActualYTDValue05 = ISNULL(Month05, 0),
		ActualYTDValue06 = ISNULL(Month06, 0),
		ActualYTDValue07 = ISNULL(Month07, 0),
		ActualYTDValue08 = ISNULL(Month08, 0),
		ActualYTDValue09 = ISNULL(Month09, 0),
		ActualYTDValue10 = ISNULL(Month10, 0),
		ActualYTDValue11 = ISNULL(Month11, 0),
		ActualYTDValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolumeHistory] cvh
		INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID
		INNER JOIN 
		(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,   
					cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value
				 FROM [int].[FactCDM] cdm 
				 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
				WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 1 
				   AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded
				   AND cdm.UnitTypeID IN (145) --units
				 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
			AND cv.UnitTypeID = pv.UnitTypeID
	WHERE
		 cv.EntityGroupConfigID = @EntityGroupConfigID
  
	--Update Prior Year units		
	UPDATE
		cvh
	SET
		PriorYearActualValue01 = ISNULL(Month01, 0),
		PriorYearActualValue02 = ISNULL(Month02, 0),
		PriorYearActualValue03 = ISNULL(Month03, 0),
		PriorYearActualValue04 = ISNULL(Month04, 0),
		PriorYearActualValue05 = ISNULL(Month05, 0),
		PriorYearActualValue06 = ISNULL(Month06, 0),
		PriorYearActualValue07 = ISNULL(Month07, 0),
		PriorYearActualValue08 = ISNULL(Month08, 0),
		PriorYearActualValue09 = ISNULL(Month09, 0),
		PriorYearActualValue10 = ISNULL(Month10, 0),
		PriorYearActualValue11 = ISNULL(Month11, 0),
		PriorYearActualValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolumeHistory] cvh
		INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID
		INNER JOIN 
		(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,  
					cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value
				 FROM [int].[FactCDM] cdm 
				 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
				 WHERE cdm.FiscalYearID = @CurrentFiscalYearID - 1 AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0
				   AND cdm.UnitTypeID IN (145)
				 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
			AND cv.UnitTypeID = pv.UnitTypeID
	WHERE
		cv.EntityGroupConfigID = @EntityGroupConfigID

	--update CYB units
	UPDATE
		cvh
	SET
		CurrentYearBudget01 = ISNULL(Month01, 0),
		CurrentYearBudget02 = ISNULL(Month02, 0),
		CurrentYearBudget03 = ISNULL(Month03, 0),
		CurrentYearBudget04 = ISNULL(Month04, 0),
		CurrentYearBudget05 = ISNULL(Month05, 0),
		CurrentYearBudget06 = ISNULL(Month06, 0),
		CurrentYearBudget07 = ISNULL(Month07, 0),
		CurrentYearBudget08 = ISNULL(Month08, 0),
		CurrentYearBudget09 = ISNULL(Month09, 0),
		CurrentYearBudget10 = ISNULL(Month10, 0),
		CurrentYearBudget11 = ISNULL(Month11, 0),
		CurrentYearBudget12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolumeHistory] cvh
		INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID
		INNER JOIN 
		(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,  
					cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value
				 FROM [int].[FactCDM] cdm 
				 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
				 WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 2 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0
				   AND cdm.UnitTypeID = 145 --units
				 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
			AND cv.UnitTypeID = pv.UnitTypeID
	WHERE
		cv.EntityGroupConfigID = @EntityGroupConfigID

END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeInitialDollars
/**************************************************************
** Change History
**************************************************************
** CID  Date			Author		WI			Description
** 1	  2023-02-02   NT     JAZZ-48268  Make change to use the new fp.ChargeVolume (data restructure)
*************************************************************/
CREATE PROCEDURE fp.procSampleChargeVolumeInitialDollars
	@EntityGroupConfigID int,
	@IsEntityUsed BIT,
	@IsPatientClassUsed BIT,
	@MonthsLoaded INT
AS
BEGIN
	
	UPDATE cv
    SET
		-- Initial Budget 
		cv.InitialBudgetDollars01 = cv.InitialBudget01 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars02 = cv.InitialBudget02 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars03 = cv.InitialBudget03 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars04 = cv.InitialBudget04 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars05 = cv.InitialBudget05 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars06 = cv.InitialBudget06 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars07 = cv.InitialBudget07 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars08 = cv.InitialBudget08 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars09 = cv.InitialBudget09 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars10 = cv.InitialBudget10 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars11 = cv.InitialBudget11 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars12 = cv.InitialBudget12 * ISNULL(budgCm.BaselineChargeRate, 0),

		-- Initial Projection 
		cv.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded < 1 THEN  cv.InitialProjection01 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars01 END,
		cv.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded < 2 THEN  cv.InitialProjection02 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars02 END,
		cv.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded < 3 THEN  cv.InitialProjection03 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars03 END,
		cv.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded < 4 THEN  cv.InitialProjection04 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars04 END,
		cv.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded < 5 THEN  cv.InitialProjection05 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars05 END,
		cv.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded < 6 THEN  cv.InitialProjection06 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars06 END,
		cv.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded < 7 THEN  cv.InitialProjection07 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars07 END,
		cv.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded < 8 THEN  cv.InitialProjection08 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars08 END,
		cv.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded < 9 THEN  cv.InitialProjection09 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars09 END,
		cv.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN cv.InitialProjection10 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars10 END,
		cv.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN cv.InitialProjection11 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars11 END,
		cv.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN cv.InitialProjection12 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars12 END,

		--Update ProjectionPrice** (ProjectionDollarsAdjusted** are a computed columns and will automatically reflect this update to ProjectionPrice**)
		cv.ProjectionPrice01 = CASE WHEN @MonthsLoaded < 1 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice01 END,
		cv.ProjectionPrice02 = CASE WHEN @MonthsLoaded < 2 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice02 END,
		cv.ProjectionPrice03 = CASE WHEN @MonthsLoaded < 3 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice03 END,
		cv.ProjectionPrice04 = CASE WHEN @MonthsLoaded < 4 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice04 END,
		cv.ProjectionPrice05 = CASE WHEN @MonthsLoaded < 5 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice05 END,
		cv.ProjectionPrice06 = CASE WHEN @MonthsLoaded < 6 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice06 END,
		cv.ProjectionPrice07 = CASE WHEN @MonthsLoaded < 7 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice07 END,
		cv.ProjectionPrice08 = CASE WHEN @MonthsLoaded < 8 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice08 END,
		cv.ProjectionPrice09 = CASE WHEN @MonthsLoaded < 9 THEN  ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice09 END,
		cv.ProjectionPrice10 = CASE WHEN @MonthsLoaded < 10 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice10 END,
		cv.ProjectionPrice11 = CASE WHEN @MonthsLoaded < 11 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice11 END,
		cv.ProjectionPrice12 = CASE WHEN @MonthsLoaded < 12 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice12 END
    FROM [fp].[ChargeVolume] cv
    LEFT JOIN [fp].[FactChargeMaster] budgCm 
     ON budgCm.BudgetConfigID = cv.BudgetConfigID 
    AND budgCm.ChargeCodeID = cv.ChargeCodeID
    AND budgCm.TimeClassID = 2
	 AND ((@IsEntityUsed = 1 AND budgCm.EntityID = cv.EntityID) OR @IsEntityUsed = 0)
 	 AND ((@IsPatientClassUsed = 1 AND budgCm.PatientClassID = cv.PatientClassID) OR @IsPatientClassUsed = 0);
			
	/*	Commenting this out, instead updating ProijectionPrice** columns up above as these columsn are now computed
	-- Update adjusted values for DollarsProjection table, so that it can be used for months loaded
	UPDATE cv
	SET
		AdjustedValue01 = cvd.InitialProjection01,
		AdjustedValue02 = cvd.InitialProjection02,
		AdjustedValue03 = cvd.InitialProjection03,
		AdjustedValue04 = cvd.InitialProjection04,
		AdjustedValue05 = cvd.InitialProjection05,
		AdjustedValue06 = cvd.InitialProjection06,
		AdjustedValue07 = cvd.InitialProjection07,
		AdjustedValue08 = cvd.InitialProjection08,
		AdjustedValue09 = cvd.InitialProjection09,
		AdjustedValue10 = cvd.InitialProjection10,
		AdjustedValue11 = cvd.InitialProjection11,
		AdjustedValue12 = cvd.InitialProjection12
	FROM [fp].[ChargeVolume] cv 
	WHERE cv.EntityGroupConfigID = @EntityGroupConfigID*/

END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeOriginalBudgetDollars
CREATE PROCEDURE [fp].[procSampleChargeVolumeOriginalBudgetDollars]
	@EntityGroupConfigID int,
	@IsEntityUsed BIT,
	@IsPatientClassUsed BIT
AS
BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   Description
	 ** 1	 2022-09-01	 JB		 JAZZ-32095	Remove Payor and PayorGroupID from joins.
	 ** 2   2023-01-26   NT      JAZZ-48268  Make change to sample charge volume budget data into the new fp.ChargeVolume (data restructure)
	*************************************************************/	 
	-- update the initial values, need to do this separately because initial has already been flexed
	UPDATE cv
    SET
       cv.InitialBudgetDollars01 = cv.InitialBudget01 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars02 = cv.InitialBudget02 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars03 = cv.InitialBudget03 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars04 = cv.InitialBudget04 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars05 = cv.InitialBudget05 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars06 = cv.InitialBudget06 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars07 = cv.InitialBudget07 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars08 = cv.InitialBudget08 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars09 = cv.InitialBudget09 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars10 = cv.InitialBudget10 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars11 = cv.InitialBudget11 * ISNULL(budgCm.BaselineChargeRate, 0),
		cv.InitialBudgetDollars12 = cv.InitialBudget12 * ISNULL(budgCm.BaselineChargeRate, 0)
    FROM [fp].[ChargeVolume] cv
    LEFT JOIN [fp].[FactChargeMaster] budgCm 
        ON  budgCm.BudgetConfigID = cv.BudgetConfigID 
        AND budgCm.ChargeCodeID = cv.ChargeCodeID
        AND budgCm.TimeClassID = 2
		AND ((@IsEntityUsed = 1 AND budgCm.EntityID =cv.EntityID) OR @IsEntityUsed = 0)
		AND ((@IsPatientClassUsed = 1 AND budgCm.PatientClassID = cv.PatientClassID) OR @IsPatientClassUsed = 0)
    WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeOriginalBudgetUnits
CREATE   PROCEDURE [fp].[procSampleChargeVolumeOriginalBudgetUnits]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	 2022-06-06  BK      JAZZ-37271		Add casting so that Initial and Adjusted values match, there were rounding issues before
** 2	 2022-07-28  BK      JAZZ-40950		Remove "Is Service Lines Used" feature flag and use Stats Model on EGC instead
** 3	 2022-12-12	 DM		 JAZZ-46455		Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
** 4     2023-01-26  NT       JAZZ-48268     Make change to sample charge volume budget data into the new fp.ChargeVolume (data restructure)
*************************************************************/

	DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)
	
	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	-- set all of the values from the source fy/tc
	UPDATE
		cv
	SET
		SampledBudget01 = ISNULL(Month01, 0),
		SampledBudget02 = ISNULL(Month02, 0),
		SampledBudget03 = ISNULL(Month03, 0),
		SampledBudget04 = ISNULL(Month04, 0),
		SampledBudget05 = ISNULL(Month05, 0),
		SampledBudget06 = ISNULL(Month06, 0),
		SampledBudget07 = ISNULL(Month07, 0),
		SampledBudget08 = ISNULL(Month08, 0),
		SampledBudget09 = ISNULL(Month09, 0),
		SampledBudget10 = ISNULL(Month10, 0),
		SampledBudget11 = ISNULL(Month11, 0),
		SampledBudget12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolume] cv
		INNER JOIN 
			(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,
					cdm.ChargeCodeID, fm.MonthColumnName, SUM(Value) AS Value
			 FROM [int].[FactCDM] cdm 
			 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
			 WHERE cdm.FiscalYearID = @SourceFiscalYearID 
			   AND cdm.TimeclassID = @SourceTimeClassID 
			   AND cdm.IsDeleted = 0 
			   AND cdm.FiscalMonthID != 0 
			   AND cdm.UnitTypeID = 145 
			   AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
			 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, fm.MonthColumnName
			 ) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS pv
		  	 ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
	WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
	  AND cv.UnitTypeID = 145

	-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data
	IF(@IsAnnualized = 1) 
	BEGIN
	
		DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
		DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
		DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded)
				
		UPDATE
			cv
		SET
			SampledBudget02 = CASE WHEN @MonthsLoaded >= 2  THEN SampledBudget02 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget03 = CASE WHEN @MonthsLoaded >= 3  THEN SampledBudget03 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget04 = CASE WHEN @MonthsLoaded >= 4  THEN SampledBudget04 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget05 = CASE WHEN @MonthsLoaded >= 5  THEN SampledBudget05 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget06 = CASE WHEN @MonthsLoaded >= 6  THEN SampledBudget06 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget07 = CASE WHEN @MonthsLoaded >= 7  THEN SampledBudget07 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget08 = CASE WHEN @MonthsLoaded >= 8  THEN SampledBudget08 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget09 = CASE WHEN @MonthsLoaded >= 9  THEN SampledBudget09 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget10 = CASE WHEN @MonthsLoaded >= 10 THEN SampledBudget10 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget11 = CASE WHEN @MonthsLoaded >= 11 THEN SampledBudget11 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END,
			SampledBudget12 = CASE WHEN @MonthsLoaded >= 12 THEN SampledBudget12 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END
		FROM [fp].[ChargeVolume] cv
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID	
		  AND cv.UnitTypeID = 145
	END
	
	IF ((SELECT StatisticsModel FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) = 0)  -- StatisticsModel "0" is SL->CV->Stats, so using Service Lines
	BEGIN
		-- If we're using Service Lines we need to update the baseline.
		DECLARE @BudgetConfigID INT = (SELECT bc.BudgetConfigID 
											   FROM [fp].[EntityGroupConfig] ec
											   	INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID
											   WHERE EntityGroupConfigID = @EntityGroupConfigID)
	
			;WITH ServiceLineEncounters AS (
				SELECT
					EntityID,
					PatientClassID,
					ServiceLineID,
					AgeCohortID,
					MedicalSurgicalID,
					SUM(TargetAdjusted01) AS TargetAdjusted01, 
					SUM(TargetAdjusted02) AS TargetAdjusted02, 
					SUM(TargetAdjusted03) AS TargetAdjusted03, 
					SUM(TargetAdjusted04) AS TargetAdjusted04, 
					SUM(TargetAdjusted05) AS TargetAdjusted05, 
					SUM(TargetAdjusted06) AS TargetAdjusted06, 
					SUM(TargetAdjusted07) AS TargetAdjusted07,
					SUM(TargetAdjusted08) AS TargetAdjusted08, 
					SUM(TargetAdjusted09) AS TargetAdjusted09, 
					SUM(TargetAdjusted10) AS TargetAdjusted10, 
					SUM(TargetAdjusted11) AS TargetAdjusted11, 
					SUM(TargetAdjusted12) AS TargetAdjusted12,
					SUM(InitialBudgetTotal) AS InitialBudgetTotal
				FROM [fp].[ServiceLineEncounter] fsle
				WHERE
					fsle.BudgetConfigID = @BudgetConfigID
				GROUP BY 
					EntityID,
					PatientClassID,
					ServiceLineID,
					AgeCohortID,
					MedicalSurgicalID
			)
			UPDATE fcv
			SET -- note that I tried other combinations of not using this ridiculous casting and they did not return the same rate value as the saved rate, so this is required. For more info see https://jira.sdt.local/browse/JAZZ-37271
			fcv.InitialBudget01 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted01), 0),
			fcv.InitialBudget02 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted02), 0),
			fcv.InitialBudget03 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted03), 0),
			fcv.InitialBudget04 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted04), 0),
			fcv.InitialBudget05 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted05), 0),
			fcv.InitialBudget06 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted06), 0),
			fcv.InitialBudget07 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted07), 0),
			fcv.InitialBudget08 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted08), 0),
			fcv.InitialBudget09 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted09), 0),
			fcv.InitialBudget10 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted10), 0),
			fcv.InitialBudget11 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted11), 0),
			fcv.InitialBudget12 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted12), 0)
			FROM [fp].[ChargeVolume] fcv
				INNER JOIN ServiceLineEncounters sle 
					ON fcv.AgeCohortID = sle.AgeCohortID
					AND fcv.MedicalSurgicalID = sle.MedicalSurgicalID 
					AND fcv.PatientClassID = sle.PatientClassID
					AND fcv.ServiceLineID = sle.ServiceLineID 
					AND fcv.EntityID = sle.EntityID
			WHERE 
				fcv.BudgetConfigID = @BudgetConfigID
				AND fcv.UnitTypeID = 145	
		
	END ELSE BEGIN
		-- update the initial values to be equal to the sampled values
		UPDATE
			cv
		SET
			InitialBudget01 = SampledBudgetTotal / 12,
			InitialBudget02 = SampledBudgetTotal / 12,
			InitialBudget03 = SampledBudgetTotal / 12,
			InitialBudget04 = SampledBudgetTotal / 12,
			InitialBudget05 = SampledBudgetTotal / 12,
			InitialBudget06 = SampledBudgetTotal / 12,
			InitialBudget07 = SampledBudgetTotal / 12,
			InitialBudget08 = SampledBudgetTotal / 12,
			InitialBudget09 = SampledBudgetTotal / 12,
			InitialBudget10 = SampledBudgetTotal / 12,
			InitialBudget11 = SampledBudgetTotal / 12,
			InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) +
							 				             (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + 
												          (SampledBudgetTotal / 12)) 
		FROM [fp].[ChargeVolume] cv
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID AND cv.UnitTypeID = 145
	END
END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeOriginalProjectionDollars
CREATE   PROCEDURE [fp].[procSampleChargeVolumeOriginalProjectionDollars]
	@EntityGroupConfigID int,
	@IsEntityUsed BIT,
	@IsPatientClassUsed BIT,
	@CurrentYear INT,
	@MonthsLoaded INT
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-12-12	 DM		JAZZ-46455		Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
** 2    2023-01-26   NT     JAZZ-48268  Make change to sample charge volume budget data into the new fp.ChargeVolume (data restructure)
*************************************************************/

	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	-- Need to set the dollars based on the actual YTD
	UPDATE
		cv
	SET
		InitialProjectionDollars01 = ISNULL(Month01, 0),
		InitialProjectionDollars02 = ISNULL(Month02, 0),
		InitialProjectionDollars03 = ISNULL(Month03, 0),
		InitialProjectionDollars04 = ISNULL(Month04, 0),
		InitialProjectionDollars05 = ISNULL(Month05, 0),
		InitialProjectionDollars06 = ISNULL(Month06, 0),
		InitialProjectionDollars07 = ISNULL(Month07, 0),
		InitialProjectionDollars08 = ISNULL(Month08, 0),
		InitialProjectionDollars09 = ISNULL(Month09, 0),
		InitialProjectionDollars10 = ISNULL(Month10, 0),
		InitialProjectionDollars11 = ISNULL(Month11, 0),
		InitialProjectionDollars12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolume] cv
		INNER JOIN 
			(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, 
					cdm.ChargeCodeID, fm.MonthColumnName, SUM(Value) AS Value
			 FROM [int].[FactCDM] cdm 
			 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
			 WHERE cdm.FiscalYearID = @CurrentYear 
			 	AND cdm.TimeclassID = 1
				AND cdm.IsDeleted = 0 
				AND cdm.FiscalMonthID != 0 
				AND cdm.UnitTypeID = 34
			 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
	WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
		
	-- update the initial values. Need to do this separate because Initial could have already been flexed by SLV
   UPDATE cv
   SET
      	cv.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded < 1  THEN cv.InitialProjection01 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars01 END,
		cv.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded < 2  THEN cv.InitialProjection02 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars02 END,
		cv.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded < 3  THEN cv.InitialProjection03 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars03 END,
		cv.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded < 4  THEN cv.InitialProjection04 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars04 END,
		cv.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded < 5  THEN cv.InitialProjection05 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars05 END,
		cv.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded < 6  THEN cv.InitialProjection06 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars06 END,
		cv.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded < 7  THEN cv.InitialProjection07 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars07 END,
		cv.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded < 8  THEN cv.InitialProjection08 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars08 END,
		cv.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded < 9  THEN cv.InitialProjection09 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars09 END,
		cv.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN cv.InitialProjection10 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars10 END,
		cv.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN cv.InitialProjection11 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars11 END,
		cv.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN cv.InitialProjection12 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars12 END
    FROM [fp].[ChargeVolume] cv
	LEFT JOIN [fp].[FactChargeMaster] projCm 
        ON  projCm.BudgetConfigID = cv.BudgetConfigID 
        AND projCm.ChargeCodeID = cv.ChargeCodeID
        AND projCm.TimeClassID = 12
		AND ((@IsEntityUsed = 1 AND projCm.EntityID = cv.EntityID) OR @IsEntityUsed = 0)
		AND ((@IsPatientClassUsed = 1 AND projCm.PatientClassID = cv.PatientClassID) OR @IsPatientClassUsed = 0)
    WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
		
END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeOriginalProjectionUnits
CREATE   PROCEDURE [fp].[procSampleChargeVolumeOriginalProjectionUnits]
	@EntityGroupConfigID INT,
	@CurrentFiscalYearID SMALLINT,
	@MonthsLoaded INT
AS
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID  Date         Author  WI				Description
** 1	2022-12-12	 DM		 JAZZ-46455		Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
** 2    2023-01-27   NT      JAZZ-48268	    Make change to sample charge volume projection data into the new fp.ChargeVolume (data restructure)
** 3    2023-07-27   MY      JAZZ-58113	    Update non-DSS CV sampling to flex InitialProjection by SLE if using
*************************************************************/

	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID)
	DECLARE @IsFlexInitialProjectionByEncounter BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Flex Initial Projection ChargeVolume by Encounters' AND BudgetConfigID = @BudgetConfigID), 0)

	-- set the orig values for the months where we have data (month sort order <= @MonthsLoaded)
	UPDATE
		cv
	SET
		SampledProjection01 = ISNULL(Month01, 0),
		SampledProjection02 = ISNULL(Month02, 0),
		SampledProjection03 = ISNULL(Month03, 0),
		SampledProjection04 = ISNULL(Month04, 0),
		SampledProjection05 = ISNULL(Month05, 0),
		SampledProjection06 = ISNULL(Month06, 0),
		SampledProjection07 = ISNULL(Month07, 0),
		SampledProjection08 = ISNULL(Month08, 0),
		SampledProjection09 = ISNULL(Month09, 0),
		SampledProjection10 = ISNULL(Month10, 0),
		SampledProjection11 = ISNULL(Month11, 0),
		SampledProjection12 = ISNULL(Month12, 0)
	FROM
		[fp].[ChargeVolume] cv
		INNER JOIN 
			(SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, 
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID,
					cdm.ChargeCodeID, fm.MonthColumnName, SUM(Value) AS Value
				 FROM [int].[FactCDM] cdm 
				 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID
				 WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded AND cdm.UnitTypeID = 145
				 GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON cv.DepartmentID = pv.DepartmentID
			AND cv.ServiceLineID = pv.ServiceLineID
			AND cv.PatientClassID = pv.PatientClassID
			AND cv.AgeCohortID = pv.AgeCohortID
			AND cv.MedicalSurgicalID = pv.MedicalSurgicalID
			AND cv.ChargeCodeID = pv.ChargeCodeID
	WHERE
		cv.EntityGroupConfigID = @EntityGroupConfigID
		AND cv.UnitTypeID = 145
		
	-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	-- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize
	UPDATE
		cv
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END,
		SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END
	FROM
		[fp].[ChargeVolume] cv
	WHERE
		cv.EntityGroupConfigID = @EntityGroupConfigID AND cv.UnitTypeID = 145

	IF @IsFlexInitialProjectionByEncounter = 1 
	BEGIN -- FF On
		IF OBJECT_ID('tempdb..#tbl_entitygroup') IS NOT NULL DROP TABLE #tbl_entitygroup;
        IF OBJECT_ID('tempdb..#sle') IS NOT NULL DROP TABLE #sle;

	    CREATE TABLE #tbl_entitygroup (EntityGroupConfigID INT, IsAnnualized INT);

	    CREATE TABLE #sle  (EntityID INT, PatientClassID INT, ServiceLineID INT, AgeCohortID INT, MedicalSurgicalID INT, MSDRGID INT, CPTID INT, ProviderID INT,
			InitialProjection01 DECIMAL(19,8),InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8),
			InitialProjection07 DECIMAL(19,8),InitialProjection08 DECIMAL(19,8), InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8),
			InitialProjectionTotal DECIMAL(30,8), MonthsLoadedTotal DECIMAL(30,8));
			
	    INSERT INTO #tbl_entitygroup (EntityGroupConfigID, IsAnnualized)
	    SELECT EntityGroupConfigID, CASE WHEN ServiceLineEncounterTimeClassID = 1 AND ServiceLineEncounterFiscalYearID = @CurrentFiscalYearID THEN 1 ELSE 0 END
	    FROM [fp].[EntityGroupConfig] egc 
			INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID 
	    WHERE bc.BudgetConfigID = @BudgetConfigID

        -- Set Initial to Sampled values
        UPDATE
		    cv
	    SET
			InitialProjection01 = SampledProjection01,  
			InitialProjection02 = SampledProjection02,
			InitialProjection03 = SampledProjection03,
			InitialProjection04 = SampledProjection04,
			InitialProjection05 = SampledProjection05,
			InitialProjection06 = SampledProjection06,
			InitialProjection07 = SampledProjection07,
			InitialProjection08 = SampledProjection08,
			InitialProjection09 = SampledProjection09,
			InitialProjection10 = SampledProjection10,
			InitialProjection11 = SampledProjection11,
			InitialProjection12 = SampledProjection12
        FROM [fp].[ChargeVolume] cv 
	    WHERE cv.EntityGroupConfigID = @EntityGroupConfigID; 

        -- Now update months not loaded using SLE flexing
        INSERT INTO #sle (EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID,
                InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06,
                InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
                InitialProjectionTotal, MonthsLoadedTotal)
		SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID,
			SUM(InitialProjection01) AS InitialProjection01, SUM(InitialProjection02) AS InitialProjection02, SUM(InitialProjection03) AS InitialProjection03, 
			SUM(InitialProjection04) AS InitialProjection04, SUM(InitialProjection05) AS InitialProjection05, SUM(InitialProjection06) AS InitialProjection06, 
			SUM(InitialProjection07) AS InitialProjection07, SUM(InitialProjection08) AS InitialProjection08, SUM(InitialProjection09) AS InitialProjection09, 
			SUM(InitialProjection10) AS InitialProjection10, SUM(InitialProjection11) AS InitialProjection11, SUM(InitialProjection12) AS InitialProjection12,
			SUM(InitialProjectionTotal) AS InitialProjectionTotal, 
			CASE WHEN @MonthsLoaded = 1  THEN SUM(sle.InitialProjection01)
					 WHEN @MonthsLoaded = 2  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02) 
					 WHEN @MonthsLoaded = 3  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03)
					 WHEN @MonthsLoaded = 4  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04)
					 WHEN @MonthsLoaded = 5  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05)
					 WHEN @MonthsLoaded = 6  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06)
					 WHEN @MonthsLoaded = 7  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07)
					 WHEN @MonthsLoaded = 8  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08)
					 WHEN @MonthsLoaded = 9  THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09)
					 WHEN @MonthsLoaded = 10 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09 + sle.InitialProjection10) 
					 WHEN @MonthsLoaded = 11 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09 + sle.InitialProjection10 + sle.InitialProjection11)
					 WHEN @MonthsLoaded = 12 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09 + sle.InitialProjection10 + sle.InitialProjection11 + sle.InitialProjection12)			
			END AS MonthsLoadedTotal
		FROM [fp].[ServiceLineEncounter] sle
		WHERE
			sle.BudgetConfigID = @BudgetConfigID
		GROUP BY 
			EntityID,
			PatientClassID,
			ServiceLineID,
			AgeCohortID,
			MedicalSurgicalID,
            MSDRGID,
            CPTID,
            ProviderID
			       
		-- Non-annualized
	    IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 0) 
		BEGIN		
			-- Next we need to flex the Initial Projection months not loaded
			-- Calculation: (Charges (Months Loaded) / Encounters (Months Loaded)) * Initial Projection Charges by Month
			-- This is essentially calculating the Charge Per Encounter and the flexing it. This is similar to how we'd do it in Statistics or other sections
			-- except we aren't storing the rate (in the future we probably should update this to be like stats)
			UPDATE cv
			SET 
				cv.InitialProjection01 = cv.InitialProjection01,
				cv.InitialProjection02 = CASE WHEN @MonthsLoaded < 2  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection02), 0) ELSE cv.InitialProjection02 END,
                cv.InitialProjection03 = CASE WHEN @MonthsLoaded < 3  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection03), 0) ELSE cv.InitialProjection03 END,
                cv.InitialProjection04 = CASE WHEN @MonthsLoaded < 4  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection04), 0) ELSE cv.InitialProjection04 END,
                cv.InitialProjection05 = CASE WHEN @MonthsLoaded < 5  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection05), 0) ELSE cv.InitialProjection05 END,
                cv.InitialProjection06 = CASE WHEN @MonthsLoaded < 6  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection06), 0) ELSE cv.InitialProjection06 END,
                cv.InitialProjection07 = CASE WHEN @MonthsLoaded < 7  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection07), 0) ELSE cv.InitialProjection07 END,
                cv.InitialProjection08 = CASE WHEN @MonthsLoaded < 8  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection08), 0) ELSE cv.InitialProjection08 END,
                cv.InitialProjection09 = CASE WHEN @MonthsLoaded < 9  THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection09), 0) ELSE cv.InitialProjection09 END,
                cv.InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection10), 0) ELSE cv.InitialProjection10 END,
                cv.InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection11), 0) ELSE cv.InitialProjection11 END,
                cv.InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection12), 0) ELSE cv.InitialProjection12 END
           FROM [fp].[ChargeVolume] cv
				INNER JOIN #sle sle 
					ON  cv.ServiceEntityID = sle.EntityID
                    AND cv.PatientClassID = sle.PatientClassID
                    AND cv.ServiceLineID = sle.ServiceLineID
                    AND cv.AgeCohortID = sle.AgeCohortID
					AND cv.MedicalSurgicalID = sle.MedicalSurgicalID 
                    AND cv.MSDRGID = sle.MSDRGID
                    AND cv.PrimaryCPTID = sle.CPTID
					AND cv.ServiceProviderID = sle.ProviderID
                INNER JOIN #tbl_entitygroup egc ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
			WHERE cv.BudgetConfigID = @BudgetConfigID 
				AND egc.IsAnnualized = 0;
        END

        -- Annualized
	    IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 1) 
		BEGIN
		
			EXEC [dbo].[procSysDropTempTable] '#chargeMonthsLoaded'

			SELECT
				cv.ChargeVolumeID,
				CASE WHEN @MonthsLoaded = 1  THEN SUM(cv.InitialProjection01)
					 WHEN @MonthsLoaded = 2  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02) 
					 WHEN @MonthsLoaded = 3  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03)
					 WHEN @MonthsLoaded = 4  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04)
					 WHEN @MonthsLoaded = 5  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05)
					 WHEN @MonthsLoaded = 6  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06)
					 WHEN @MonthsLoaded = 7  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07)
					 WHEN @MonthsLoaded = 8  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08)
					 WHEN @MonthsLoaded = 9  THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09)
					 WHEN @MonthsLoaded = 10 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09 + cv.InitialProjection10) 
					 WHEN @MonthsLoaded = 11 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09 + cv.InitialProjection10 + cv.InitialProjection11)
					 WHEN @MonthsLoaded = 12 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09 + cv.InitialProjection10 + cv.InitialProjection11 + cv.InitialProjection12)			
				END AS MonthsLoadedTotal
			INTO #chargeMonthsLoaded
			FROM [fp].[ChargeVolume] cv
				INNER JOIN #sle sle 
					ON  cv.ServiceEntityID = sle.EntityID
                    AND cv.PatientClassID = sle.PatientClassID
                    AND cv.ServiceLineID = sle.ServiceLineID
                    AND cv.AgeCohortID = sle.AgeCohortID
					AND cv.MedicalSurgicalID = sle.MedicalSurgicalID 
                    AND cv.MSDRGID = sle.MSDRGID
                    AND cv.PrimaryCPTID = sle.CPTID
					AND cv.ServiceProviderID = sle.ProviderID
				INNER JOIN #tbl_entitygroup egc ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
			WHERE cv.BudgetConfigID = @BudgetConfigID 
				AND egc.IsAnnualized = 1
			GROUP BY cv.ChargeVolumeID;

			-- Next we need to flex the Initial Projection months not loaded
			-- Calculation: (Initial Charges (Months Loaded) / Initial Encounters (Months Loaded)) * Initial Projection Charges by Month
			-- This is essentially calculating the Charge Per Encounter and the flexing it. This is similar to how we'd do it in Statistics or other sections
			-- except we aren't storing the rate (in the future we probably should update this to be like stats)
            UPDATE cv
			SET 
				cv.InitialProjection01 = cv.InitialProjection01,
				cv.InitialProjection02 = CASE WHEN @MonthsLoaded < 2   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection02), 0) ELSE cv.InitialProjection02 END,
				cv.InitialProjection03 = CASE WHEN @MonthsLoaded < 3   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection03), 0) ELSE cv.InitialProjection03 END,
				cv.InitialProjection04 = CASE WHEN @MonthsLoaded < 4   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection04), 0) ELSE cv.InitialProjection04 END,
				cv.InitialProjection05 = CASE WHEN @MonthsLoaded < 5   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection05), 0) ELSE cv.InitialProjection05 END,
				cv.InitialProjection06 = CASE WHEN @MonthsLoaded < 6   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection06), 0) ELSE cv.InitialProjection06 END,
				cv.InitialProjection07 = CASE WHEN @MonthsLoaded < 7   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection07), 0) ELSE cv.InitialProjection07 END,
				cv.InitialProjection08 = CASE WHEN @MonthsLoaded < 8   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection08), 0) ELSE cv.InitialProjection08 END,
				cv.InitialProjection09 = CASE WHEN @MonthsLoaded < 9   THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection09), 0) ELSE cv.InitialProjection09 END,
				cv.InitialProjection10 = CASE WHEN @MonthsLoaded < 10  THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection10), 0) ELSE cv.InitialProjection10 END,
				cv.InitialProjection11 = CASE WHEN @MonthsLoaded < 11  THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection11), 0) ELSE cv.InitialProjection11 END,
				cv.InitialProjection12 = CASE WHEN @MonthsLoaded < 12  THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection12), 0) ELSE cv.InitialProjection12 END
            FROM [fp].[ChargeVolume] cv
				INNER JOIN #chargeMonthsLoaded cml ON cv.ChargeVolumeID = cml.ChargeVolumeID
				INNER JOIN #sle sle 
					ON  cv.ServiceEntityID = sle.EntityID
                    AND cv.PatientClassID = sle.PatientClassID
                    AND cv.ServiceLineID = sle.ServiceLineID
                    AND cv.AgeCohortID = sle.AgeCohortID
					AND cv.MedicalSurgicalID = sle.MedicalSurgicalID 
                    AND cv.MSDRGID = sle.MSDRGID
                    AND cv.PrimaryCPTID = sle.CPTID
					AND cv.ServiceProviderID = sle.ProviderID
                INNER JOIN #tbl_entitygroup egc 
			                    ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
			WHERE 
				cv.BudgetConfigID = @BudgetConfigID AND egc.IsAnnualized = 1;
		END
	END ELSE 
	BEGIN -- FF Off

		CREATE TABLE #Totals (ChargeVolumeID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8));	
		INSERT INTO #Totals (ChargeVolumeID, SampledProjectionTotal)
		SELECT ChargeVolumeID, 
			CASE WHEN @MonthsLoaded = 11 THEN cv.SampledProjection12  
					WHEN @MonthsLoaded = 10 THEN cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 9 THEN cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 8 THEN cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 7 THEN cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 6 THEN cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 5 THEN cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 4 THEN cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 3 THEN cv.SampledProjection04 + cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10  + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 2 THEN cv.SampledProjection03 + cv.SampledProjection04 + cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12
					WHEN @MonthsLoaded = 1 THEN cv.SampledProjection02 + cv.SampledProjection03 + cv.SampledProjection04 + cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12  
			 		ELSE 0
				END
			FROM [fp].[ChargeVolume] cv
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID
			AND cv.UnitTypeID = 145
	      
		UPDATE a 
		SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded)
		FROM #Totals a 
					
		UPDATE cv
		SET
			InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN cv.SampledProjection01 ELSE NewValue END,
			InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN cv.SampledProjection02 ELSE NewValue END,
			InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN cv.SampledProjection03 ELSE NewValue END,
			InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN cv.SampledProjection04 ELSE NewValue END,
			InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN cv.SampledProjection05 ELSE NewValue END,
			InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN cv.SampledProjection06 ELSE NewValue END,
			InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN cv.SampledProjection07 ELSE NewValue END,
			InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN cv.SampledProjection08 ELSE NewValue END,
			InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN cv.SampledProjection09 ELSE NewValue END,
			InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN cv.SampledProjection10 ELSE NewValue END,
			InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN cv.SampledProjection11 ELSE NewValue END,
			InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN cv.SampledProjection12 ELSE NewValue END
		FROM [fp].[ChargeVolume] cv INNER JOIN #Totals t on cv.ChargeVolumeID = t.ChargeVolumeID
		WHERE cv.EntityGroupConfigID  = @EntityGroupConfigID 
			AND cv.UnitTypeID = 145

	END

END
GO


---------------------------------------------

-- fp.procSampleChargeVolumeProjectionData
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1    2023-01-31   NT     JAZZ-48268   Make change to use the new fp.ChargeVolume (data restructure)
*************************************************************/
CREATE PROCEDURE [fp].[procSampleChargeVolumeProjectionData]
	@EntityGroupConfigID int
AS
BEGIN

	UPDATE
			cv
		SET
			ProjectionAdjusted01 = InitialProjection01,
			ProjectionAdjusted02 = InitialProjection02,
			ProjectionAdjusted03 = InitialProjection03,
			ProjectionAdjusted04 = InitialProjection04,
			ProjectionAdjusted05 = InitialProjection05,
			ProjectionAdjusted06 = InitialProjection06,
			ProjectionAdjusted07 = InitialProjection07,
			ProjectionAdjusted08 = InitialProjection08,
			ProjectionAdjusted09 = InitialProjection09,
			ProjectionAdjusted10 = InitialProjection10,
			ProjectionAdjusted11 = InitialProjection11,
			ProjectionAdjusted12 = InitialProjection12
		FROM [fp].[ChargeVolume] cv
		WHERE cv.EntityGroupConfigID = @EntityGroupConfigID 
		  AND cv.UnitTypeID = 145
		  AND IsNew = 0
	
END
GO


---------------------------------------------

-- fp.procSampleDependentStatisticsByDriverStatisticsRates
CREATE   PROCEDURE [fp].[procSampleDependentStatisticsByDriverStatisticsRates]
	@BudgetConfigID INT,
	@CurrentFiscalYearID SMALLINT,
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI			    Description
	 ** 1 	 12-14-2020  MY  	 JAZZ-11324 	Initial
	 ** 2 	 2021-02-18  BK  	JAZZ-15007		Add distinct to fix flexing inflation problem
	 ** 3 	 2022-09-12  BK  	JAZZ-43016		Add provider FF to sample rates
	 ** 4 	 2022-06-20  MY  	JAZZ-53443		Update stats sampling for cross department stats flexing
	 ** 5 	 2023-09-19  JB  	JAZZ-59196		Remove FF Dependent Statistics Flex By Provider
	 ** 6 	 2024-10-01  MY  	JAZZ-77827		Dependent Stat with multiple Drivers is causing inflated rates
	 *************************************************************/
	 	
	IF OBJECT_ID('tempdb..#entityGroupConfig') IS NOT NULL DROP TABLE #entityGroupConfig
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment 
	IF OBJECT_ID('tempdb..#filteredFlexConfigTable') IS NOT NULL DROP TABLE #filteredFlexConfigTable 
	IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers 
	IF OBJECT_ID('tempdb..#rolledUpDrivers') IS NOT NULL DROP TABLE #rolledUpDrivers 
	IF OBJECT_ID('tempdb..#dependents') IS NOT NULL DROP TABLE #dependents 

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'),
			@Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent')

	-- JAZZ-77827: Dependent Stat with multiple Drivers not working as expected
	DECLARE @IsDriverCalculationFixEnabled BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting 
		WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enabled Multiple Driver Fix for Dependent Statistics Flexing'), 0)

	-- Unlike other rate sampling, we can just use the sampled values. In other rates, we need to typically use the baseline of what we're flexing
	-- so we can compare apples to apples. You wouldn't want to compare 2018 Actuals to 2017 Budget for example. Stats is unique because we're doing
	-- stats to stats so they'll always have the same baseline because flexing is inter-department. Because of this, we need to break out annualization based
	-- on the entity group config since if one department uses annualization, it doesn't mean another one would.	
	CREATE TABLE #entityGroupConfig (
		EntityGroupConfigID INT NOT NULL,
		IsAnnualized BIT NOT NULL
	);

	INSERT INTO #entityGroupConfig (EntityGroupConfigID, IsAnnualized)
	SELECT
		EntityGroupConfigID, 
		CASE WHEN egc.StatisticsFiscalYearID = @CurrentFiscalYearID AND egc.StatisticsTimeClassID = 1 THEN 1 ELSE 0 END
	FROM fp.EntityGroupConfig egc
		INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID

	CREATE TABLE #filteredFlexConfigTable (
		DepartmentID INT NOT NULL,
		DriverAccountID INT NOT NULL,
		DependentAccountID INT NOT NULL,
		SourceDepartmentID INT NOT NULL
	);

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #filteredFlexConfigTable (DepartmentID, DriverAccountID, DependentAccountID, SourceDepartmentID)
		SELECT DISTINCT
			fcm.DepartmentID,
			StatAccountID,
			DependentStatisticAccountID,
			fcm.SourceDepartmentID
		FROM fp.FlexConfigMapping fcm
			INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fcm.DepartmentID
			INNER JOIN fp.EntityGroupConfig egc ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID
			INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE BudgetConfigID = @BudgetConfigID
			AND FlexingTypeID = 8
	END ELSE BEGIN
		INSERT INTO #filteredFlexConfigTable (DepartmentID, DriverAccountID, DependentAccountID, SourceDepartmentID)
		SELECT DISTINCT
			fcm.DepartmentID,
			StatAccountID,
			DependentStatisticAccountID,
			fcm.SourceDepartmentID
		FROM fp.FlexConfigMapping fcm
			INNER JOIN fp.EntityGroupConfig egc ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID
			INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE BudgetConfigID = @BudgetConfigID
			AND FlexingTypeID = 8
	END

	-- 1. For statistics rates we calculate it by taking the total dependent stats / driver stats. We do it to the initial budget so that
	-- it can be used within the engine after a configuration change. Sampled $/UOS doesn't really matter as it can change with each configuration change.
	-- 2. Projection rates should match the budget rates (this is the same for other flexing types)
    -- 3. Calculate the stats for each Department/Account that is setup to be flexed by stats
	-- 4. Rates DO NOT vary by month

	-- Drivers
    -- Calculate the stats for each Department/Account that is setup to be flexed by stats
	CREATE TABLE #drivers (DepartmentID INT, SourceDepartmentID INT, DependentAccountID INT, ProviderID INT, SampledBudgetTotal DECIMAL(19,8))
	CREATE TABLE #dependents (DepartmentID INT, DependentAccountID INT, ProviderID INT, SampledBudgetTotal DECIMAL(19,8))

	INSERT INTO #drivers (DepartmentID, SourceDepartmentID, DependentAccountID, ProviderID, SampledBudgetTotal)
	SELECT 
		map.DepartmentID,
		map.SourceDepartmentID,
		map.DependentAccountID,
		stat.ProviderID,
		(SUM(CASE WHEN  1 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END + 
				CASE WHEN  2 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END + 
				CASE WHEN  3 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END + 
				CASE WHEN  4 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END + 
				CASE WHEN  5 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END + 
				CASE WHEN  6 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END + 
				CASE WHEN  7 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END + 
				CASE WHEN  8 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END + 
				CASE WHEN  9 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END + 
				CASE WHEN 10 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END + 
				CASE WHEN 11 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END + 
				CASE WHEN 12 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal -- If it's annualized we still only want the months loaded.
	FROM #filteredFlexConfigTable map
		INNER JOIN fp.FactStatistics stat ON map.SourceDepartmentID = stat.DepartmentID AND map.DriverAccountID = stat.AccountID AND stat.SubsectionID = @Driver
		INNER JOIN #entityGroupConfig egc ON stat.EntityGroupConfigID = egc.EntityGroupConfigID
	GROUP BY
		map.DepartmentID, map.SourceDepartmentID, map.DependentAccountID, stat.ProviderID
		
	CREATE TABLE #dependentMapping (
		DepartmentID INT,
		DriverAccountID INT,
		DependentAccountID INT
	)

	IF @IsDriverCalculationFixEnabled = 1
	BEGIN
		INSERT INTO #dependentMapping (DepartmentID, DriverAccountID, DependentAccountID)
		SELECT DISTINCT DepartmentID, 0 AS DriverAccountID, DependentAccountID FROM #filteredFlexConfigTable
	END ELSE BEGIN
		INSERT INTO #dependentMapping (DepartmentID, DriverAccountID, DependentAccountID)
		SELECT DISTINCT DepartmentID, DriverAccountID, DependentAccountID FROM #filteredFlexConfigTable
	END

	-- Dependents
	-- We just need to find the specific dependent values so we can take the previous temp table to calculate a rate
	INSERT INTO #dependents (DepartmentID, DependentAccountID, ProviderID, SampledBudgetTotal)
	SELECT 
		map.DepartmentID,
		map.DependentAccountID, stat.ProviderID,
		(SUM(CASE WHEN  1 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END + 
			 CASE WHEN  2 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END + 
			 CASE WHEN  3 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END + 
			 CASE WHEN  4 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END + 
			 CASE WHEN  5 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END + 
			 CASE WHEN  6 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END + 
			 CASE WHEN  7 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END + 
			 CASE WHEN  8 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END + 
			 CASE WHEN  9 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END + 
			 CASE WHEN 10 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END + 
			 CASE WHEN 11 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END + 
			 CASE WHEN 12 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal -- If it's annualized we still only wants the months loaded.
	FROM #dependentMapping map
		INNER JOIN fp.FactStatistics stat ON map.DepartmentID = stat.DepartmentID AND map.DependentAccountID = stat.AccountID AND stat.SubsectionID = @Dependent
		INNER JOIN #entityGroupConfig egc ON stat.EntityGroupConfigID = egc.EntityGroupConfigID
	GROUP BY
		map.DepartmentID, map.DependentAccountID, stat.ProviderID		
	
	-- Once we get the driver data by source department, we need to roll it up for regular department so the calculation works correctly
	SELECT 
		DepartmentID,
		DependentAccountID,
		ProviderID,
		SUM(SampledBudgetTotal) AS SampledBudgetTotal
	INTO #rolledUpDrivers
	FROM #drivers
	GROUP BY
		DepartmentID, 
		DependentAccountID, 
		ProviderID

	IF (@IsDebug = 0)
	BEGIN
		-- Set the rate values on statistics table
	    UPDATE
			stat
		SET
			InitialBudgetRate01 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate02 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate03 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate04 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate05 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate06 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate07 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate08 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate09 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate10 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate11 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialBudgetRate12 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			
			-- Projection rates should match the budget rates and use the budget baseline to calculate
			InitialProjectionRate01 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate02 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate03 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate04 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate05 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate06 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate07 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate08 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate09 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate10 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate11 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0),
			InitialProjectionRate12 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0)
		FROM
			[fp].[FactStatistics] stat
			INNER JOIN #rolledUpDrivers driver ON stat.DepartmentID = driver.DepartmentID AND stat.AccountID = driver.DependentAccountID and stat.ProviderID = driver.ProviderID
			INNER JOIN #dependents [dependent] ON stat.DepartmentID = [dependent].DepartmentID AND stat.AccountID = [dependent].DependentAccountID and stat.ProviderID = [dependent].ProviderID
		WHERE driver.ProviderID = [dependent].ProviderID
			AND	stat.UnitTypeID = 140
			AND stat.BudgetConfigID = @BudgetConfigID
			AND (
					stat.InitialBudgetRate01 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate02 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate03 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate04 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate05 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate06 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate07 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate08 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate09 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate10 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate11 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialBudgetRate12 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR				
					stat.InitialProjectionRate01 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate02 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate03 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate04 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate05 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate06 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate07 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate08 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate09 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate10 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate11 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR 
					stat.InitialProjectionRate12 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0))
	END ELSE BEGIN
		SELECT 'filteredFlexConfigTable', * FROM #filteredFlexConfigTable
		SELECT 'entityGroupConfig', * FROM #entityGroupConfig
		SELECT 'drivers', * FROM #drivers
		SELECT 'FilterByDepartment', * FROM #FilterByDepartment
		SELECT 'dependents', * FROM #dependents
		SELECT 'rolledUpDrivers', * FROM #rolledUpDrivers
	END
		
END
GO


---------------------------------------------

-- fp.procSampleEncountersToReimbursement
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author WI            Description
** 1    2022-02-04	MY     JAZZ-31904    Initial
** 2    2022-06-15	MY     JAZZ-37901    Create Fix Change History Process for Reimbursement
** 3    2022-09-29	BW     JAZZ-43894    Update to join on projection with budget phase 2
** 4    2023-01-17  BK     JAZZ-48267    New data structure
** 5    2023-11-15  BK     JAZZ-62974    Fix issue with Encounters not being pushed to Reimbursement because of missing Charges data
** 6    2024-01-11  AO     JAZZ-64530	 Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE PROCEDURE [fp].[procSampleEncountersToReimbursement]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	DECLARE @IsMedicalSurgicalUsed BIT,
			@IsMsdrgUsed BIT,
			@IsCptUsed BIT

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'PrimaryCPTID'

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters;
	IF OBJECT_ID('tempdb..#projectionBasisIDs') IS NOT NULL DROP TABLE #projectionBasisIDs
	IF OBJECT_ID('tempdb..#budgetBasisIDs') IS NOT NULL DROP TABLE #budgetBasisIDs
	
	CREATE TABLE #budgetBasisIDs (ReimbursementEncounterID INT);
	CREATE TABLE #projectionBasisIDs (ReimbursementEncounterID INT);

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT);

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED)
			INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID	
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
		UNION
		SELECT DISTINCT sle.EntityID, sle.ServiceLineID 
		FROM fp.ServiceLineEncounter sle 
			LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID 
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
		
	END ELSE 
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
			
	-- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well.
	SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		sle.PayorID, sle.PayorGroupID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID,
		SUM(TargetAdjusted01) AS Target01, SUM(TargetAdjusted02) AS Target02, SUM(TargetAdjusted03) AS Target03, 
		SUM(TargetAdjusted04) AS Target04, SUM(TargetAdjusted05) AS Target05, SUM(TargetAdjusted06) AS Target06,
		SUM(TargetAdjusted07) AS Target07, SUM(TargetAdjusted08) AS Target08, SUM(TargetAdjusted09) AS Target09, 
		SUM(TargetAdjusted10) AS Target10, SUM(TargetAdjusted11) AS Target11, SUM(TargetAdjusted12) AS Target12,

		SUM(BudgetAdjusted01) AS Budget01, SUM(BudgetAdjusted02) AS Budget02, SUM(BudgetAdjusted03) AS Budget03, 
		SUM(BudgetAdjusted04) AS Budget04, SUM(BudgetAdjusted05) AS Budget05, SUM(BudgetAdjusted06) AS Budget06,
		SUM(BudgetAdjusted07) AS Budget07, SUM(BudgetAdjusted08) AS Budget08, SUM(BudgetAdjusted09) AS Budget09, 
		SUM(BudgetAdjusted10) AS Budget10, SUM(BudgetAdjusted11) AS Budget11, SUM(BudgetAdjusted12) AS Budget12,

		SUM(ProjectionAdjusted01) AS Projection01, SUM(ProjectionAdjusted02) AS Projection02, SUM(ProjectionAdjusted03) AS Projection03, 
		SUM(ProjectionAdjusted04) AS Projection04, SUM(ProjectionAdjusted05) AS Projection05, SUM(ProjectionAdjusted06) AS Projection06,
		SUM(ProjectionAdjusted07) AS Projection07, SUM(ProjectionAdjusted08) AS Projection08, SUM(ProjectionAdjusted09) AS Projection09, 
		SUM(ProjectionAdjusted10) AS Projection10, SUM(ProjectionAdjusted11) AS Projection11, SUM(ProjectionAdjusted12) AS Projection12
	INTO #factReimbursementEncounters
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
	WHERE sle.BudgetConfigID = @BudgetConfigID
	GROUP BY sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END, sle.PayorID, sle.PayorGroupID, CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END, CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
			sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID
		FROM #factReimbursementEncounters sle
	END ELSE
	BEGIN
		-- Publish Target
		;WITH TGT AS   
		(  
			SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, 
				fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, tgt.BudgetPhaseID,
				tgt.AdjustedEncounters01, tgt.AdjustedEncounters02, tgt.AdjustedEncounters03,
				tgt.AdjustedEncounters04, tgt.AdjustedEncounters05, tgt.AdjustedEncounters06,
				tgt.AdjustedEncounters07, tgt.AdjustedEncounters08, tgt.AdjustedEncounters09,
				tgt.AdjustedEncounters10, tgt.AdjustedEncounters11, tgt.AdjustedEncounters12
			FROM [fp].[FactReimbursementEncounter] fact  
				INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID
				INNER JOIN fp.FactReimbursementEncounterBudget tgt ON fact.ReimbursementEncounterID = tgt.ReimbursementEncounterID AND tgt.BudgetPhaseID = 2
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #factReimbursementEncounters AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.BudgetPhaseID = 2
		)  
		WHEN MATCHED AND (
							target.AdjustedEncounters01 <> src.Target01 OR
							target.AdjustedEncounters02 <> src.Target02 OR
							target.AdjustedEncounters03 <> src.Target03 OR
							target.AdjustedEncounters04 <> src.Target04 OR
							target.AdjustedEncounters05 <> src.Target05 OR
							target.AdjustedEncounters06 <> src.Target06 OR
							target.AdjustedEncounters07 <> src.Target07 OR
							target.AdjustedEncounters08 <> src.Target08 OR
							target.AdjustedEncounters09 <> src.Target09 OR
							target.AdjustedEncounters10 <> src.Target10 OR
							target.AdjustedEncounters11 <> src.Target11 OR
							target.AdjustedEncounters12 <> src.Target12
						 )
		THEN  
			UPDATE SET target.AdjustedEncounters01 = src.Target01,
					   target.AdjustedEncounters02 = src.Target02,
					   target.AdjustedEncounters03 = src.Target03,
					   target.AdjustedEncounters04 = src.Target04,
					   target.AdjustedEncounters05 = src.Target05,
					   target.AdjustedEncounters06 = src.Target06,
					   target.AdjustedEncounters07 = src.Target07,
					   target.AdjustedEncounters08 = src.Target08,
					   target.AdjustedEncounters09 = src.Target09,
					   target.AdjustedEncounters10 = src.Target10,
					   target.AdjustedEncounters11 = src.Target11,
					   target.AdjustedEncounters12 = src.Target12;

		-- Publish Budget
		;WITH TGT AS   
		(  
			SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, 
				fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, budg.ReimbursementEncounterID, budg.BudgetPhaseID,
				budg.AdjustedEncounters01, budg.AdjustedEncounters02, budg.AdjustedEncounters03,
				budg.AdjustedEncounters04, budg.AdjustedEncounters05, budg.AdjustedEncounters06,
				budg.AdjustedEncounters07, budg.AdjustedEncounters08, budg.AdjustedEncounters09,
				budg.AdjustedEncounters10, budg.AdjustedEncounters11, budg.AdjustedEncounters12
			FROM [fp].[FactReimbursementEncounter] fact  
				INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID
				INNER JOIN fp.FactReimbursementEncounterBudget budg ON fact.ReimbursementEncounterID = budg.ReimbursementEncounterID AND budg.BudgetPhaseID = 3
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #factReimbursementEncounters AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.BudgetPhaseID = 3
		)  
		WHEN MATCHED AND (
							target.AdjustedEncounters01 <> src.Budget01 OR
							target.AdjustedEncounters02 <> src.Budget02 OR
							target.AdjustedEncounters03 <> src.Budget03 OR
							target.AdjustedEncounters04 <> src.Budget04 OR
							target.AdjustedEncounters05 <> src.Budget05 OR
							target.AdjustedEncounters06 <> src.Budget06 OR
							target.AdjustedEncounters07 <> src.Budget07 OR
							target.AdjustedEncounters08 <> src.Budget08 OR
							target.AdjustedEncounters09 <> src.Budget09 OR
							target.AdjustedEncounters10 <> src.Budget10 OR
							target.AdjustedEncounters11 <> src.Budget11 OR
							target.AdjustedEncounters12 <> src.Budget12
						 )
		THEN  
			UPDATE SET target.AdjustedEncounters01 = src.Budget01,
					   target.AdjustedEncounters02 = src.Budget02,
					   target.AdjustedEncounters03 = src.Budget03,
					   target.AdjustedEncounters04 = src.Budget04,
					   target.AdjustedEncounters05 = src.Budget05,
					   target.AdjustedEncounters06 = src.Budget06,
					   target.AdjustedEncounters07 = src.Budget07,
					   target.AdjustedEncounters08 = src.Budget08,
					   target.AdjustedEncounters09 = src.Budget09,
					   target.AdjustedEncounters10 = src.Budget10,
					   target.AdjustedEncounters11 = src.Budget11,
					   target.AdjustedEncounters12 = src.Budget12
		OUTPUT 
			INSERTED.ReimbursementEncounterID
		INTO
			#budgetBasisIDs (ReimbursementEncounterID);

		-- Publish Projection
		;WITH TGT AS   
		(  
			SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, 
				fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, proj.ReimbursementEncounterID,
				proj.AdjustedEncounters01, proj.AdjustedEncounters02, proj.AdjustedEncounters03,
				proj.AdjustedEncounters04, proj.AdjustedEncounters05, proj.AdjustedEncounters06,
				proj.AdjustedEncounters07, proj.AdjustedEncounters08, proj.AdjustedEncounters09,
				proj.AdjustedEncounters10, proj.AdjustedEncounters11, proj.AdjustedEncounters12
			FROM [fp].[FactReimbursementEncounter] fact  
				INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID
				INNER JOIN fp.FactReimbursementEncounterProjection proj ON fact.ReimbursementEncounterID = proj.ReimbursementEncounterID
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #factReimbursementEncounters AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN MATCHED AND (
							target.AdjustedEncounters01 <> src.Projection01 OR
							target.AdjustedEncounters02 <> src.Projection02 OR
							target.AdjustedEncounters03 <> src.Projection03 OR
							target.AdjustedEncounters04 <> src.Projection04 OR
							target.AdjustedEncounters05 <> src.Projection05 OR
							target.AdjustedEncounters06 <> src.Projection06 OR
							target.AdjustedEncounters07 <> src.Projection07 OR
							target.AdjustedEncounters08 <> src.Projection08 OR
							target.AdjustedEncounters09 <> src.Projection09 OR
							target.AdjustedEncounters10 <> src.Projection10 OR
							target.AdjustedEncounters11 <> src.Projection11 OR
							target.AdjustedEncounters12 <> src.Projection12
						 )
		THEN  
			UPDATE SET target.AdjustedEncounters01 = src.Projection01,
					   target.AdjustedEncounters02 = src.Projection02,
					   target.AdjustedEncounters03 = src.Projection03,
					   target.AdjustedEncounters04 = src.Projection04,
					   target.AdjustedEncounters05 = src.Projection05,
					   target.AdjustedEncounters06 = src.Projection06,
					   target.AdjustedEncounters07 = src.Projection07,
					   target.AdjustedEncounters08 = src.Projection08,
					   target.AdjustedEncounters09 = src.Projection09,
					   target.AdjustedEncounters10 = src.Projection10,
					   target.AdjustedEncounters11 = src.Projection11,
					   target.AdjustedEncounters12 = src.Projection12
		OUTPUT 
			INSERTED.ReimbursementEncounterID
		INTO
			#projectionBasisIDs (ReimbursementEncounterID);

		-- Find out what was changed. We can cross apply all 12 months in this case because months are on rows. If we change
		-- projection to only update the months not loaded, we'll want to update this. Unlike other procs that are similar,
		-- we don't care about the value because when we fix the change history, we take the stored rate in the change history
		-- times the volume in the DB, we don't actually care what the value was we flexed to like in the past.
		SELECT DISTINCT ReimbursementEncounterID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID
		FROM #budgetBasisIDs
			CROSS JOIN fw.DimFiscalMonth m
		WHERE m.FiscalMonthID != 0
		UNION ALL
		SELECT DISTINCT ReimbursementEncounterID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(12 as tinyint) AS TimeClassID
		FROM #projectionBasisIDs
			CROSS JOIN fw.DimFiscalMonth m
		WHERE m.FiscalMonthID != 0
	END
END
GO


---------------------------------------------

-- fp.procSampleEncountersToReimbursement_History
/**************************************************************
** Change History
**************************************************************
** CID Date        Author  WI            Description
** 1   2022-02-04  MY      JAZZ-31904    Initial
** 2   2023-01-17  BK      JAZZ-48267    New data structure
** 3   2023-05-18  MY      JAZZ-55153    Updated History table
** 4   2023-11-15  BK      JAZZ-62974    Fix issue with Encounters not being pushed to Reimbursement because of missing Charges data
** 5   2024-01-11  AO      JAZZ-64530	 Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE PROCEDURE [fp].[procSampleEncountersToReimbursement_History]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,		
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	DECLARE @IsMedicalSurgicalUsed BIT,
			@IsMsdrgUsed BIT,
			@IsCptUsed BIT

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'PrimaryCPTID'

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters;

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT);

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED)
			INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID	
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
		UNION
		SELECT DISTINCT sle.EntityID, sle.ServiceLineID 
		FROM fp.ServiceLineEncounter sle 
			LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID 
			LEFT JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
		
	END ELSE 
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
			
	-- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well.
	SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, 
		sle.PayorID, sle.PayorGroupID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID, 
		SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, 
		SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06,
		SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08, SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, 
		SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12,

		SUM(hist.ActualYTDValue01) AS ActualYTDValue01, SUM(hist.ActualYTDValue02) AS ActualYTDValue02, SUM(hist.ActualYTDValue03) AS ActualYTDValue03, 
		SUM(hist.ActualYTDValue04) AS ActualYTDValue04, SUM(hist.ActualYTDValue05) AS ActualYTDValue05, SUM(hist.ActualYTDValue06) AS ActualYTDValue06,
		SUM(hist.ActualYTDValue07) AS ActualYTDValue07, SUM(hist.ActualYTDValue08) AS ActualYTDValue08, SUM(hist.ActualYTDValue09) AS ActualYTDValue09, 
		SUM(hist.ActualYTDValue10) AS ActualYTDValue10, SUM(hist.ActualYTDValue11) AS ActualYTDValue11, SUM(hist.ActualYTDValue12) AS ActualYTDValue12,

		SUM(hist.CurrentYearBudget01) AS CurrentYearBudget01, SUM(hist.CurrentYearBudget02) AS CurrentYearBudget02, SUM(hist.CurrentYearBudget03) AS CurrentYearBudget03, 
		SUM(hist.CurrentYearBudget04) AS CurrentYearBudget04, SUM(hist.CurrentYearBudget05) AS CurrentYearBudget05, SUM(hist.CurrentYearBudget06) AS CurrentYearBudget06,
		SUM(hist.CurrentYearBudget07) AS CurrentYearBudget07, SUM(hist.CurrentYearBudget08) AS CurrentYearBudget08, SUM(hist.CurrentYearBudget09) AS CurrentYearBudget09, 
		SUM(hist.CurrentYearBudget10) AS CurrentYearBudget10, SUM(hist.CurrentYearBudget11) AS CurrentYearBudget11, SUM(hist.CurrentYearBudget12) AS CurrentYearBudget12
	INTO #factReimbursementEncounters
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
		INNER JOIN fp.ServiceLineEncounterHistory hist ON sle.ServiceLineEncounterID = hist.ServiceLineEncounterID
	WHERE sle.BudgetConfigID = @BudgetConfigID
	GROUP BY sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END, sle.PayorID, sle.PayorGroupID, CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END, CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
			sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID
		FROM #factReimbursementEncounters sle
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, 
				fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, 
				hist.ActualYTDEncounters01, hist.ActualYTDEncounters02, hist.ActualYTDEncounters03,
				hist.ActualYTDEncounters04, hist.ActualYTDEncounters05, hist.ActualYTDEncounters06,
				hist.ActualYTDEncounters07, hist.ActualYTDEncounters08, hist.ActualYTDEncounters09,
				hist.ActualYTDEncounters10, hist.ActualYTDEncounters11, hist.ActualYTDEncounters12,

				hist.PriorYearActualEncounters01, hist.PriorYearActualEncounters02, hist.PriorYearActualEncounters03,
				hist.PriorYearActualEncounters04, hist.PriorYearActualEncounters05, hist.PriorYearActualEncounters06,
				hist.PriorYearActualEncounters07, hist.PriorYearActualEncounters08, hist.PriorYearActualEncounters09,
				hist.PriorYearActualEncounters10, hist.PriorYearActualEncounters11, hist.PriorYearActualEncounters12,

				hist.CurrentYearBudgetEncounters01, hist.CurrentYearBudgetEncounters02, hist.CurrentYearBudgetEncounters03,
				hist.CurrentYearBudgetEncounters04, hist.CurrentYearBudgetEncounters05, hist.CurrentYearBudgetEncounters06,
				hist.CurrentYearBudgetEncounters07, hist.CurrentYearBudgetEncounters08, hist.CurrentYearBudgetEncounters09,
				hist.CurrentYearBudgetEncounters10, hist.CurrentYearBudgetEncounters11, hist.CurrentYearBudgetEncounters12
			FROM [fp].[FactReimbursementEncounter] fact  
				INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID
				INNER JOIN fp.FactReimbursementEncounterHistory hist ON fact.ReimbursementEncounterID = hist.ReimbursementEncounterID
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #factReimbursementEncounters AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN MATCHED AND (
							target.ActualYTDEncounters01 <> src.ActualYTDValue01 OR
							target.ActualYTDEncounters02 <> src.ActualYTDValue02 OR
							target.ActualYTDEncounters03 <> src.ActualYTDValue03 OR
							target.ActualYTDEncounters04 <> src.ActualYTDValue04 OR
							target.ActualYTDEncounters05 <> src.ActualYTDValue05 OR
							target.ActualYTDEncounters06 <> src.ActualYTDValue06 OR
							target.ActualYTDEncounters07 <> src.ActualYTDValue07 OR
							target.ActualYTDEncounters08 <> src.ActualYTDValue08 OR
							target.ActualYTDEncounters09 <> src.ActualYTDValue09 OR
							target.ActualYTDEncounters10 <> src.ActualYTDValue10 OR
							target.ActualYTDEncounters11 <> src.ActualYTDValue11 OR
							target.ActualYTDEncounters12 <> src.ActualYTDValue12 OR

							target.PriorYearActualEncounters01 <> src.PriorYearActualValue01 OR
							target.PriorYearActualEncounters02 <> src.PriorYearActualValue02 OR
							target.PriorYearActualEncounters03 <> src.PriorYearActualValue03 OR
							target.PriorYearActualEncounters04 <> src.PriorYearActualValue04 OR
							target.PriorYearActualEncounters05 <> src.PriorYearActualValue05 OR
							target.PriorYearActualEncounters06 <> src.PriorYearActualValue06 OR
							target.PriorYearActualEncounters07 <> src.PriorYearActualValue07 OR
							target.PriorYearActualEncounters08 <> src.PriorYearActualValue08 OR
							target.PriorYearActualEncounters09 <> src.PriorYearActualValue09 OR
							target.PriorYearActualEncounters10 <> src.PriorYearActualValue10 OR
							target.PriorYearActualEncounters11 <> src.PriorYearActualValue11 OR
							target.PriorYearActualEncounters12 <> src.PriorYearActualValue12 OR

							target.CurrentYearBudgetEncounters01 <> src.CurrentYearBudget01 OR
							target.CurrentYearBudgetEncounters02 <> src.CurrentYearBudget02 OR
							target.CurrentYearBudgetEncounters03 <> src.CurrentYearBudget03 OR
							target.CurrentYearBudgetEncounters04 <> src.CurrentYearBudget04 OR
							target.CurrentYearBudgetEncounters05 <> src.CurrentYearBudget05 OR
							target.CurrentYearBudgetEncounters06 <> src.CurrentYearBudget06 OR
							target.CurrentYearBudgetEncounters07 <> src.CurrentYearBudget07 OR
							target.CurrentYearBudgetEncounters08 <> src.CurrentYearBudget08 OR
							target.CurrentYearBudgetEncounters09 <> src.CurrentYearBudget09 OR
							target.CurrentYearBudgetEncounters10 <> src.CurrentYearBudget10 OR
							target.CurrentYearBudgetEncounters11 <> src.CurrentYearBudget11 OR
							target.CurrentYearBudgetEncounters12 <> src.CurrentYearBudget12
						 )
		THEN  
			UPDATE SET target.ActualYTDEncounters01 = src.ActualYTDValue01,
					   target.ActualYTDEncounters02 = src.ActualYTDValue02,
					   target.ActualYTDEncounters03 = src.ActualYTDValue03,
					   target.ActualYTDEncounters04 = src.ActualYTDValue04,
					   target.ActualYTDEncounters05 = src.ActualYTDValue05,
					   target.ActualYTDEncounters06 = src.ActualYTDValue06,
					   target.ActualYTDEncounters07 = src.ActualYTDValue07,
					   target.ActualYTDEncounters08 = src.ActualYTDValue08,
					   target.ActualYTDEncounters09 = src.ActualYTDValue09,
					   target.ActualYTDEncounters10 = src.ActualYTDValue10,
					   target.ActualYTDEncounters11 = src.ActualYTDValue11,
					   target.ActualYTDEncounters12 = src.ActualYTDValue12,
					   
					   target.PriorYearActualEncounters01 = src.PriorYearActualValue01,
					   target.PriorYearActualEncounters02 = src.PriorYearActualValue02,
					   target.PriorYearActualEncounters03 = src.PriorYearActualValue03,
					   target.PriorYearActualEncounters04 = src.PriorYearActualValue04,
					   target.PriorYearActualEncounters05 = src.PriorYearActualValue05,
					   target.PriorYearActualEncounters06 = src.PriorYearActualValue06,
					   target.PriorYearActualEncounters07 = src.PriorYearActualValue07,
					   target.PriorYearActualEncounters08 = src.PriorYearActualValue08,
					   target.PriorYearActualEncounters09 = src.PriorYearActualValue09,
					   target.PriorYearActualEncounters10 = src.PriorYearActualValue10,
					   target.PriorYearActualEncounters11 = src.PriorYearActualValue11,
					   target.PriorYearActualEncounters12 = src.PriorYearActualValue12,
					   
					   target.CurrentYearBudgetEncounters01 = src.CurrentYearBudget01,
					   target.CurrentYearBudgetEncounters02 = src.CurrentYearBudget02,
					   target.CurrentYearBudgetEncounters03 = src.CurrentYearBudget03,
					   target.CurrentYearBudgetEncounters04 = src.CurrentYearBudget04,
					   target.CurrentYearBudgetEncounters05 = src.CurrentYearBudget05,
					   target.CurrentYearBudgetEncounters06 = src.CurrentYearBudget06,
					   target.CurrentYearBudgetEncounters07 = src.CurrentYearBudget07,
					   target.CurrentYearBudgetEncounters08 = src.CurrentYearBudget08,
					   target.CurrentYearBudgetEncounters09 = src.CurrentYearBudget09,
					   target.CurrentYearBudgetEncounters10 = src.CurrentYearBudget10,
					   target.CurrentYearBudgetEncounters11 = src.CurrentYearBudget11,
					   target.CurrentYearBudgetEncounters12 = src.CurrentYearBudget12;

	END
END
GO


---------------------------------------------

-- fp.procSampleEncountersToReimbursement_Initial
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author	 WI	           Description
** 1    2022-02-04	MY      JAZZ-31904	 Initial
** 2    2023-01-17  BK      JAZZ-48267   New data structure
** 3    2023-11-15  BK      JAZZ-62974   Fix issue with Encounters not being pushed to Reimbursement because of missing Charges data
** 4    2024-01-11  AO      JAZZ-64530	 Data transfer for SLE is based on selected Model in Plan Config 
*************************************************************/
CREATE PROCEDURE [fp].[procSampleEncountersToReimbursement_Initial]
	@BudgetConfigID INT,
	@IsReimbursementGLEnabled BIT = 0,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN	
	DECLARE @IsMedicalSurgicalUsed BIT,
			@IsMsdrgUsed BIT,
			@IsCptUsed BIT

	SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MedicalSurgicalID'

	SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'MSDRGID'

	SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END
	FROM fp.SectionSetup ss
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID
	WHERE bc.BudgetConfigID = @BudgetConfigID
		AND ss.PlanSectionID = 7 -- Reimbursement
		AND ss.SubSectionID = 5 -- Reimbursement - Encounters
		AND ss.LevelID = 'PrimaryCPTID'

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments;
	IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters;

	CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT);
	INSERT INTO #ChargeVolumeDepartments (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT);

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED)
			INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID	
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
		UNION
		SELECT DISTINCT sle.EntityID, sle.ServiceLineID 
		FROM fp.ServiceLineEncounter sle 
			LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
		
	END ELSE 
	BEGIN
		INSERT INTO #encounterTargeting (EntityID, ServiceLineID)
		SELECT DISTINCT map.EntityID, map.ServiceLineID 
		FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED)
			LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID	
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE map.BudgetConfigID  = @BudgetConfigID	
			AND ((@IsReimbursementGLEnabled = 1 
				AND (bc.DefaultReimbursementNetRevenueModelID = 1 
					AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model
					OR rnrm.NetRevenueModelID = 1) 
				OR @IsReimbursementGLEnabled = 0) 
	END
			
	-- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well.
	SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, 
		CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, 
		CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID, 
		SUM(sle.InitialBudget01) AS InitialBudget01, SUM(sle.InitialBudget02) AS InitialBudget02, SUM(sle.InitialBudget03) AS InitialBudget03, SUM(sle.InitialBudget04) AS InitialBudget04, SUM(sle.InitialBudget05) AS InitialBudget05, SUM(sle.InitialBudget06) AS InitialBudget06,
		SUM(sle.InitialBudget07) AS InitialBudget07, SUM(sle.InitialBudget08) AS InitialBudget08, SUM(sle.InitialBudget09) AS InitialBudget09, SUM(sle.InitialBudget10) AS InitialBudget10, SUM(sle.InitialBudget11) AS InitialBudget11, SUM(sle.InitialBudget12) AS InitialBudget12
	INTO #factReimbursementEncounters
	FROM fp.ServiceLineEncounter sle 
		INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID
	WHERE sle.BudgetConfigID = @BudgetConfigID
	GROUP BY sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
		CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END, sle.PayorID, sle.PayorGroupID, CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END, CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments
		SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, 
			sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID
		FROM #factReimbursementEncounters sle
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID],
				fact.[PayorID], fact.[PayorGroupID], fact.[MSDRGID], fact.[CPTID],
				[InitialBudgetEncounters01], [InitialBudgetEncounters02], [InitialBudgetEncounters03], [InitialBudgetEncounters04], [InitialBudgetEncounters05], [InitialBudgetEncounters06], 
				[InitialBudgetEncounters07], [InitialBudgetEncounters08], [InitialBudgetEncounters09], [InitialBudgetEncounters10], [InitialBudgetEncounters11], [InitialBudgetEncounters12]
			FROM [fp].[FactReimbursementEncounter] fact  
				INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID
			WHERE fact.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #factReimbursementEncounters AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PatientClassID = src.PatientClassID  
			AND target.ServiceLineID = src.ServiceLineID 
			AND target.ServiceLineRollupID = src.ServiceLineRollupID 
			AND target.MedicalSurgicalID = src.MedicalSurgicalID 
			AND target.MSDRGID = src.MSDRGID 
			AND target.CPTID = src.CPTID 
			AND target.PayorID = src.PayorID 
			AND target.PayorGroupID = src.PayorGroupID 
		)  
		WHEN MATCHED AND (
							target.InitialBudgetEncounters01 <> src.InitialBudget01 OR
							target.InitialBudgetEncounters02 <> src.InitialBudget02 OR
							target.InitialBudgetEncounters03 <> src.InitialBudget03 OR
							target.InitialBudgetEncounters04 <> src.InitialBudget04 OR
							target.InitialBudgetEncounters05 <> src.InitialBudget05 OR
							target.InitialBudgetEncounters06 <> src.InitialBudget06 OR
							target.InitialBudgetEncounters07 <> src.InitialBudget07 OR
							target.InitialBudgetEncounters08 <> src.InitialBudget08 OR
							target.InitialBudgetEncounters09 <> src.InitialBudget09 OR
							target.InitialBudgetEncounters10 <> src.InitialBudget10 OR
							target.InitialBudgetEncounters11 <> src.InitialBudget11 OR
							target.InitialBudgetEncounters12 <> src.InitialBudget12
						 )
		THEN  
			UPDATE SET target.InitialBudgetEncounters01 = src.InitialBudget01,
					   target.InitialBudgetEncounters02 = src.InitialBudget02,
					   target.InitialBudgetEncounters03 = src.InitialBudget03,
					   target.InitialBudgetEncounters04 = src.InitialBudget04,
					   target.InitialBudgetEncounters05 = src.InitialBudget05,
					   target.InitialBudgetEncounters06 = src.InitialBudget06,
					   target.InitialBudgetEncounters07 = src.InitialBudget07,
					   target.InitialBudgetEncounters08 = src.InitialBudget08,
					   target.InitialBudgetEncounters09 = src.InitialBudget09,
					   target.InitialBudgetEncounters10 = src.InitialBudget10,
					   target.InitialBudgetEncounters11 = src.InitialBudget11,
					   target.InitialBudgetEncounters12 = src.InitialBudget12;

	END
END
GO


---------------------------------------------

-- fp.procSampleGLDollarsPerUOS
CREATE   PROCEDURE [fp].[procSampleGLDollarsPerUOS]
	@EntityGroupConfigID INT,
	@CurrentFiscalYearID SMALLINT,
	@SourceFiscalYearID SMALLINT,
	@SourceTimeClassID TINYINT,
	@MonthsLoaded INT,
	@APEModelSectionIDs SqlByteListTableType READONLY,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI				Description
	 ** 1 	 2019-03-26  IP  	 B-22466		Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2 	 2021-03-24  NN  	 Jazz-14123		Remove null joins
	 ** 3 	 2021-12-09  BK  	 Jazz-30703		Use fp.FactStatistics historicals instead of int.FactStatistic
	 ** 4	 2023-03-13	 MY		 JAZZ-48981	    Update sampling for cross department flexing
	 ** 5	 5-9-2023    NT      JAZZ-54290		Data restructure changes to use new fp.GeneralLedger table
	 ** 6	 2024-08-26	 MY		 JAZZ-76040		Adjust Statistics for Leap Year
	 *************************************************************/
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED)
		WHERE d.EntityGroupConfigID = @EntityGroupConfigID
			AND d.FlexingTypeID IN (1, 2)
	END

	DECLARE @IdsCount TINYINT;
	SELECT @IdsCount = COUNT(value) FROM @APEModelSectionIDs;

	DECLARE @IsAnnualized BIT = (CASE WHEN (@SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1) THEN 1 ELSE 0 END);
	DECLARE @IsCurrentYearALeapYear BIT = (CASE WHEN (@CurrentFiscalYearID % 4 = 0 AND @CurrentFiscalYearID % 100 <> 0) OR @CurrentFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
	
	DECLARE @EnableLeapYearAdjustedStatistics BIT = ISNULL((SELECT bcs.Value 
										FROM fp.viewBudgetConfigSetting bcs
											INNER JOIN fp.BudgetConfig bc ON bcs.BudgetConfigID = bc.BudgetConfigID
											INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
										WHERE bcs.Name = 'Enable Leap Year Adjusted Statistics for Calculating Rates' 
											AND egc.EntityGroupConfigID = @EntityGroupConfigID), 0);

	-- JAZZ-76040: Adjust Statistics for Leap Year. This only needs to be applied for Annualized and if the current year is a leap year.
	DECLARE @AdjustStatisticsForLeapYear BIT = CASE WHEN @EnableLeapYearAdjustedStatistics = 1 AND @IsAnnualized = 1 AND @IsCurrentYearALeapYear = 1 THEN 1 ELSE 0 END;

	-- For $/UOS we calculate it by taking the total variable dollars / total stats. We do it to the initial budget so that
	-- it can be used within the engine after a configuration change. Sampled $/UOS doesn't really matter as it can change with each configuration change.

	-- Projection rates should match the budget rates 

    -- Calculate the stats for each Department/GL Account that is setup to be flexed by stats

	DECLARE @UsePriorYear BIT = 0;
	DECLARE @UseActualYTD BIT = 0;
	DECLARE @UseCurrentYearBudget BIT = 0;
	
	IF @SourceTimeClassID = 2 BEGIN
		SET @UseCurrentYearBudget = 1;
	END ELSE BEGIN
		IF @CurrentFiscalYearID = @SourceFiscalYearID BEGIN
			SET @UseActualYTD = 1;
		END ELSE BEGIN
			SET @UsePriorYear = 1
			END
	END		

	SELECT 
		map.DepartmentID,
		map.GLAccountID as AccountID,
		CASE 
			WHEN @UseActualYTD = 1 THEN ISNULL(SUM(statHist.ActualYTDValueTotal), 0)
			WHEN @UseCurrentYearBudget = 1 THEN ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0)
			WHEN @UsePriorYear = 1 THEN ISNULL(SUM(statHist.PriorYearActualValueTotal), 0)
		END
		 AS StatTotal
	INTO #budgetStats
	FROM [fp].[FlexConfigMapping] map
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = map.DepartmentID
		INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigID = map.EntityGroupConfigID
		INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
		LEFT JOIN fp.[FactStatistics] stat ON stat.DepartmentID = map.SourceDepartmentID AND stat.AccountID = map.StatAccountID AND stat.BudgetConfigID = bc.BudgetConfigID
		LEFT JOIN fp.[FactStatisticsHistory] statHist ON stat.StatisticsID = statHist.StatisticsID
	WHERE map.EntityGroupConfigID = @EntityGroupConfigID
		AND map.GLAccountID != 0
		AND map.FlexingTypeID IN (1, 2)
	GROUP BY
		map.DepartmentID, 
		map.GLAccountID
					
	-- JAZZ-76040: Adjust Statistics for Leap Year
	IF (@AdjustStatisticsForLeapYear = 1)
	BEGIN
		
		-- per stackoverflow (per MY)
		DECLARE @BudgetFiscalYearID INT = @CurrentFiscalYearID + 1;
		DECLARE @IsBudgetLeapYear BIT = (CASE WHEN (@BudgetFiscalYearID % 4 = 0 AND @BudgetFiscalYearID % 100 <> 0) OR @BudgetFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)  
		DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12)
		DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsCurrentYearALeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)

		UPDATE #budgetStats
		SET	StatTotal = ((StatTotal / @DaysInMonthsLoaded) * @DaysBudgetYear)		

	END

	-- We need to recalculate the variable dollars on the fly because InitialBudget/Projection Dollars will get flexed, otherwise if we don't 
	-- the rate will rise each time.
	SELECT
		fgl.DepartmentID,
		fgl.AccountID,
		fgl.EntityGroupConfigID,
		COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal AS BudgetDollarTotal
	INTO #variableDollars
    FROM [fp].[GeneralLedger] fgl
    LEFT JOIN @APEModelSectionIDs ids ON ids.value = fgl.APEModelSectionID
    INNER JOIN (
        SELECT 
            fgl.DepartmentID,
			fgl.AccountID,
			(SUM(CASE WHEN  1 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget01 ELSE 0 END + 
				 CASE WHEN  2 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget02 ELSE 0 END + 
				 CASE WHEN  3 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget03 ELSE 0 END + 
				 CASE WHEN  4 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget04 ELSE 0 END + 
				 CASE WHEN  5 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget05 ELSE 0 END + 
				 CASE WHEN  6 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget06 ELSE 0 END + 
				 CASE WHEN  7 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget07 ELSE 0 END + 
				 CASE WHEN  8 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget08 ELSE 0 END + 
				 CASE WHEN  9 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget09 ELSE 0 END + 
				 CASE WHEN 10 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget10 ELSE 0 END + 
				 CASE WHEN 11 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget11 ELSE 0 END + 
				 CASE WHEN 12 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal
        FROM 
            [fp].[GeneralLedger] fgl
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
        WHERE 
            fgl.EntityGroupConfigID = @EntityGroupConfigID
		GROUP BY
			fgl.DepartmentID,
			fgl.AccountID
    ) as total
        ON total.DepartmentID = fgl.DepartmentID
            AND total.AccountID = fgl.AccountID
    LEFT JOIN (
        SELECT fav.DepartmentID, fav.AccountID, MAX(FixedPercentage) AS FixedPercentage
	    FROM [fp].[FactAccountVariability] fav
			INNER JOIN [fp].[EntityGroupConfig] egc ON 
					egc.EntityGroupConfigID = @EntityGroupConfigID 
				AND egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fav.DepartmentID
	    GROUP BY fav.DepartmentID, fav.AccountID
    ) fv 
        ON fv.DepartmentID = fgl.DepartmentID 
        AND fv.AccountID = fgl.AccountID
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID		
      AND fgl.VariabilityID = 2		
	  AND (@IdsCount = 0 OR ids.value IS NOT NULL)


	-- set the Dollars/UOS values on GL table
    UPDATE
		fgl
	SET
		InitialBudgetDollarsPerUOS01 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS02 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS03 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS04 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS05 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS06 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS07 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS08 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS09 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS10 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS11 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialBudgetDollarsPerUOS12 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		
		-- Projection rates should match the budget rates and use the budget baseline to calculate
		InitialProjectionDollarsPerUOS01 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS02 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS03 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS04 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS05 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS06 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS07 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS08 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS09 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS10 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS11 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
		InitialProjectionDollarsPerUOS12 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0)

	FROM
		[fp].[GeneralLedger] fgl
		INNER JOIN #variableDollars fglDollars
			ON fgl.DepartmentID = fglDollars.DepartmentID
			AND fgl.AccountID = fglDollars.AccountID
			AND fgl.EntityGroupConfigID = fglDollars.EntityGroupConfigID
		INNER JOIN #budgetStats stat
			ON stat.DepartmentID = fgl.DepartmentID
			AND stat.AccountID = fgl.AccountID
	WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
		AND (		
			   fgl.InitialBudgetDollarsPerUOS01 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS02 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR
				fgl.InitialBudgetDollarsPerUOS03 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS04 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS05 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS06 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS07 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS08 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS09 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS10 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS11 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialBudgetDollarsPerUOS12 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR

				fgl.InitialProjectionDollarsPerUOS01 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS02 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS03 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS04 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS05 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS06 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS07 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS08 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS09 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS10 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS11 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
				fgl.InitialProjectionDollarsPerUOS12 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0))
		
END
GO


---------------------------------------------

-- fp.procSampleGeneralLedgerToReimbursement
CREATE PROCEDURE [fp].[procSampleGeneralLedgerToReimbursement] 
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsUpdatePerOfCharge BIT,
	@IsDebug BIT = 0 
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    05-23-2023   MZ        JAZZ-54503  Initial Creation
	** 2    07-04-2023   AO        JAZZ-57174  Adjusted formula NetAsPercentOfCharge
	** 3	08-08-2023	 MZ		   JAZZ-55099  Added IsUpdatePerOfCharge
	** 4	08-11-2023	 MZ		   JAZZ-55099  Fix targeting
	** 5	10-04-2023	 MZ		   JAZZ-61634  Fix % of charge calculation when revenue stays the same but new deductions were found
	** 6	10-12-2023	 NH		   JAZZ-59310  GL Reimbursement/ Adjustments - update Change history when edit past adjustment in Plan Editor	
	** 7	01-03-2024	 AO		   JAZZ-65384  Data transfer for GL is based on selected Model in Plan Config 
	** 8	08-12-2024   VZ		   JAZZ-74434  Data transfer for GL based on excluded departments
	*************************************************************/

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#ReimbursementGL') IS NOT NULL DROP TABLE #ReimbursementGL;
	IF OBJECT_ID('tempdb..#ReimbursementTargeting') IS NOT NULL DROP TABLE #ReimbursementTargeting;
	IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData;
	IF OBJECT_ID('tempdb..#DeductionData') IS NOT NULL DROP TABLE #DeductionData;
	IF OBJECT_ID('tempdb..#projectionBasisIDs') IS NOT NULL DROP TABLE #projectionBasisIDs
	IF OBJECT_ID('tempdb..#budgetBasisIDs') IS NOT NULL DROP TABLE #budgetBasisIDs
	IF OBJECT_ID('tempdb..#targetBasisIDs') IS NOT NULL DROP TABLE #targetBasisIDs
	
	CREATE TABLE #projectionBasisIDs (ReimbursementGeneralLedgerID INT)
	CREATE TABLE #budgetBasisIDs (ReimbursementGeneralLedgerID INT);
	CREATE TABLE #targetBasisIDs (ReimbursementGeneralLedgerID INT);

	CREATE TABLE #FilterByDepartment (DepartmentID INT);
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #ReimbursementTargeting (EntityID INT);

	CREATE TABLE #RevenueData (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],

		[Target01] [decimal](19, 8),
		[Target02] [decimal](19, 8),
		[Target03] [decimal](19, 8),
		[Target04] [decimal](19, 8),
		[Target05] [decimal](19, 8),
		[Target06] [decimal](19, 8),
		[Target07] [decimal](19, 8),
		[Target08] [decimal](19, 8),
		[Target09] [decimal](19, 8),
		[Target10] [decimal](19, 8),
		[Target11] [decimal](19, 8),
		[Target12] [decimal](19, 8),

		[Budget01] [decimal](19, 8),
		[Budget02] [decimal](19, 8),
		[Budget03] [decimal](19, 8),
		[Budget04] [decimal](19, 8),
		[Budget05] [decimal](19, 8),
		[Budget06] [decimal](19, 8),
		[Budget07] [decimal](19, 8),
		[Budget08] [decimal](19, 8),
		[Budget09] [decimal](19, 8),
		[Budget10] [decimal](19, 8),
		[Budget11] [decimal](19, 8),
		[Budget12] [decimal](19, 8),

		[Projection01] [decimal](19, 8),
		[Projection02] [decimal](19, 8),
		[Projection03] [decimal](19, 8),
		[Projection04] [decimal](19, 8),
		[Projection05] [decimal](19, 8),
		[Projection06] [decimal](19, 8),
		[Projection07] [decimal](19, 8),
		[Projection08] [decimal](19, 8),
		[Projection09] [decimal](19, 8),
		[Projection10] [decimal](19, 8),
		[Projection11] [decimal](19, 8),
		[Projection12] [decimal](19, 8)	
	)

	CREATE TABLE #DeductionData (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],

		[Target01] [decimal](19, 8),
		[Target02] [decimal](19, 8),
		[Target03] [decimal](19, 8),
		[Target04] [decimal](19, 8),
		[Target05] [decimal](19, 8),
		[Target06] [decimal](19, 8),
		[Target07] [decimal](19, 8),
		[Target08] [decimal](19, 8),
		[Target09] [decimal](19, 8),
		[Target10] [decimal](19, 8),
		[Target11] [decimal](19, 8),
		[Target12] [decimal](19, 8),

		[Budget01] [decimal](19, 8),
		[Budget02] [decimal](19, 8),
		[Budget03] [decimal](19, 8),
		[Budget04] [decimal](19, 8),
		[Budget05] [decimal](19, 8),
		[Budget06] [decimal](19, 8),
		[Budget07] [decimal](19, 8),
		[Budget08] [decimal](19, 8),
		[Budget09] [decimal](19, 8),
		[Budget10] [decimal](19, 8),
		[Budget11] [decimal](19, 8),
		[Budget12] [decimal](19, 8),

		[Projection01] [decimal](19, 8),
		[Projection02] [decimal](19, 8),
		[Projection03] [decimal](19, 8),
		[Projection04] [decimal](19, 8),
		[Projection05] [decimal](19, 8),
		[Projection06] [decimal](19, 8),
		[Projection07] [decimal](19, 8),
		[Projection08] [decimal](19, 8),
		[Projection09] [decimal](19, 8),
		[Projection10] [decimal](19, 8),
		[Projection11] [decimal](19, 8),
		[Projection12] [decimal](19, 8)	
	)

	CREATE TABLE #ReimbursementGL (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],

		[TargetAdjusted01] [decimal](19, 8),
		[TargetAdjusted02] [decimal](19, 8),
		[TargetAdjusted03] [decimal](19, 8),
		[TargetAdjusted04] [decimal](19, 8),
		[TargetAdjusted05] [decimal](19, 8),
		[TargetAdjusted06] [decimal](19, 8),
		[TargetAdjusted07] [decimal](19, 8),
		[TargetAdjusted08] [decimal](19, 8),
		[TargetAdjusted09] [decimal](19, 8),
		[TargetAdjusted10] [decimal](19, 8),
		[TargetAdjusted11] [decimal](19, 8),
		[TargetAdjusted12] [decimal](19, 8),

		[TargetAdjustedNetAsPercentOfCharge01] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge02] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge03] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge04] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge05] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge06] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge07] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge08] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge09] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge10] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge11] [decimal](19, 8),
		[TargetAdjustedNetAsPercentOfCharge12] [decimal](19, 8),

		[BudgetAdjusted01] [decimal](19, 8),
		[BudgetAdjusted02] [decimal](19, 8),
		[BudgetAdjusted03] [decimal](19, 8),
		[BudgetAdjusted04] [decimal](19, 8),
		[BudgetAdjusted05] [decimal](19, 8),
		[BudgetAdjusted06] [decimal](19, 8),
		[BudgetAdjusted07] [decimal](19, 8),
		[BudgetAdjusted08] [decimal](19, 8),
		[BudgetAdjusted09] [decimal](19, 8),
		[BudgetAdjusted10] [decimal](19, 8),
		[BudgetAdjusted11] [decimal](19, 8),
		[BudgetAdjusted12] [decimal](19, 8),

		[BudgetAdjustedNetAsPercentOfCharge01] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge02] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge03] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge04] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge05] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge06] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge07] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge08] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge09] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge10] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge11] [decimal](19, 8),
		[BudgetAdjustedNetAsPercentOfCharge12] [decimal](19, 8),

		[ProjectionAdjusted01] [decimal](19, 8),
		[ProjectionAdjusted02] [decimal](19, 8),
		[ProjectionAdjusted03] [decimal](19, 8),
		[ProjectionAdjusted04] [decimal](19, 8),
		[ProjectionAdjusted05] [decimal](19, 8),
		[ProjectionAdjusted06] [decimal](19, 8),
		[ProjectionAdjusted07] [decimal](19, 8),
		[ProjectionAdjusted08] [decimal](19, 8),
		[ProjectionAdjusted09] [decimal](19, 8),
		[ProjectionAdjusted10] [decimal](19, 8),
		[ProjectionAdjusted11] [decimal](19, 8),
		[ProjectionAdjusted12] [decimal](19, 8),

		[ProjectionAdjustedNetAsPercentOfCharge01] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge02] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge03] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge04] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge05] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge06] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge07] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge08] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge09] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge10] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge11] [decimal](19, 8),
		[ProjectionAdjustedNetAsPercentOfCharge12] [decimal](19, 8)
	)

	DECLARE @Revenue INT = 1;
	DECLARE @Deduction INT = 4;

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #ReimbursementTargeting (gl.EntityID)
		SELECT DISTINCT gl.EntityID
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
			INNER JOIN #FilterByDepartment d ON gl.DepartmentID = d.DepartmentID
		WHERE gl.BudgetConfigID = @BudgetConfigID 
			AND ((bc.DefaultReimbursementNetRevenueModelID = 2 
				AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) 
				OR rnrm.NetRevenueModelID = 2) -- GL Model
	END ELSE 
	BEGIN
		INSERT INTO #ReimbursementTargeting (gl.EntityID)
		SELECT DISTINCT gl.EntityID
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE gl.BudgetConfigID = @BudgetConfigID AND 
			((bc.DefaultReimbursementNetRevenueModelID = 2 
				AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) 
				OR rnrm.NetRevenueModelID = 2) -- GL Model
	END
	
	--#RevenueData
	INSERT INTO #RevenueData(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		Target01, Target02, Target03, Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12,
		Budget01, Budget02, Budget03, Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12,
		Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12
		)
	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID,
		SUM(gl.TargetAdjusted01) AS Target01, SUM(gl.TargetAdjusted02) AS Target02, SUM(gl.TargetAdjusted03) AS Target03, SUM(gl.TargetAdjusted04) AS Target04, SUM(gl.TargetAdjusted05) AS Target05, SUM(gl.TargetAdjusted06) AS Target06,
		SUM(gl.TargetAdjusted07)  AS Target07, SUM(gl.TargetAdjusted08) AS Target08, SUM(gl.TargetAdjusted09) AS Target09, SUM(gl.TargetAdjusted10) AS Target10, SUM(gl.TargetAdjusted11) AS Target11, SUM(gl.TargetAdjusted12) AS Target12,

		SUM(gl.BudgetAdjusted01) AS Budget01, SUM(gl.BudgetAdjusted02) AS Budget02, SUM(gl.BudgetAdjusted03) AS Budget03, SUM(gl.BudgetAdjusted04) AS Budget04, SUM(gl.BudgetAdjusted05) AS Budget05, SUM(gl.BudgetAdjusted06) AS Budget06,
		SUM(gl.BudgetAdjusted07) AS Budget07, SUM(gl.BudgetAdjusted08) AS Budget08, SUM(gl.BudgetAdjusted09) AS Budget09, SUM(gl.BudgetAdjusted10) AS Budget10, SUM(gl.BudgetAdjusted11) AS Budget11, SUM(gl.BudgetAdjusted12) AS Budget12,

		SUM(gl.ProjectionAdjusted01) AS Projection01, SUM(gl.ProjectionAdjusted02) AS Projection02, SUM(gl.ProjectionAdjusted03) AS Projection03, SUM(gl.ProjectionAdjusted04) AS Projection04, SUM(gl.ProjectionAdjusted05) AS Projection05, SUM(gl.ProjectionAdjusted06) AS Projection06,
		SUM(gl.ProjectionAdjusted07) AS Projection07, SUM(gl.ProjectionAdjusted08) AS Projection08, SUM(gl.ProjectionAdjusted09) AS Projection09, SUM(gl.ProjectionAdjusted10) AS Projection10, SUM(gl.ProjectionAdjusted11) AS Projection11, SUM(gl.ProjectionAdjusted12) AS Projection12
	FROM fp.GeneralLedger gl
		INNER JOIN #ReimbursementTargeting rt ON rt.EntityID = gl.EntityID
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID
	WHERE gl.BudgetConfigID = @BudgetConfigID 
		AND gl.APEModelSectionID = @Revenue
		AND gl.DepartmentID NOT IN (SELECT DepartmentID FROM fp.GeneralLedgerReimbursementExcludedDepartments
			WHERE BudgetConfigGUID = bc.BudgetConfigGUID)
	GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, gl.APEModelSectionID, a.PatientClassID

	--#DeductionData
	INSERT INTO #DeductionData(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		Target01, Target02, Target03, Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12,
		Budget01, Budget02, Budget03, Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12,
		Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12
		)
	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID,
		SUM(gl.TargetAdjusted01) AS Target01, SUM(gl.TargetAdjusted02) AS Target02, SUM(gl.TargetAdjusted03) AS Target03, SUM(gl.TargetAdjusted04) AS Target04, SUM(gl.TargetAdjusted05) AS Target05, SUM(gl.TargetAdjusted06) AS Target06,
		SUM(gl.TargetAdjusted07)  AS Target07, SUM(gl.TargetAdjusted08) AS Target08, SUM(gl.TargetAdjusted09) AS Target09, SUM(gl.TargetAdjusted10) AS Target10, SUM(gl.TargetAdjusted11) AS Target11, SUM(gl.TargetAdjusted12) AS Target12,

		SUM(gl.BudgetAdjusted01) AS Budget01, SUM(gl.BudgetAdjusted02) AS Budget02, SUM(gl.BudgetAdjusted03) AS Budget03, SUM(gl.BudgetAdjusted04) AS Budget04, SUM(gl.BudgetAdjusted05) AS Budget05, SUM(gl.BudgetAdjusted06) AS Budget06,
		SUM(gl.BudgetAdjusted07) AS Budget07, SUM(gl.BudgetAdjusted08) AS Budget08, SUM(gl.BudgetAdjusted09) AS Budget09, SUM(gl.BudgetAdjusted10) AS Budget10, SUM(gl.BudgetAdjusted11) AS Budget11, SUM(gl.BudgetAdjusted12) AS Budget12,

		SUM(gl.ProjectionAdjusted01) AS Projection01, SUM(gl.ProjectionAdjusted02) AS Projection02, SUM(gl.ProjectionAdjusted03) AS Projection03, SUM(gl.ProjectionAdjusted04) AS Projection04, SUM(gl.ProjectionAdjusted05) AS Projection05, SUM(gl.ProjectionAdjusted06) AS Projection06,
		SUM(gl.ProjectionAdjusted07) AS Projection07, SUM(gl.ProjectionAdjusted08) AS Projection08, SUM(gl.ProjectionAdjusted09) AS Projection09, SUM(gl.ProjectionAdjusted10) AS Projection10, SUM(gl.ProjectionAdjusted11) AS Projection11, SUM(gl.ProjectionAdjusted12) AS Projection12
	FROM fp.GeneralLedger gl
		INNER JOIN #ReimbursementTargeting rt ON rt.EntityID = gl.EntityID
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID
	WHERE gl.BudgetConfigID = @BudgetConfigID 
		AND gl.APEModelSectionID = @Deduction
		AND a.OBModelSectionName = 'Deductions - Reimbursement'
		AND gl.DepartmentID NOT IN (SELECT DepartmentID FROM fp.GeneralLedgerReimbursementExcludedDepartments
			WHERE BudgetConfigGUID = bc.BudgetConfigGUID)
	GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, gl.APEModelSectionID, a.PatientClassID


	INSERT INTO #ReimbursementGL(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,

		[TargetAdjusted01], [TargetAdjusted02], [TargetAdjusted03], [TargetAdjusted04], [TargetAdjusted05], [TargetAdjusted06],
		[TargetAdjusted07], [TargetAdjusted08], [TargetAdjusted09], [TargetAdjusted10], [TargetAdjusted11], [TargetAdjusted12],

		[TargetAdjustedNetAsPercentOfCharge01], [TargetAdjustedNetAsPercentOfCharge02],	[TargetAdjustedNetAsPercentOfCharge03],	[TargetAdjustedNetAsPercentOfCharge04],
		[TargetAdjustedNetAsPercentOfCharge05], [TargetAdjustedNetAsPercentOfCharge06], [TargetAdjustedNetAsPercentOfCharge07], [TargetAdjustedNetAsPercentOfCharge08],
		[TargetAdjustedNetAsPercentOfCharge09],	[TargetAdjustedNetAsPercentOfCharge10],	[TargetAdjustedNetAsPercentOfCharge11], [TargetAdjustedNetAsPercentOfCharge12],

		[BudgetAdjusted01],	[BudgetAdjusted02],	[BudgetAdjusted03],	[BudgetAdjusted04],	[BudgetAdjusted05],	[BudgetAdjusted06],
		[BudgetAdjusted07],	[BudgetAdjusted08],	[BudgetAdjusted09],	[BudgetAdjusted10],	[BudgetAdjusted11],	[BudgetAdjusted12],

		[BudgetAdjustedNetAsPercentOfCharge01],	[BudgetAdjustedNetAsPercentOfCharge02],	[BudgetAdjustedNetAsPercentOfCharge03],	[BudgetAdjustedNetAsPercentOfCharge04],
		[BudgetAdjustedNetAsPercentOfCharge05],	[BudgetAdjustedNetAsPercentOfCharge06],	[BudgetAdjustedNetAsPercentOfCharge07],	[BudgetAdjustedNetAsPercentOfCharge08],
		[BudgetAdjustedNetAsPercentOfCharge09],	[BudgetAdjustedNetAsPercentOfCharge10],	[BudgetAdjustedNetAsPercentOfCharge11],	[BudgetAdjustedNetAsPercentOfCharge12],

		[ProjectionAdjusted01],	[ProjectionAdjusted02],	[ProjectionAdjusted03],	[ProjectionAdjusted04],	[ProjectionAdjusted05],	[ProjectionAdjusted06],
		[ProjectionAdjusted07],	[ProjectionAdjusted08],	[ProjectionAdjusted09],	[ProjectionAdjusted10],	[ProjectionAdjusted11],	[ProjectionAdjusted12],

		[ProjectionAdjustedNetAsPercentOfCharge01],	[ProjectionAdjustedNetAsPercentOfCharge02],	[ProjectionAdjustedNetAsPercentOfCharge03],	[ProjectionAdjustedNetAsPercentOfCharge04],
		[ProjectionAdjustedNetAsPercentOfCharge05],	[ProjectionAdjustedNetAsPercentOfCharge06],	[ProjectionAdjustedNetAsPercentOfCharge07],	[ProjectionAdjustedNetAsPercentOfCharge08],
		[ProjectionAdjustedNetAsPercentOfCharge09],	[ProjectionAdjustedNetAsPercentOfCharge10],	[ProjectionAdjustedNetAsPercentOfCharge11],	[ProjectionAdjustedNetAsPercentOfCharge12]
		)
	SELECT DISTINCT 
		r.BudgetConfigID, r.EntityGroupConfigID, r.EntityID, r.PayorGroupID, r.PatientClassID,
		
		--Target
		-- %ofCharge = NetReimbursement/revenue = (revenue - deduction) / revenue

		r.Target01, r.Target02, r.Target03, r.Target04, r.Target05, r.Target06, r.Target07, r.Target08, r.Target09, r.Target10, r.Target11, r.Target12,

		CASE WHEN r.Target01 IS NULL OR r.Target01 = 0 THEN 0 WHEN d.Target01 IS NULL THEN 1
		ELSE (r.Target01 - d.Target01) / r.Target01 END AS TargetAdjustedNetAsPercentOfCharge01,
		CASE WHEN r.Target02 IS NULL OR r.Target02 = 0 THEN 0 WHEN d.Target02 IS NULL THEN 1
		ELSE (r.Target02 - d.Target02) / r.Target02 END AS TargetAdjustedNetAsPercentOfCharge02,
		CASE WHEN r.Target03 IS NULL OR r.Target03 = 0 THEN 0 WHEN d.Target03 IS NULL THEN 1
		ELSE (r.Target03 - d.Target03) / r.Target03 END AS TargetAdjustedNetAsPercentOfCharge03,
		CASE WHEN r.Target04 IS NULL OR r.Target04 = 0 THEN 0 WHEN d.Target04 IS NULL THEN 1 
		ELSE (r.Target04 - d.Target04) / r.Target04 END AS TargetAdjustedNetAsPercentOfCharge04,
		CASE WHEN r.Target05 IS NULL OR r.Target05 = 0 THEN 0 WHEN d.Target05 IS NULL THEN 1
		ELSE (r.Target05 - d.Target05) / r.Target05 END AS TargetAdjustedNetAsPercentOfCharge05,
		CASE WHEN r.Target06 IS NULL OR r.Target06 = 0 THEN 0 WHEN d.Target06 IS NULL THEN 1
		ELSE (r.Target06 - d.Target06) / r.Target06 END AS TargetAdjustedNetAsPercentOfCharge06,
		CASE WHEN r.Target07 IS NULL OR r.Target07 = 0 THEN 0 WHEN d.Target07 IS NULL THEN 1 
		ELSE (r.Target07 - d.Target07) / r.Target07 END AS TargetAdjustedNetAsPercentOfCharge07,
		CASE WHEN r.Target08 IS NULL OR r.Target08 = 0 THEN 0 WHEN d.Target08 IS NULL THEN 1 
		ELSE (r.Target08 - d.Target08) / r.Target08 END AS TargetAdjustedNetAsPercentOfCharge08,
		CASE WHEN r.Target09 IS NULL OR r.Target09 = 0 THEN 0 WHEN d.Target09 IS NULL THEN 1 
		ELSE (r.Target09 - d.Target09) / r.Target09 END AS TargetAdjustedNetAsPercentOfCharge09,
		CASE WHEN r.Target10 IS NULL OR r.Target10 = 0 THEN 0 WHEN d.Target10 IS NULL THEN 1
		ELSE (r.Target10 - d.Target10) / r.Target10 END AS TargetAdjustedNetAsPercentOfCharge10,
		CASE WHEN r.Target11 IS NULL OR r.Target11 = 0 THEN 0 WHEN d.Target11 IS NULL THEN 1 
		ELSE (r.Target11 - d.Target11) / r.Target11 END AS TargetAdjustedNetAsPercentOfCharge11,
		CASE WHEN r.Target12 IS NULL OR r.Target12 = 0 THEN 0 WHEN d.Target12 IS NULL THEN 1 
		ELSE (r.Target12 - d.Target12) / r.Target12 END AS TargetAdjustedNetAsPercentOfCharge12,

		--Budget
		r.Budget01, r.Budget02, r.Budget03, r.Budget04, r.Budget05, r.Budget06, r.Budget07, r.Budget08, r.Budget09, r.Budget10, r.Budget11, r.Budget12,

		CASE WHEN r.Budget01 IS NULL OR r.Budget01 = 0 THEN 0 WHEN d.Budget01 IS NULL THEN 1 
		ELSE (r.Budget01 - d.Budget01) / r.Budget01 END AS BudgetAdjustedNetAsPercentOfCharge01,
		CASE WHEN r.Budget02 IS NULL OR r.Budget02 = 0 THEN 0 WHEN d.Budget02 IS NULL THEN 1 
		ELSE (r.Budget02 - d.Budget02) / r.Budget02 END AS BudgetAdjustedNetAsPercentOfCharge02,
		CASE WHEN r.Budget03 IS NULL OR r.Budget03 = 0 THEN 0 WHEN d.Budget03 IS NULL THEN 1 
		ELSE (r.Budget03 - d.Budget03) / r.Budget03 END AS BudgetAdjustedNetAsPercentOfCharge03,
		CASE WHEN r.Budget04 IS NULL OR r.Budget04 = 0 THEN 0 WHEN d.Budget04 IS NULL THEN 1 
		ELSE (r.Budget04 - d.Budget04) / r.Budget04 END AS BudgetAdjustedNetAsPercentOfCharge04,
		CASE WHEN r.Budget05 IS NULL OR r.Budget05 = 0 THEN 0 WHEN d.Budget05 IS NULL THEN 1 
		ELSE (r.Budget05 - d.Budget05) / r.Budget05 END AS BudgetAdjustedNetAsPercentOfCharge05,
		CASE WHEN r.Budget06 IS NULL OR r.Budget06 = 0 THEN 0 WHEN d.Budget06 IS NULL THEN 1 
		ELSE (r.Budget06 - d.Budget06) / r.Budget06 END AS BudgetAdjustedNetAsPercentOfCharge06,
		CASE WHEN r.Budget07 IS NULL OR r.Budget07 = 0 THEN 0 WHEN d.Budget07 IS NULL THEN 1 
		ELSE (r.Budget07 - d.Budget07) / r.Budget07 END AS BudgetAdjustedNetAsPercentOfCharge07,
		CASE WHEN r.Budget08 IS NULL OR r.Budget08 = 0 THEN 0 WHEN d.Budget08 IS NULL THEN 1 
		ELSE (r.Budget08 - d.Budget08) / r.Budget08 END AS BudgetAdjustedNetAsPercentOfCharge08,
		CASE WHEN r.Budget09 IS NULL OR r.Budget09 = 0 THEN 0 WHEN d.Budget09 IS NULL THEN 1 
		ELSE (r.Budget09 - d.Budget09) / r.Budget09 END AS BudgetAdjustedNetAsPercentOfCharge09,
		CASE WHEN r.Budget10 IS NULL OR r.Budget10 = 0 THEN 0 WHEN d.Budget10 IS NULL THEN 1 
		ELSE (r.Budget10 - d.Budget10) / r.Budget10 END AS BudgetAdjustedNetAsPercentOfCharge10,
		CASE WHEN r.Budget11 IS NULL OR r.Budget11 = 0 THEN 0 WHEN d.Budget11 IS NULL THEN 1 
		ELSE (r.Budget11 - d.Budget11) / r.Budget11 END AS BudgetAdjustedNetAsPercentOfCharge11,
		CASE WHEN r.Budget12 IS NULL OR r.Budget12 = 0 THEN 0 WHEN d.Budget12 IS NULL THEN 1 
		ELSE (r.Budget12 - d.Budget12) / r.Budget12 END AS BudgetAdjustedNetAsPercentOfCharge12,

		--Projection
		r.Projection01, r.Projection02, r.Projection03, r.Projection04, r.Projection05, r.Projection06, r.Projection07, r.Projection08, r.Projection09, r.Projection10, r.Projection11, r.Projection12,

		CASE WHEN r.Projection01 IS NULL OR r.Projection01 = 0 THEN 0 WHEN d.Projection01 IS NULL THEN 1 
		ELSE (r.Projection01 - d.Projection01) / r.Projection01 END AS ProjectionAdjustedNetAsPercentOfCharge01,
		CASE WHEN r.Projection02 IS NULL OR r.Projection02 = 0 THEN 0 WHEN d.Projection02 IS NULL THEN 1 
		ELSE (r.Projection02 - d.Projection02) / r.Projection02 END AS ProjectionAdjustedNetAsPercentOfCharge02,
		CASE WHEN r.Projection03 IS NULL OR r.Projection03 = 0 THEN 0 WHEN d.Projection03 IS NULL THEN 1 
		ELSE (r.Projection03 - d.Projection03) / r.Projection03 END AS ProjectionAdjustedNetAsPercentOfCharge03,
		CASE WHEN r.Projection04 IS NULL OR r.Projection04 = 0 THEN 0 WHEN d.Projection04 IS NULL THEN 1 
		ELSE (r.Projection04 - d.Projection04) / r.Projection04 END AS ProjectionAdjustedNetAsPercentOfCharge04,
		CASE WHEN r.Projection05 IS NULL OR r.Projection05 = 0 THEN 0 WHEN d.Projection05 IS NULL THEN 1 
		ELSE (r.Projection05 - d.Projection05) / r.Projection05 END AS ProjectionAdjustedNetAsPercentOfCharge05,
		CASE WHEN r.Projection06 IS NULL OR r.Projection06 = 0 THEN 0 WHEN d.Projection06 IS NULL THEN 1 
		ELSE (r.Projection06 - d.Projection06) / r.Projection06 END AS ProjectionAdjustedNetAsPercentOfCharge06,
		CASE WHEN r.Projection07 IS NULL OR r.Projection07 = 0 THEN 0 WHEN d.Projection07 IS NULL THEN 1 
		ELSE (r.Projection07 - d.Projection07) / r.Projection07 END AS ProjectionAdjustedNetAsPercentOfCharge07,
		CASE WHEN r.Projection08 IS NULL OR r.Projection08 = 0 THEN 0 WHEN d.Projection08 IS NULL THEN 1 
		ELSE (r.Projection08 - d.Projection08) / r.Projection08 END AS ProjectionAdjustedNetAsPercentOfCharge08,
		CASE WHEN r.Projection09 IS NULL OR r.Projection09 = 0 THEN 0 WHEN d.Projection09 IS NULL THEN 1 
		ELSE (r.Projection09 - d.Projection09) / r.Projection09 END AS ProjectionAdjustedNetAsPercentOfCharge09,
		CASE WHEN r.Projection10 IS NULL OR r.Projection10 = 0 THEN 0 WHEN d.Projection10 IS NULL THEN 1 
		ELSE (r.Projection10 - d.Projection10) / r.Projection10 END AS ProjectionAdjustedNetAsPercentOfCharge10,
		CASE WHEN r.Projection11 IS NULL OR r.Projection11 = 0 THEN 0 WHEN d.Projection11 IS NULL THEN 1 
		ELSE (r.Projection11 - d.Projection11) / r.Projection11 END AS ProjectionAdjustedNetAsPercentOfCharge11,
		CASE WHEN r.Projection12 IS NULL OR r.Projection12 = 0 THEN 0 WHEN d.Projection12 IS NULL THEN 1 
		ELSE (r.Projection12 - d.Projection12) / r.Projection12 END AS ProjectionAdjustedNetAsPercentOfCharge12

	FROM #RevenueData r
		LEFT JOIN #DeductionData d ON  d.BudgetConfigID = r.BudgetConfigID
		AND d.EntityGroupConfigID = r.EntityGroupConfigID
		AND d.EntityID = r.EntityID 
		AND d.PayorGroupID = r.PayorGroupID 
		AND d.PatientClassID = r.PatientClassID
	WHERE r.BudgetConfigID = @BudgetConfigID 

	IF (@IsDebug = 1)
	BEGIN
		SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment
		SELECT '#ReimbursementTargeting', EntityID FROM #ReimbursementTargeting
		SELECT '#RevenueData', * FROM #RevenueData
		SELECT '#DeductionData', * FROM #DeductionData
		SELECT '#ReimbursementGL', * FROM #ReimbursementGL
	END ELSE
	BEGIN
		-- Publish Target
		;WITH TGT AS   
		(  
			SELECT rgl.ReimbursementGeneralLedgerID, rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID,
				[TargetAdjusted01], [TargetAdjusted02], [TargetAdjusted03], [TargetAdjusted04], [TargetAdjusted05], [TargetAdjusted06],
				[TargetAdjusted07], [TargetAdjusted08], [TargetAdjusted09], [TargetAdjusted10], [TargetAdjusted11], [TargetAdjusted12],

				[TargetAdjustedNetAsPercentOfCharge01], [TargetAdjustedNetAsPercentOfCharge02],	[TargetAdjustedNetAsPercentOfCharge03],	[TargetAdjustedNetAsPercentOfCharge04],
				[TargetAdjustedNetAsPercentOfCharge05], [TargetAdjustedNetAsPercentOfCharge06], [TargetAdjustedNetAsPercentOfCharge07], [TargetAdjustedNetAsPercentOfCharge08],
				[TargetAdjustedNetAsPercentOfCharge09],	[TargetAdjustedNetAsPercentOfCharge10],	[TargetAdjustedNetAsPercentOfCharge11], [TargetAdjustedNetAsPercentOfCharge12]
			FROM [fp].[ReimbursementGeneralLedger] rgl  
			WHERE rgl.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #ReimbursementGL AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.PatientClassID = src.PatientClassID
		)  
		WHEN MATCHED AND (
							target.TargetAdjusted01 <> src.TargetAdjusted01 OR
							target.TargetAdjusted02 <> src.TargetAdjusted02 OR
							target.TargetAdjusted03 <> src.TargetAdjusted03 OR
							target.TargetAdjusted04 <> src.TargetAdjusted04 OR
							target.TargetAdjusted05 <> src.TargetAdjusted05 OR
							target.TargetAdjusted06 <> src.TargetAdjusted06 OR
							target.TargetAdjusted07 <> src.TargetAdjusted07 OR
							target.TargetAdjusted08 <> src.TargetAdjusted08 OR
							target.TargetAdjusted09 <> src.TargetAdjusted09 OR
							target.TargetAdjusted10 <> src.TargetAdjusted10 OR
							target.TargetAdjusted11 <> src.TargetAdjusted11 OR
							target.TargetAdjusted12 <> src.TargetAdjusted12 OR
							( @IsUpdatePerOfCharge = 1 AND (
								target.TargetAdjustedNetAsPercentOfCharge01 <> src.TargetAdjustedNetAsPercentOfCharge01 OR
								target.TargetAdjustedNetAsPercentOfCharge02 <> src.TargetAdjustedNetAsPercentOfCharge02 OR
								target.TargetAdjustedNetAsPercentOfCharge03 <> src.TargetAdjustedNetAsPercentOfCharge03 OR
								target.TargetAdjustedNetAsPercentOfCharge04 <> src.TargetAdjustedNetAsPercentOfCharge04 OR
								target.TargetAdjustedNetAsPercentOfCharge05 <> src.TargetAdjustedNetAsPercentOfCharge05 OR
								target.TargetAdjustedNetAsPercentOfCharge06 <> src.TargetAdjustedNetAsPercentOfCharge06 OR
								target.TargetAdjustedNetAsPercentOfCharge07 <> src.TargetAdjustedNetAsPercentOfCharge07 OR
								target.TargetAdjustedNetAsPercentOfCharge08 <> src.TargetAdjustedNetAsPercentOfCharge08 OR
								target.TargetAdjustedNetAsPercentOfCharge09 <> src.TargetAdjustedNetAsPercentOfCharge09 OR
								target.TargetAdjustedNetAsPercentOfCharge10 <> src.TargetAdjustedNetAsPercentOfCharge10 OR
								target.TargetAdjustedNetAsPercentOfCharge11 <> src.TargetAdjustedNetAsPercentOfCharge11 OR
								target.TargetAdjustedNetAsPercentOfCharge12 <> src.TargetAdjustedNetAsPercentOfCharge12 )
							)
						 )
		THEN  
			UPDATE SET target.TargetAdjusted01 = src.TargetAdjusted01,
					   target.TargetAdjusted02 = src.TargetAdjusted02,
					   target.TargetAdjusted03 = src.TargetAdjusted03,
					   target.TargetAdjusted04 = src.TargetAdjusted04,
					   target.TargetAdjusted05 = src.TargetAdjusted05,
					   target.TargetAdjusted06 = src.TargetAdjusted06,
					   target.TargetAdjusted07 = src.TargetAdjusted07,
					   target.TargetAdjusted08 = src.TargetAdjusted08,
					   target.TargetAdjusted09 = src.TargetAdjusted09,
					   target.TargetAdjusted10 = src.TargetAdjusted10,
					   target.TargetAdjusted11 = src.TargetAdjusted11,
					   target.TargetAdjusted12 = src.TargetAdjusted12,

					   target.TargetAdjustedNetAsPercentOfCharge01 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge01 ELSE target.TargetAdjustedNetAsPercentOfCharge01 END,
					   target.TargetAdjustedNetAsPercentOfCharge02 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge02 ELSE target.TargetAdjustedNetAsPercentOfCharge02 END,
					   target.TargetAdjustedNetAsPercentOfCharge03 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge03 ELSE target.TargetAdjustedNetAsPercentOfCharge03 END,
					   target.TargetAdjustedNetAsPercentOfCharge04 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge04 ELSE target.TargetAdjustedNetAsPercentOfCharge04 END,
					   target.TargetAdjustedNetAsPercentOfCharge05 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge05 ELSE target.TargetAdjustedNetAsPercentOfCharge05 END,
					   target.TargetAdjustedNetAsPercentOfCharge06 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge06 ELSE target.TargetAdjustedNetAsPercentOfCharge06 END,
					   target.TargetAdjustedNetAsPercentOfCharge07 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge07 ELSE target.TargetAdjustedNetAsPercentOfCharge07 END,
					   target.TargetAdjustedNetAsPercentOfCharge08 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge08 ELSE target.TargetAdjustedNetAsPercentOfCharge08 END,
					   target.TargetAdjustedNetAsPercentOfCharge09 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge09 ELSE target.TargetAdjustedNetAsPercentOfCharge09 END,
					   target.TargetAdjustedNetAsPercentOfCharge10 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge10 ELSE target.TargetAdjustedNetAsPercentOfCharge10 END,
					   target.TargetAdjustedNetAsPercentOfCharge11 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge11 ELSE target.TargetAdjustedNetAsPercentOfCharge11 END,
					   target.TargetAdjustedNetAsPercentOfCharge12 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge12 ELSE target.TargetAdjustedNetAsPercentOfCharge12 END
		OUTPUT 
			INSERTED.ReimbursementGeneralLedgerID
		INTO
			#targetBasisIDs (ReimbursementGeneralLedgerID);

		-- Publish Budget
		;WITH TGT AS   
		(  
			SELECT rgl.ReimbursementGeneralLedgerID, rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID,
				[BudgetAdjusted01],	[BudgetAdjusted02],	[BudgetAdjusted03],	[BudgetAdjusted04],	[BudgetAdjusted05],	[BudgetAdjusted06],
				[BudgetAdjusted07],	[BudgetAdjusted08],	[BudgetAdjusted09],	[BudgetAdjusted10],	[BudgetAdjusted11],	[BudgetAdjusted12],

				[BudgetAdjustedNetAsPercentOfCharge01],	[BudgetAdjustedNetAsPercentOfCharge02],	[BudgetAdjustedNetAsPercentOfCharge03],	[BudgetAdjustedNetAsPercentOfCharge04],
				[BudgetAdjustedNetAsPercentOfCharge05],	[BudgetAdjustedNetAsPercentOfCharge06],	[BudgetAdjustedNetAsPercentOfCharge07],	[BudgetAdjustedNetAsPercentOfCharge08],
				[BudgetAdjustedNetAsPercentOfCharge09],	[BudgetAdjustedNetAsPercentOfCharge10],	[BudgetAdjustedNetAsPercentOfCharge11],	[BudgetAdjustedNetAsPercentOfCharge12]
				FROM [fp].[ReimbursementGeneralLedger] rgl  
			WHERE rgl.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #ReimbursementGL AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.PatientClassID = src.PatientClassID
		)  
		WHEN MATCHED AND (
							target.BudgetAdjusted01 <> src.BudgetAdjusted01 OR
							target.BudgetAdjusted02 <> src.BudgetAdjusted02 OR
							target.BudgetAdjusted03 <> src.BudgetAdjusted03 OR
							target.BudgetAdjusted04 <> src.BudgetAdjusted04 OR
							target.BudgetAdjusted05 <> src.BudgetAdjusted05 OR
							target.BudgetAdjusted06 <> src.BudgetAdjusted06 OR
							target.BudgetAdjusted07 <> src.BudgetAdjusted07 OR
							target.BudgetAdjusted08 <> src.BudgetAdjusted08 OR
							target.BudgetAdjusted09 <> src.BudgetAdjusted09 OR
							target.BudgetAdjusted10 <> src.BudgetAdjusted10 OR
							target.BudgetAdjusted11 <> src.BudgetAdjusted11 OR
							target.BudgetAdjusted12 <> src.BudgetAdjusted12 OR
							( @IsUpdatePerOfCharge = 1 AND (
								target.BudgetAdjustedNetAsPercentOfCharge01 <> src.BudgetAdjustedNetAsPercentOfCharge01 OR
								target.BudgetAdjustedNetAsPercentOfCharge02 <> src.BudgetAdjustedNetAsPercentOfCharge02 OR
								target.BudgetAdjustedNetAsPercentOfCharge03 <> src.BudgetAdjustedNetAsPercentOfCharge03 OR
								target.BudgetAdjustedNetAsPercentOfCharge04 <> src.BudgetAdjustedNetAsPercentOfCharge04 OR
								target.BudgetAdjustedNetAsPercentOfCharge05 <> src.BudgetAdjustedNetAsPercentOfCharge05 OR
								target.BudgetAdjustedNetAsPercentOfCharge06 <> src.BudgetAdjustedNetAsPercentOfCharge06 OR
								target.BudgetAdjustedNetAsPercentOfCharge07 <> src.BudgetAdjustedNetAsPercentOfCharge07 OR
								target.BudgetAdjustedNetAsPercentOfCharge08 <> src.BudgetAdjustedNetAsPercentOfCharge08 OR
								target.BudgetAdjustedNetAsPercentOfCharge09 <> src.BudgetAdjustedNetAsPercentOfCharge09 OR
								target.BudgetAdjustedNetAsPercentOfCharge10 <> src.BudgetAdjustedNetAsPercentOfCharge10 OR
								target.BudgetAdjustedNetAsPercentOfCharge11 <> src.BudgetAdjustedNetAsPercentOfCharge11 OR
								target.BudgetAdjustedNetAsPercentOfCharge12 <> src.BudgetAdjustedNetAsPercentOfCharge12 )
							)
						 )
		THEN  
			UPDATE SET target.BudgetAdjusted01 = src.BudgetAdjusted01,
					   target.BudgetAdjusted02 = src.BudgetAdjusted02,
					   target.BudgetAdjusted03 = src.BudgetAdjusted03,
					   target.BudgetAdjusted04 = src.BudgetAdjusted04,
					   target.BudgetAdjusted05 = src.BudgetAdjusted05,
					   target.BudgetAdjusted06 = src.BudgetAdjusted06,
					   target.BudgetAdjusted07 = src.BudgetAdjusted07,
					   target.BudgetAdjusted08 = src.BudgetAdjusted08,
					   target.BudgetAdjusted09 = src.BudgetAdjusted09,
					   target.BudgetAdjusted10 = src.BudgetAdjusted10,
					   target.BudgetAdjusted11 = src.BudgetAdjusted11,
					   target.BudgetAdjusted12 = src.BudgetAdjusted12,

					   target.BudgetAdjustedNetAsPercentOfCharge01 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge01 ELSE target.BudgetAdjustedNetAsPercentOfCharge01 END,
					   target.BudgetAdjustedNetAsPercentOfCharge02 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge02 ELSE target.BudgetAdjustedNetAsPercentOfCharge02 END,
					   target.BudgetAdjustedNetAsPercentOfCharge03 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge03 ELSE target.BudgetAdjustedNetAsPercentOfCharge03 END,
					   target.BudgetAdjustedNetAsPercentOfCharge04 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge04 ELSE target.BudgetAdjustedNetAsPercentOfCharge04 END,
					   target.BudgetAdjustedNetAsPercentOfCharge05 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge05 ELSE target.BudgetAdjustedNetAsPercentOfCharge05 END,
					   target.BudgetAdjustedNetAsPercentOfCharge06 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge06 ELSE target.BudgetAdjustedNetAsPercentOfCharge06 END,
					   target.BudgetAdjustedNetAsPercentOfCharge07 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge07 ELSE target.BudgetAdjustedNetAsPercentOfCharge07 END,
					   target.BudgetAdjustedNetAsPercentOfCharge08 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge08 ELSE target.BudgetAdjustedNetAsPercentOfCharge08 END,
					   target.BudgetAdjustedNetAsPercentOfCharge09 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge09 ELSE target.BudgetAdjustedNetAsPercentOfCharge09 END,
					   target.BudgetAdjustedNetAsPercentOfCharge10 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge10 ELSE target.BudgetAdjustedNetAsPercentOfCharge10 END,
					   target.BudgetAdjustedNetAsPercentOfCharge11 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge11 ELSE target.BudgetAdjustedNetAsPercentOfCharge11 END,
					   target.BudgetAdjustedNetAsPercentOfCharge12 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge12 ELSE target.BudgetAdjustedNetAsPercentOfCharge12 END
		OUTPUT 
			INSERTED.ReimbursementGeneralLedgerID
		INTO
			#budgetBasisIDs (ReimbursementGeneralLedgerID);


		
		-- Publish Projection
		;WITH TGT AS   
		(  
			SELECT rgl.ReimbursementGeneralLedgerID, rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID,
				[ProjectionAdjusted01],	[ProjectionAdjusted02],	[ProjectionAdjusted03],	[ProjectionAdjusted04],	[ProjectionAdjusted05],	[ProjectionAdjusted06],
				[ProjectionAdjusted07],	[ProjectionAdjusted08],	[ProjectionAdjusted09],	[ProjectionAdjusted10],	[ProjectionAdjusted11],	[ProjectionAdjusted12],

				[ProjectionAdjustedNetAsPercentOfCharge01],	[ProjectionAdjustedNetAsPercentOfCharge02],	[ProjectionAdjustedNetAsPercentOfCharge03],	[ProjectionAdjustedNetAsPercentOfCharge04],
				[ProjectionAdjustedNetAsPercentOfCharge05],	[ProjectionAdjustedNetAsPercentOfCharge06],	[ProjectionAdjustedNetAsPercentOfCharge07],	[ProjectionAdjustedNetAsPercentOfCharge08],
				[ProjectionAdjustedNetAsPercentOfCharge09],	[ProjectionAdjustedNetAsPercentOfCharge10],	[ProjectionAdjustedNetAsPercentOfCharge11],	[ProjectionAdjustedNetAsPercentOfCharge12]
			FROM [fp].[ReimbursementGeneralLedger] rgl  
			WHERE rgl.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #ReimbursementGL AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.PatientClassID = src.PatientClassID
		)  
		WHEN MATCHED AND (
							target.ProjectionAdjusted01 <> src.ProjectionAdjusted01 OR
							target.ProjectionAdjusted02 <> src.ProjectionAdjusted02 OR
							target.ProjectionAdjusted03 <> src.ProjectionAdjusted03 OR
							target.ProjectionAdjusted04 <> src.ProjectionAdjusted04 OR
							target.ProjectionAdjusted05 <> src.ProjectionAdjusted05 OR
							target.ProjectionAdjusted06 <> src.ProjectionAdjusted06 OR
							target.ProjectionAdjusted07 <> src.ProjectionAdjusted07 OR
							target.ProjectionAdjusted08 <> src.ProjectionAdjusted08 OR
							target.ProjectionAdjusted09 <> src.ProjectionAdjusted09 OR
							target.ProjectionAdjusted10 <> src.ProjectionAdjusted10 OR
							target.ProjectionAdjusted11 <> src.ProjectionAdjusted11 OR
							target.ProjectionAdjusted12 <> src.ProjectionAdjusted12 OR
							( @IsUpdatePerOfCharge = 1 AND (
								target.ProjectionAdjustedNetAsPercentOfCharge01 <> src.ProjectionAdjustedNetAsPercentOfCharge01 OR
								target.ProjectionAdjustedNetAsPercentOfCharge02 <> src.ProjectionAdjustedNetAsPercentOfCharge02 OR
								target.ProjectionAdjustedNetAsPercentOfCharge03 <> src.ProjectionAdjustedNetAsPercentOfCharge03 OR
								target.ProjectionAdjustedNetAsPercentOfCharge04 <> src.ProjectionAdjustedNetAsPercentOfCharge04 OR
								target.ProjectionAdjustedNetAsPercentOfCharge05 <> src.ProjectionAdjustedNetAsPercentOfCharge05 OR
								target.ProjectionAdjustedNetAsPercentOfCharge06 <> src.ProjectionAdjustedNetAsPercentOfCharge06 OR
								target.ProjectionAdjustedNetAsPercentOfCharge07 <> src.ProjectionAdjustedNetAsPercentOfCharge07 OR
								target.ProjectionAdjustedNetAsPercentOfCharge08 <> src.ProjectionAdjustedNetAsPercentOfCharge08 OR
								target.ProjectionAdjustedNetAsPercentOfCharge09 <> src.ProjectionAdjustedNetAsPercentOfCharge09 OR
								target.ProjectionAdjustedNetAsPercentOfCharge10 <> src.ProjectionAdjustedNetAsPercentOfCharge10 OR
								target.ProjectionAdjustedNetAsPercentOfCharge11 <> src.ProjectionAdjustedNetAsPercentOfCharge11 OR
								target.ProjectionAdjustedNetAsPercentOfCharge12 <> src.ProjectionAdjustedNetAsPercentOfCharge12 )
							)
						 )
		THEN  
			UPDATE SET target.ProjectionAdjusted01 = src.ProjectionAdjusted01,
					   target.ProjectionAdjusted02 = src.ProjectionAdjusted02,
					   target.ProjectionAdjusted03 = src.ProjectionAdjusted03,
					   target.ProjectionAdjusted04 = src.ProjectionAdjusted04,
					   target.ProjectionAdjusted05 = src.ProjectionAdjusted05,
					   target.ProjectionAdjusted06 = src.ProjectionAdjusted06,
					   target.ProjectionAdjusted07 = src.ProjectionAdjusted07,
					   target.ProjectionAdjusted08 = src.ProjectionAdjusted08,
					   target.ProjectionAdjusted09 = src.ProjectionAdjusted09,
					   target.ProjectionAdjusted10 = src.ProjectionAdjusted10,
					   target.ProjectionAdjusted11 = src.ProjectionAdjusted11,
					   target.ProjectionAdjusted12 = src.ProjectionAdjusted12,

					   target.ProjectionAdjustedNetAsPercentOfCharge01 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge01 ELSE target.ProjectionAdjustedNetAsPercentOfCharge01 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge02 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge02 ELSE target.ProjectionAdjustedNetAsPercentOfCharge02 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge03 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge03 ELSE target.ProjectionAdjustedNetAsPercentOfCharge03 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge04 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge04 ELSE target.ProjectionAdjustedNetAsPercentOfCharge04 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge05 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge05 ELSE target.ProjectionAdjustedNetAsPercentOfCharge05 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge06 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge06 ELSE target.ProjectionAdjustedNetAsPercentOfCharge06 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge07 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge07 ELSE target.ProjectionAdjustedNetAsPercentOfCharge07 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge08 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge08 ELSE target.ProjectionAdjustedNetAsPercentOfCharge08 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge09 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge09 ELSE target.ProjectionAdjustedNetAsPercentOfCharge09 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge10 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge10 ELSE target.ProjectionAdjustedNetAsPercentOfCharge10 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge11 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge11 ELSE target.ProjectionAdjustedNetAsPercentOfCharge11 END,
					   target.ProjectionAdjustedNetAsPercentOfCharge12 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge12 ELSE target.ProjectionAdjustedNetAsPercentOfCharge12 END
		OUTPUT 
			INSERTED.ReimbursementGeneralLedgerID
		INTO
			#projectionBasisIDs (ReimbursementGeneralLedgerID);

		-- Find out what was changed. We can cross apply all 12 months in this case because months are on rows. If we change
		-- projection to only update the months not loaded, we'll want to update this. Unlike other procs that are similar,
		-- we don't care about the value because when we fix the change history, we take the stored rate in the change history
		-- times the volume in the DB, we don't actually care what the value was we flexed to like in the past.
		SELECT DISTINCT ReimbursementGeneralLedgerID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID
		FROM #budgetBasisIDs
			CROSS JOIN fw.DimFiscalMonth m
		WHERE m.FiscalMonthID != 0
		UNION ALL
		SELECT DISTINCT ReimbursementGeneralLedgerID AS BasisID, m.FiscalMonthID, cast(2 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID
		FROM #targetBasisIDs
			CROSS JOIN fw.DimFiscalMonth m
		WHERE m.FiscalMonthID != 0
		UNION ALL
		SELECT DISTINCT ReimbursementGeneralLedgerID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(12 as tinyint) AS TimeClassID
		FROM #projectionBasisIDs
			CROSS JOIN fw.DimFiscalMonth m
		WHERE m.FiscalMonthID != 0
	END
END
GO


---------------------------------------------

-- fp.procSampleGeneralLedgerToReimbursement_History
CREATE PROCEDURE [fp].[procSampleGeneralLedgerToReimbursement_History] 
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    05-23-2023   MZ        JAZZ-54503  Initial Creation
	** 2    07-04-2023   AO        JAZZ-57174  Adjusted formula NetAsPercentOfCharge
	** 3    10-04-2023   MZ        JAZZ-61634  Fix % of charge calculation when revenue stays the same but new deductions were found
	** 4	01-03-2024	 AO		   JAZZ-65384  Data transfer for GL is based on selected Model in Plan Config 
	** 5	08-12-2024   VZ		   JAZZ-74434  Data transfer for GL based on excluded departments
	*************************************************************/

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#ReimbursementGL') IS NOT NULL DROP TABLE #ReimbursementGL;
	IF OBJECT_ID('tempdb..#glTargeting') IS NOT NULL DROP TABLE #glTargeting;
	IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData;
	IF OBJECT_ID('tempdb..#DeductionData') IS NOT NULL DROP TABLE #DeductionData;

	CREATE TABLE #FilterByDepartment (DepartmentID INT);
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #glTargeting (EntityID INT, GeneralLedgerID INT);

	DECLARE @Revenue INT = 1;
	DECLARE @Deduction INT = 4;

	CREATE TABLE #RevenueData (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],
		[PriorYearActualValue01] [decimal](19, 8),
		[PriorYearActualValue02] [decimal](19, 8),
		[PriorYearActualValue03] [decimal](19, 8),
		[PriorYearActualValue04] [decimal](19, 8),
		[PriorYearActualValue05] [decimal](19, 8),
		[PriorYearActualValue06] [decimal](19, 8),
		[PriorYearActualValue07] [decimal](19, 8),
		[PriorYearActualValue08] [decimal](19, 8),
		[PriorYearActualValue09] [decimal](19, 8),
		[PriorYearActualValue10] [decimal](19, 8),
		[PriorYearActualValue11] [decimal](19, 8),
		[PriorYearActualValue12] [decimal](19, 8)
	)

	CREATE TABLE #DeductionData (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],
		[PriorYearActualValue01] [decimal](19, 8),
		[PriorYearActualValue02] [decimal](19, 8),
		[PriorYearActualValue03] [decimal](19, 8),
		[PriorYearActualValue04] [decimal](19, 8),
		[PriorYearActualValue05] [decimal](19, 8),
		[PriorYearActualValue06] [decimal](19, 8),
		[PriorYearActualValue07] [decimal](19, 8),
		[PriorYearActualValue08] [decimal](19, 8),
		[PriorYearActualValue09] [decimal](19, 8),
		[PriorYearActualValue10] [decimal](19, 8),
		[PriorYearActualValue11] [decimal](19, 8),
		[PriorYearActualValue12] [decimal](19, 8)
	)

	CREATE TABLE #ReimbursementGL (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],
		[PriorYearActualValue01] [decimal](19, 8),
		[PriorYearActualValue02] [decimal](19, 8),
		[PriorYearActualValue03] [decimal](19, 8),
		[PriorYearActualValue04] [decimal](19, 8),
		[PriorYearActualValue05] [decimal](19, 8),
		[PriorYearActualValue06] [decimal](19, 8),
		[PriorYearActualValue07] [decimal](19, 8),
		[PriorYearActualValue08] [decimal](19, 8),
		[PriorYearActualValue09] [decimal](19, 8),
		[PriorYearActualValue10] [decimal](19, 8),
		[PriorYearActualValue11] [decimal](19, 8),
		[PriorYearActualValue12] [decimal](19, 8),

		[PriorYearActualValueNetAsPercentOfCharge01] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge02] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge03] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge04] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge05] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge06] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge07] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge08] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge09] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge10] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge11] [decimal](19, 8),
		[PriorYearActualValueNetAsPercentOfCharge12] [decimal](19, 8)
	)

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE gl.BudgetConfigID  = @BudgetConfigID 
			AND ((bc.DefaultReimbursementNetRevenueModelID = 2 
				AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) 
				OR rnrm.NetRevenueModelID = 2) -- GL Model
	END

	DELETE #FilterByDepartment
	WHERE DepartmentID IN (
		SELECT DepartmentID 
		FROM fp.GeneralLedgerReimbursementExcludedDepartments glred
			JOIN fp.BudgetConfig bc ON glred.BudgetConfigGuid = bc.BudgetConfigGuid
		WHERE bc.BudgetConfigID = @BudgetConfigID)

	--Revenue
	INSERT INTO #RevenueData(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		PriorYearActualValue01,	PriorYearActualValue02,	PriorYearActualValue03,	PriorYearActualValue04,	PriorYearActualValue05,	PriorYearActualValue06,
		PriorYearActualValue07,	PriorYearActualValue08,	PriorYearActualValue09,	PriorYearActualValue10,	PriorYearActualValue11,	PriorYearActualValue12
		)
	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID,
		SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, 
		SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06,
		SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08, SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, 
		SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12
	FROM fp.GeneralLedger gl
		JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
		INNER JOIN [fp].[GeneralLedgerHistory] hist ON gl.GeneralLedgerID = hist.GeneralLedgerID
	WHERE gl.BudgetConfigID = @BudgetConfigID 
		AND gl.APEModelSectionID in (@Revenue)
	GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID

	--Deduction
	INSERT INTO #DeductionData(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,
		PriorYearActualValue01,	PriorYearActualValue02,	PriorYearActualValue03,	PriorYearActualValue04,	PriorYearActualValue05,	PriorYearActualValue06,
		PriorYearActualValue07,	PriorYearActualValue08,	PriorYearActualValue09,	PriorYearActualValue10,	PriorYearActualValue11,	PriorYearActualValue12
		)
	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID,
		SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, 
		SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06,
		SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08, SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, 
		SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12
	FROM fp.GeneralLedger gl
		JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
		INNER JOIN [fp].[GeneralLedgerHistory] hist ON gl.GeneralLedgerID = hist.GeneralLedgerID
	WHERE gl.BudgetConfigID = @BudgetConfigID 
		AND gl.APEModelSectionID in (@Deduction)
		AND a.OBModelSectionName = 'Deductions - Reimbursement'
	GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID


	INSERT INTO #ReimbursementGL(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,

		PriorYearActualValue01,	PriorYearActualValue02,	PriorYearActualValue03,	PriorYearActualValue04,	PriorYearActualValue05,	PriorYearActualValue06,
		PriorYearActualValue07,	PriorYearActualValue08,	PriorYearActualValue09,	PriorYearActualValue10,	PriorYearActualValue11,	PriorYearActualValue12,

		PriorYearActualValueNetAsPercentOfCharge01, PriorYearActualValueNetAsPercentOfCharge02, PriorYearActualValueNetAsPercentOfCharge03, PriorYearActualValueNetAsPercentOfCharge04,
		PriorYearActualValueNetAsPercentOfCharge05, PriorYearActualValueNetAsPercentOfCharge06, PriorYearActualValueNetAsPercentOfCharge07, PriorYearActualValueNetAsPercentOfCharge08,
		PriorYearActualValueNetAsPercentOfCharge09, PriorYearActualValueNetAsPercentOfCharge10, PriorYearActualValueNetAsPercentOfCharge11, PriorYearActualValueNetAsPercentOfCharge12
		)
	SELECT DISTINCT r.BudgetConfigID, r.EntityGroupConfigID, r.EntityID, r.PayorGroupID, r.PatientClassID,
		r.PriorYearActualValue01, r.PriorYearActualValue02,	r.PriorYearActualValue03, r.PriorYearActualValue04,	r.PriorYearActualValue05, r.PriorYearActualValue06,
		r.PriorYearActualValue07, r.PriorYearActualValue08,	r.PriorYearActualValue09, r.PriorYearActualValue10,	r.PriorYearActualValue11, r.PriorYearActualValue12,
		--PriorYearActualValueNetAsPercentOfCharge
		-- %ofCharge = NetReimbursement/revenue = (revenue - deduction) / revenue
		CASE 
			WHEN r.PriorYearActualValue01 IS NULL OR r.PriorYearActualValue01 = 0 THEN 0 
			WHEN d.PriorYearActualValue01 IS NULL THEN 1
			ELSE (r.PriorYearActualValue01 - d.PriorYearActualValue01) / r.PriorYearActualValue01 
		END AS PriorYearActualValueNetAsPercentOfCharge01,
		CASE 
			WHEN r.PriorYearActualValue02 IS NULL OR r.PriorYearActualValue02 = 0 THEN 0 
			WHEN d.PriorYearActualValue02 IS NULL THEN 1
			ELSE (r.PriorYearActualValue02 - d.PriorYearActualValue02) / r.PriorYearActualValue02 
		END AS PriorYearActualValueNetAsPercentOfCharge02,
		CASE 
			WHEN r.PriorYearActualValue03 IS NULL OR r.PriorYearActualValue03 = 0 THEN 0 
			WHEN d.PriorYearActualValue03 IS NULL THEN 1
			ELSE (r.PriorYearActualValue03 - d.PriorYearActualValue03) / r.PriorYearActualValue03 
		END AS PriorYearActualValueNetAsPercentOfCharge03,
		CASE 
			WHEN r.PriorYearActualValue04 IS NULL OR r.PriorYearActualValue04 = 0 THEN 0 
			WHEN d.PriorYearActualValue04 IS NULL THEN 1
			ELSE (r.PriorYearActualValue04 - d.PriorYearActualValue04) / r.PriorYearActualValue04 
		END AS PriorYearActualValueNetAsPercentOfCharge04,
		CASE 
			WHEN r.PriorYearActualValue05 IS NULL OR r.PriorYearActualValue05 = 0 THEN 0 
			WHEN d.PriorYearActualValue05 IS NULL THEN 1
			ELSE (r.PriorYearActualValue05 - d.PriorYearActualValue05) / r.PriorYearActualValue05 
		END AS PriorYearActualValueNetAsPercentOfCharge05,
		CASE 
			WHEN r.PriorYearActualValue06 IS NULL OR r.PriorYearActualValue06 = 0 THEN 0 
			WHEN d.PriorYearActualValue06 IS NULL THEN 1
			ELSE (r.PriorYearActualValue06 - d.PriorYearActualValue06) / r.PriorYearActualValue06 
		END AS PriorYearActualValueNetAsPercentOfCharge06,
		CASE 
			WHEN r.PriorYearActualValue07 IS NULL OR r.PriorYearActualValue07 = 0 THEN 0 
			WHEN d.PriorYearActualValue07 IS NULL THEN 1
			ELSE (r.PriorYearActualValue07 - d.PriorYearActualValue07) / r.PriorYearActualValue07 
		END AS PriorYearActualValueNetAsPercentOfCharge07,
		CASE 
			WHEN r.PriorYearActualValue08 IS NULL OR r.PriorYearActualValue08 = 0 THEN 0 
			WHEN d.PriorYearActualValue08 IS NULL THEN 1
			ELSE (r.PriorYearActualValue08 - d.PriorYearActualValue08) / r.PriorYearActualValue08 
		END AS PriorYearActualValueNetAsPercentOfCharge08,
		CASE 
			WHEN r.PriorYearActualValue09 IS NULL OR r.PriorYearActualValue09 = 0 THEN 0 
			WHEN d.PriorYearActualValue09 IS NULL THEN 1
			ELSE (r.PriorYearActualValue09 - d.PriorYearActualValue09) / r.PriorYearActualValue09 
		END AS PriorYearActualValueNetAsPercentOfCharge09,
		CASE 
			WHEN r.PriorYearActualValue10 IS NULL OR r.PriorYearActualValue10 = 0 THEN 0 
			WHEN d.PriorYearActualValue10 IS NULL THEN 1
			ELSE (r.PriorYearActualValue10 - d.PriorYearActualValue10) / r.PriorYearActualValue10 
		END AS PriorYearActualValueNetAsPercentOfCharge10,
		CASE 
			WHEN r.PriorYearActualValue11 IS NULL OR r.PriorYearActualValue11 = 0 THEN 0 
			WHEN d.PriorYearActualValue11 IS NULL THEN 1
			ELSE (r.PriorYearActualValue11 - d.PriorYearActualValue11) / r.PriorYearActualValue11 
		END AS PriorYearActualValueNetAsPercentOfCharge11,
		CASE 
			WHEN r.PriorYearActualValue12 IS NULL OR r.PriorYearActualValue12 = 0 THEN 0 
			WHEN d.PriorYearActualValue12 IS NULL THEN 1
			ELSE (r.PriorYearActualValue12 - d.PriorYearActualValue12) / r.PriorYearActualValue12 
		END AS PriorYearActualValueNetAsPercentOfCharge12
		FROM #RevenueData r
		LEFT JOIN #DeductionData d ON  d.BudgetConfigID = r.BudgetConfigID AND d.EntityGroupConfigID = r.EntityGroupConfigID AND d.EntityID = r.EntityID 
			AND d.PayorGroupID = r.PayorGroupID  AND d.PatientClassID = r.PatientClassID
	WHERE r.BudgetConfigID = @BudgetConfigID 


	IF (@IsDebug = 1)
	BEGIN
		SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment
		SELECT '#ReimbursementGL', * FROM #ReimbursementGL
		SELECT '#DeductionData', * FROM #DeductionData
		SELECT '#RevenueData', * FROM #RevenueData
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID,
				[PriorYearActualValue01], [PriorYearActualValue02], [PriorYearActualValue03], [PriorYearActualValue04], [PriorYearActualValue05], [PriorYearActualValue06],
				[PriorYearActualValue07], [PriorYearActualValue08], [PriorYearActualValue09], [PriorYearActualValue10], [PriorYearActualValue11], [PriorYearActualValue12],
				
				[PriorYearActualValueNetAsPercentOfCharge01], [PriorYearActualValueNetAsPercentOfCharge02], [PriorYearActualValueNetAsPercentOfCharge03], [PriorYearActualValueNetAsPercentOfCharge04],
				[PriorYearActualValueNetAsPercentOfCharge05], [PriorYearActualValueNetAsPercentOfCharge06], [PriorYearActualValueNetAsPercentOfCharge07], [PriorYearActualValueNetAsPercentOfCharge08],
				[PriorYearActualValueNetAsPercentOfCharge09], [PriorYearActualValueNetAsPercentOfCharge10], [PriorYearActualValueNetAsPercentOfCharge11], [PriorYearActualValueNetAsPercentOfCharge12]

			FROM [fp].[ReimbursementGeneralLedger] rgl  
				INNER JOIN [fp].[ReimbursementGeneralLedgerHistory]	hist ON rgl.ReimbursementGeneralLedgerID = hist.ReimbursementGeneralLedgerID
			WHERE rgl.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #ReimbursementGL AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.PatientClassID = src.PatientClassID
		)  
		WHEN MATCHED AND (
							target.PriorYearActualValue01 <> src.PriorYearActualValue01 OR
							target.PriorYearActualValue02 <> src.PriorYearActualValue02 OR
							target.PriorYearActualValue03 <> src.PriorYearActualValue03 OR
							target.PriorYearActualValue04 <> src.PriorYearActualValue04 OR
							target.PriorYearActualValue05 <> src.PriorYearActualValue05 OR
							target.PriorYearActualValue06 <> src.PriorYearActualValue06 OR
							target.PriorYearActualValue07 <> src.PriorYearActualValue07 OR
							target.PriorYearActualValue08 <> src.PriorYearActualValue08 OR
							target.PriorYearActualValue09 <> src.PriorYearActualValue09 OR
							target.PriorYearActualValue10 <> src.PriorYearActualValue10 OR
							target.PriorYearActualValue11 <> src.PriorYearActualValue11 OR
							target.PriorYearActualValue12 <> src.PriorYearActualValue12 OR

							target.PriorYearActualValueNetAsPercentOfCharge01 <> src.PriorYearActualValueNetAsPercentOfCharge01 OR
							target.PriorYearActualValueNetAsPercentOfCharge02 <> src.PriorYearActualValueNetAsPercentOfCharge02 OR
							target.PriorYearActualValueNetAsPercentOfCharge03 <> src.PriorYearActualValueNetAsPercentOfCharge03 OR
							target.PriorYearActualValueNetAsPercentOfCharge04 <> src.PriorYearActualValueNetAsPercentOfCharge04 OR
							target.PriorYearActualValueNetAsPercentOfCharge05 <> src.PriorYearActualValueNetAsPercentOfCharge05 OR
							target.PriorYearActualValueNetAsPercentOfCharge06 <> src.PriorYearActualValueNetAsPercentOfCharge06 OR
							target.PriorYearActualValueNetAsPercentOfCharge07 <> src.PriorYearActualValueNetAsPercentOfCharge07 OR
							target.PriorYearActualValueNetAsPercentOfCharge08 <> src.PriorYearActualValueNetAsPercentOfCharge08 OR
							target.PriorYearActualValueNetAsPercentOfCharge09 <> src.PriorYearActualValueNetAsPercentOfCharge09 OR
							target.PriorYearActualValueNetAsPercentOfCharge10 <> src.PriorYearActualValueNetAsPercentOfCharge10 OR
							target.PriorYearActualValueNetAsPercentOfCharge11 <> src.PriorYearActualValueNetAsPercentOfCharge11 OR
							target.PriorYearActualValueNetAsPercentOfCharge12 <> src.PriorYearActualValueNetAsPercentOfCharge12
						 )
		THEN  
			UPDATE SET target.PriorYearActualValue01 = src.PriorYearActualValue01,
					   target.PriorYearActualValue02 = src.PriorYearActualValue02,
					   target.PriorYearActualValue03 = src.PriorYearActualValue03,
					   target.PriorYearActualValue04 = src.PriorYearActualValue04,
					   target.PriorYearActualValue05 = src.PriorYearActualValue05,
					   target.PriorYearActualValue06 = src.PriorYearActualValue06,
					   target.PriorYearActualValue07 = src.PriorYearActualValue07,
					   target.PriorYearActualValue08 = src.PriorYearActualValue08,
					   target.PriorYearActualValue09 = src.PriorYearActualValue09,
					   target.PriorYearActualValue10 = src.PriorYearActualValue10,
					   target.PriorYearActualValue11 = src.PriorYearActualValue11,
					   target.PriorYearActualValue12 = src.PriorYearActualValue12,

					   target.PriorYearActualValueNetAsPercentOfCharge01 = src.PriorYearActualValueNetAsPercentOfCharge01,
					   target.PriorYearActualValueNetAsPercentOfCharge02 = src.PriorYearActualValueNetAsPercentOfCharge02,
					   target.PriorYearActualValueNetAsPercentOfCharge03 = src.PriorYearActualValueNetAsPercentOfCharge03,
					   target.PriorYearActualValueNetAsPercentOfCharge04 = src.PriorYearActualValueNetAsPercentOfCharge04,
					   target.PriorYearActualValueNetAsPercentOfCharge05 = src.PriorYearActualValueNetAsPercentOfCharge05,
					   target.PriorYearActualValueNetAsPercentOfCharge06 = src.PriorYearActualValueNetAsPercentOfCharge06,
					   target.PriorYearActualValueNetAsPercentOfCharge07 = src.PriorYearActualValueNetAsPercentOfCharge07,
					   target.PriorYearActualValueNetAsPercentOfCharge08 = src.PriorYearActualValueNetAsPercentOfCharge08,
					   target.PriorYearActualValueNetAsPercentOfCharge09 = src.PriorYearActualValueNetAsPercentOfCharge09,
					   target.PriorYearActualValueNetAsPercentOfCharge10 = src.PriorYearActualValueNetAsPercentOfCharge10,
					   target.PriorYearActualValueNetAsPercentOfCharge11 = src.PriorYearActualValueNetAsPercentOfCharge11,
					   target.PriorYearActualValueNetAsPercentOfCharge12 = src.PriorYearActualValueNetAsPercentOfCharge12;
		
	END
END
GO


---------------------------------------------

-- fp.procSampleGeneralLedgerToReimbursement_Initial
CREATE PROCEDURE [fp].[procSampleGeneralLedgerToReimbursement_Initial] 
	@BudgetConfigID INT,	
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0 
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    05-23-2023   MZ        JAZZ-54503  Initial Creation
	** 2    07-04-2023   AO        JAZZ-57174  Adjusted formula NetAsPercentOfCharge
	** 3    10-04-2023   MZ        JAZZ-61634  Fix % of charge calculation when revenue stays the same but new deductions were found
	** 4	01-03-2024	 AO		   JAZZ-65384  Data transfer for GL is based on selected Model in Plan Config
	** 5	08-12-2024   VZ		   JAZZ-74434  Data transfer for GL based on excluded departments
	*************************************************************/

	-- Clean up old tables (and so SSMS is happy)
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#ReimbursementGL') IS NOT NULL DROP TABLE #ReimbursementGL;
	IF OBJECT_ID('tempdb..#glTargeting') IS NOT NULL DROP TABLE #glTargeting;
	IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData;
	IF OBJECT_ID('tempdb..#DeductionData') IS NOT NULL DROP TABLE #DeductionData;

	CREATE TABLE #FilterByDepartment (DepartmentID INT);
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
		
	CREATE TABLE #glTargeting (EntityID INT, GeneralLedgerID INT);

	CREATE TABLE #RevenueData (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],
		[InitialBudget01] [decimal](19, 8),
		[InitialBudget02] [decimal](19, 8),
		[InitialBudget03] [decimal](19, 8),
		[InitialBudget04] [decimal](19, 8),
		[InitialBudget05] [decimal](19, 8),
		[InitialBudget06] [decimal](19, 8),
		[InitialBudget07] [decimal](19, 8),
		[InitialBudget08] [decimal](19, 8),
		[InitialBudget09] [decimal](19, 8),
		[InitialBudget10] [decimal](19, 8),
		[InitialBudget11] [decimal](19, 8),
		[InitialBudget12] [decimal](19, 8),

		[InitialProjection01] [decimal](19, 8),
		[InitialProjection02] [decimal](19, 8),
		[InitialProjection03] [decimal](19, 8),
		[InitialProjection04] [decimal](19, 8),
		[InitialProjection05] [decimal](19, 8),
		[InitialProjection06] [decimal](19, 8),
		[InitialProjection07] [decimal](19, 8),
		[InitialProjection08] [decimal](19, 8),
		[InitialProjection09] [decimal](19, 8),
		[InitialProjection10] [decimal](19, 8),
		[InitialProjection11] [decimal](19, 8),
		[InitialProjection12] [decimal](19, 8)
	)

	CREATE TABLE #DeductionData (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],
		[InitialBudget01] [decimal](19, 8),
		[InitialBudget02] [decimal](19, 8),
		[InitialBudget03] [decimal](19, 8),
		[InitialBudget04] [decimal](19, 8),
		[InitialBudget05] [decimal](19, 8),
		[InitialBudget06] [decimal](19, 8),
		[InitialBudget07] [decimal](19, 8),
		[InitialBudget08] [decimal](19, 8),
		[InitialBudget09] [decimal](19, 8),
		[InitialBudget10] [decimal](19, 8),
		[InitialBudget11] [decimal](19, 8),
		[InitialBudget12] [decimal](19, 8),

		[InitialProjection01] [decimal](19, 8),
		[InitialProjection02] [decimal](19, 8),
		[InitialProjection03] [decimal](19, 8),
		[InitialProjection04] [decimal](19, 8),
		[InitialProjection05] [decimal](19, 8),
		[InitialProjection06] [decimal](19, 8),
		[InitialProjection07] [decimal](19, 8),
		[InitialProjection08] [decimal](19, 8),
		[InitialProjection09] [decimal](19, 8),
		[InitialProjection10] [decimal](19, 8),
		[InitialProjection11] [decimal](19, 8),
		[InitialProjection12] [decimal](19, 8)
	)

	CREATE TABLE #ReimbursementGL (
		[BudgetConfigID] [int],
		[EntityGroupConfigID] [int],
		[EntityID] [int],
		[PayorGroupID] [int],
		[PatientClassID] [int],
		[InitialBudget01] [decimal](19, 8),
		[InitialBudget02] [decimal](19, 8),
		[InitialBudget03] [decimal](19, 8),
		[InitialBudget04] [decimal](19, 8),
		[InitialBudget05] [decimal](19, 8),
		[InitialBudget06] [decimal](19, 8),
		[InitialBudget07] [decimal](19, 8),
		[InitialBudget08] [decimal](19, 8),
		[InitialBudget09] [decimal](19, 8),
		[InitialBudget10] [decimal](19, 8),
		[InitialBudget11] [decimal](19, 8),
		[InitialBudget12] [decimal](19, 8),

		[InitialProjection01] [decimal](19, 8),
		[InitialProjection02] [decimal](19, 8),
		[InitialProjection03] [decimal](19, 8),
		[InitialProjection04] [decimal](19, 8),
		[InitialProjection05] [decimal](19, 8),
		[InitialProjection06] [decimal](19, 8),
		[InitialProjection07] [decimal](19, 8),
		[InitialProjection08] [decimal](19, 8),
		[InitialProjection09] [decimal](19, 8),
		[InitialProjection10] [decimal](19, 8),
		[InitialProjection11] [decimal](19, 8),
		[InitialProjection12] [decimal](19, 8),

		[InitialBudgetNetAsPercentOfCharge01] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge02] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge03] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge04] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge05] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge06] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge07] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge08] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge09] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge10] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge11] [decimal](19, 8),
		[InitialBudgetNetAsPercentOfCharge12] [decimal](19, 8),

		[InitialProjectionNetAsPercentOfCharge01] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge02] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge03] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge04] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge05] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge06] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge07] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge08] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge09] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge10] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge11] [decimal](19, 8),
		[InitialProjectionNetAsPercentOfCharge12] [decimal](19, 8)
	)

	DECLARE @Revenue INT = 1;
	DECLARE @Deduction INT = 4;

	-- If the filter is empty, passing in all to avoid a bunch of duplicate statements		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED)
			INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID
			LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID
		WHERE gl.BudgetConfigID  = @BudgetConfigID 
			AND ((bc.DefaultReimbursementNetRevenueModelID = 2 
				AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) 
				OR rnrm.NetRevenueModelID = 2) -- GL Model
	END
	
	DELETE #FilterByDepartment
	WHERE DepartmentID IN (
		SELECT DepartmentID 
		FROM fp.GeneralLedgerReimbursementExcludedDepartments glred
			JOIN fp.BudgetConfig bc ON glred.BudgetConfigGuid = bc.BudgetConfigGuid
		WHERE bc.BudgetConfigID = @BudgetConfigID)
		
	--Revenue
	INSERT INTO #RevenueData(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,

		InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06,
		InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,

		InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06,
		InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12
		)
	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID,
		SUM(gl.InitialBudget01) AS InitialBudget01, SUM(gl.InitialBudget02) AS InitialBudget02, SUM(gl.InitialBudget03) AS InitialBudget03, SUM(gl.InitialBudget04) AS InitialBudget04, SUM(gl.InitialBudget05) AS InitialBudget05, SUM(gl.InitialBudget06) AS InitialBudget06, SUM(gl.InitialBudget07) AS InitialBudget07, SUM(gl.InitialBudget08) AS InitialBudget08, SUM(gl.InitialBudget09) AS InitialBudget09, SUM(gl.InitialBudget10) AS InitialBudget10, SUM(gl.InitialBudget11) AS InitialBudget11, SUM(gl.InitialBudget12) AS InitialBudget12,
		SUM(gl.InitialProjection01) AS InitialProjection01, SUM(gl.InitialProjection02) AS InitialProjection02, SUM(gl.InitialProjection03) AS InitialProjection03, SUM(gl.InitialProjection04) AS InitialProjection04, SUM(gl.InitialProjection05) AS InitialProjection05, SUM(gl.InitialProjection06) AS InitialProjection06, SUM(gl.InitialProjection07) AS InitialProjection07, SUM(gl.InitialProjection08) AS InitialProjection08, SUM(gl.InitialProjection09) AS InitialProjection09, SUM(gl.InitialProjection10) AS InitialProjection10, SUM(gl.InitialProjection11) AS InitialProjection11, SUM(gl.InitialProjection12) AS InitialProjection12
	FROM fp.GeneralLedger gl
		JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
	WHERE gl.BudgetConfigID = @BudgetConfigID 
		AND gl.APEModelSectionID in (@Revenue)
	GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID

	--Deduction
	INSERT INTO #DeductionData(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,

		InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06,
		InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,

		InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06,
		InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12
		)
	SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID,
		SUM(gl.InitialBudget01) AS InitialBudget01, SUM(gl.InitialBudget02) AS InitialBudget02, SUM(gl.InitialBudget03) AS InitialBudget03, SUM(gl.InitialBudget04) AS InitialBudget04, SUM(gl.InitialBudget05) AS InitialBudget05, SUM(gl.InitialBudget06) AS InitialBudget06, SUM(gl.InitialBudget07) AS InitialBudget07, SUM(gl.InitialBudget08) AS InitialBudget08, SUM(gl.InitialBudget09) AS InitialBudget09, SUM(gl.InitialBudget10) AS InitialBudget10, SUM(gl.InitialBudget11) AS InitialBudget11, SUM(gl.InitialBudget12) AS InitialBudget12,
		SUM(gl.InitialProjection01) AS InitialProjection01, SUM(gl.InitialProjection02) AS InitialProjection02, SUM(gl.InitialProjection03) AS InitialProjection03, SUM(gl.InitialProjection04) AS InitialProjection04, SUM(gl.InitialProjection05) AS InitialProjection05, SUM(gl.InitialProjection06) AS InitialProjection06, SUM(gl.InitialProjection07) AS InitialProjection07, SUM(gl.InitialProjection08) AS InitialProjection08, SUM(gl.InitialProjection09) AS InitialProjection09, SUM(gl.InitialProjection10) AS InitialProjection10, SUM(gl.InitialProjection11) AS InitialProjection11, SUM(gl.InitialProjection12) AS InitialProjection12
	FROM fp.GeneralLedger gl
		JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID
		INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID
	WHERE gl.BudgetConfigID = @BudgetConfigID 
		AND gl.APEModelSectionID in (@Deduction)
		AND a.OBModelSectionName = 'Deductions - Reimbursement'
	GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID



	INSERT INTO #ReimbursementGL(
		BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID,

		InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06,
		InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,

		InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06,
		InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,

		InitialBudgetNetAsPercentOfCharge01, InitialBudgetNetAsPercentOfCharge02, InitialBudgetNetAsPercentOfCharge03, InitialBudgetNetAsPercentOfCharge04,
		InitialBudgetNetAsPercentOfCharge05, InitialBudgetNetAsPercentOfCharge06, InitialBudgetNetAsPercentOfCharge07, InitialBudgetNetAsPercentOfCharge08,
		InitialBudgetNetAsPercentOfCharge09, InitialBudgetNetAsPercentOfCharge10, InitialBudgetNetAsPercentOfCharge11, InitialBudgetNetAsPercentOfCharge12,

		InitialProjectionNetAsPercentOfCharge01, InitialProjectionNetAsPercentOfCharge02, InitialProjectionNetAsPercentOfCharge03, InitialProjectionNetAsPercentOfCharge04,
		InitialProjectionNetAsPercentOfCharge05, InitialProjectionNetAsPercentOfCharge06, InitialProjectionNetAsPercentOfCharge07, InitialProjectionNetAsPercentOfCharge08,
		InitialProjectionNetAsPercentOfCharge09, InitialProjectionNetAsPercentOfCharge10, InitialProjectionNetAsPercentOfCharge11, InitialProjectionNetAsPercentOfCharge12
		)
	SELECT DISTINCT r.BudgetConfigID, r.EntityGroupConfigID, r.EntityID, r.PayorGroupID, r.PatientClassID,
		r.InitialBudget01, r.InitialBudget02, r.InitialBudget03, r.InitialBudget04, r.InitialBudget05, r.InitialBudget06, r.InitialBudget07, r.InitialBudget08, r.InitialBudget09, r.InitialBudget10, r.InitialBudget11, r.InitialBudget12,
		r.InitialProjection01, r.InitialProjection02, r.InitialProjection03, r.InitialProjection04, r.InitialProjection05, r.InitialProjection06, r.InitialProjection07, r.InitialProjection08, r.InitialProjection09, r.InitialProjection10, r.InitialProjection11, r.InitialProjection12,		

		--InitialBudgetNetAsPercentOfCharge
		-- %ofCharge = NetReimbursement/revenue = (revenue - deduction) / revenue
		CASE WHEN r.InitialBudget01 IS NULL OR r.InitialBudget01 = 0 THEN 0 WHEN d.InitialBudget01 IS NULL THEN 1
		ELSE (r.InitialBudget01 - d.InitialBudget01) / r.InitialBudget01 END AS InitialBudgetNetAsPercentOfCharge01,
		CASE WHEN r.InitialBudget02 IS NULL OR r.InitialBudget02 = 0 THEN 0 WHEN d.InitialBudget02 IS NULL THEN 1 
		ELSE (r.InitialBudget02 - d.InitialBudget02) / r.InitialBudget02 END AS InitialBudgetNetAsPercentOfCharge02,
		CASE WHEN r.InitialBudget03 IS NULL OR r.InitialBudget03 = 0 THEN 0 WHEN d.InitialBudget03 IS NULL THEN 1 
		ELSE (r.InitialBudget03 - d.InitialBudget03) / r.InitialBudget03 END AS InitialBudgetNetAsPercentOfCharge03,
		CASE WHEN r.InitialBudget04 IS NULL OR r.InitialBudget04 = 0 THEN 0 WHEN d.InitialBudget04 IS NULL THEN 1 
		ELSE (r.InitialBudget04 - d.InitialBudget04) / r.InitialBudget04 END AS InitialBudgetNetAsPercentOfCharge04,
		CASE WHEN r.InitialBudget05 IS NULL OR r.InitialBudget05 = 0 THEN 0 WHEN d.InitialBudget05 IS NULL THEN 1 
		ELSE (r.InitialBudget05 - d.InitialBudget05) / r.InitialBudget05 END AS InitialBudgetNetAsPercentOfCharge05,
		CASE WHEN r.InitialBudget06 IS NULL OR r.InitialBudget06 = 0 THEN 0 WHEN d.InitialBudget06 IS NULL THEN 1
		ELSE (r.InitialBudget06 - d.InitialBudget06) / r.InitialBudget06 END AS InitialBudgetNetAsPercentOfCharge06,
		CASE WHEN r.InitialBudget07 IS NULL OR r.InitialBudget07 = 0 THEN 0 WHEN d.InitialBudget07 IS NULL THEN 1 
		ELSE (r.InitialBudget07 - d.InitialBudget07) / r.InitialBudget07 END AS InitialBudgetNetAsPercentOfCharge07,
		CASE WHEN r.InitialBudget08 IS NULL OR r.InitialBudget08 = 0 THEN 0 WHEN d.InitialBudget08 IS NULL THEN 1
		ELSE (r.InitialBudget08 - d.InitialBudget08) / r.InitialBudget08 END AS InitialBudgetNetAsPercentOfCharge08,
		CASE WHEN r.InitialBudget09 IS NULL OR r.InitialBudget09 = 0 THEN 0 WHEN d.InitialBudget09 IS NULL THEN 1
		ELSE (r.InitialBudget09 - d.InitialBudget09) / r.InitialBudget09 END AS InitialBudgetNetAsPercentOfCharge09,
		CASE WHEN r.InitialBudget10 IS NULL OR r.InitialBudget10 = 0 THEN 0 WHEN d.InitialBudget10 IS NULL THEN 1 
		ELSE (r.InitialBudget10 - d.InitialBudget10) / r.InitialBudget10 END AS InitialBudgetNetAsPercentOfCharge10,
		CASE WHEN r.InitialBudget11 IS NULL OR r.InitialBudget11 = 0 THEN 0 WHEN d.InitialBudget11 IS NULL THEN 1 
		ELSE (r.InitialBudget11 - d.InitialBudget11) / r.InitialBudget11 END AS InitialBudgetNetAsPercentOfCharge11,
		CASE WHEN r.InitialBudget12 IS NULL OR r.InitialBudget12 = 0 THEN 0 WHEN d.InitialBudget12 IS NULL THEN 1 
		ELSE (r.InitialBudget12 - d.InitialBudget12) / r.InitialBudget12 END AS InitialBudgetNetAsPercentOfCharge12,
		--InitialProjectionNetAsPercentOfCharge
		CASE WHEN r.InitialProjection01 IS NULL OR r.InitialProjection01 = 0 THEN 0 WHEN d.InitialProjection01 IS NULL THEN 1 
		ELSE (r.InitialProjection01 - d.InitialProjection01) / r.InitialProjection01 END AS InitialProjectionNetAsPercentOfCharge01,
		CASE WHEN r.InitialProjection02 IS NULL OR r.InitialProjection02 = 0 THEN 0 WHEN d.InitialProjection02 IS NULL THEN 1 
		ELSE (r.InitialProjection02 - d.InitialProjection02) / r.InitialProjection02 END AS InitialProjectionNetAsPercentOfCharge02,
		CASE WHEN r.InitialProjection03 IS NULL OR r.InitialProjection03 = 0 THEN 0 WHEN d.InitialProjection03 IS NULL THEN 1 
		ELSE (r.InitialProjection03 - d.InitialProjection03) / r.InitialProjection03 END AS InitialProjectionNetAsPercentOfCharge03,
		CASE WHEN r.InitialProjection04 IS NULL OR r.InitialProjection04 = 0 THEN 0 WHEN d.InitialProjection04 IS NULL THEN 1 
		ELSE (r.InitialProjection04 - d.InitialProjection04) / r.InitialProjection04 END AS InitialProjectionNetAsPercentOfCharge04,
		CASE WHEN r.InitialProjection05 IS NULL OR r.InitialProjection05 = 0 THEN 0 WHEN d.InitialProjection05 IS NULL THEN 1
		ELSE (r.InitialProjection05 - d.InitialProjection05) / r.InitialProjection05 END AS InitialProjectionNetAsPercentOfCharge05,
		CASE WHEN r.InitialProjection06 IS NULL OR r.InitialProjection06 = 0 THEN 0 WHEN d.InitialProjection06 IS NULL THEN 1
		ELSE (r.InitialProjection06 - d.InitialProjection06) / r.InitialProjection06 END AS InitialProjectionNetAsPercentOfCharge06,
		CASE WHEN r.InitialProjection07 IS NULL OR r.InitialProjection07 = 0 THEN 0 WHEN d.InitialProjection07 IS NULL THEN 1 
		ELSE (r.InitialProjection07 - d.InitialProjection07) / r.InitialProjection07 END AS InitialProjectionNetAsPercentOfCharge07,
		CASE WHEN r.InitialProjection08 IS NULL OR r.InitialProjection08 = 0 THEN 0 WHEN d.InitialProjection08 IS NULL THEN 1 
		ELSE (r.InitialProjection08 - d.InitialProjection08) / r.InitialProjection08 END AS InitialProjectionNetAsPercentOfCharge08,
		CASE WHEN r.InitialProjection09 IS NULL OR r.InitialProjection09 = 0 THEN 0 WHEN d.InitialProjection09 IS NULL THEN 1
		ELSE (r.InitialProjection09 - d.InitialProjection09) / r.InitialProjection09 END AS InitialProjectionNetAsPercentOfCharge09,
		CASE WHEN r.InitialProjection10 IS NULL OR r.InitialProjection10 = 0 THEN 0 WHEN d.InitialProjection10 IS NULL THEN 1 
		ELSE (r.InitialProjection10 - d.InitialProjection10) / r.InitialProjection10 END AS InitialProjectionNetAsPercentOfCharge10,
		CASE WHEN r.InitialProjection11 IS NULL OR r.InitialProjection11 = 0 THEN 0 WHEN d.InitialProjection11 IS NULL THEN 1
		ELSE (r.InitialProjection11 - d.InitialProjection11) / r.InitialProjection11 END AS InitialProjectionNetAsPercentOfCharge11,
		CASE WHEN r.InitialProjection12 IS NULL OR r.InitialProjection12 = 0 THEN 0 WHEN d.InitialProjection12 IS NULL THEN 1
		ELSE (r.InitialProjection12 - d.InitialProjection12) / r.InitialProjection12 END AS InitialProjectionNetAsPercentOfCharge12
	FROM #RevenueData r
		LEFT JOIN #DeductionData d ON  d.BudgetConfigID = r.BudgetConfigID AND d.EntityGroupConfigID = r.EntityGroupConfigID AND d.EntityID = r.EntityID 
			AND d.PayorGroupID = r.PayorGroupID  AND d.PatientClassID = r.PatientClassID
	WHERE r.BudgetConfigID = @BudgetConfigID 


	IF (@IsDebug = 1)
	BEGIN
		SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment
		SELECT '#ReimbursementGL', * FROM #ReimbursementGL
		SELECT '#DeductionData', * FROM #DeductionData
		SELECT '#RevenueData', * FROM #RevenueData
	END ELSE
	BEGIN
		-- Publish
		;WITH TGT AS   
		(  
			SELECT rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID,
				[InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06],
				[InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12],

				[InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06],
				[InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12],

				[InitialBudgetNetAsPercentOfCharge01], [InitialBudgetNetAsPercentOfCharge02], [InitialBudgetNetAsPercentOfCharge03], [InitialBudgetNetAsPercentOfCharge04],
				[InitialBudgetNetAsPercentOfCharge05], [InitialBudgetNetAsPercentOfCharge06], [InitialBudgetNetAsPercentOfCharge07], [InitialBudgetNetAsPercentOfCharge08],
				[InitialBudgetNetAsPercentOfCharge09], [InitialBudgetNetAsPercentOfCharge10], [InitialBudgetNetAsPercentOfCharge11], [InitialBudgetNetAsPercentOfCharge12],
				
				[InitialProjectionNetAsPercentOfCharge01], [InitialProjectionNetAsPercentOfCharge02], [InitialProjectionNetAsPercentOfCharge03], [InitialProjectionNetAsPercentOfCharge04],
				[InitialProjectionNetAsPercentOfCharge05], [InitialProjectionNetAsPercentOfCharge06], [InitialProjectionNetAsPercentOfCharge07], [InitialProjectionNetAsPercentOfCharge08],
				[InitialProjectionNetAsPercentOfCharge09], [InitialProjectionNetAsPercentOfCharge10], [InitialProjectionNetAsPercentOfCharge11], [InitialProjectionNetAsPercentOfCharge12]				
			FROM [fp].[ReimbursementGeneralLedger] rgl  
			WHERE rgl.BudgetConfigID = @BudgetConfigID
		)  

		MERGE TGT AS target  
		USING #ReimbursementGL AS src  
		ON (  
				target.BudgetConfigID = src.BudgetConfigID  
			AND target.EntityGroupConfigID = src.EntityGroupConfigID  
			AND target.EntityID = src.EntityID  
			AND target.PayorGroupID = src.PayorGroupID 
			AND target.PatientClassID = src.PatientClassID
		)  
		WHEN MATCHED AND (
							target.InitialBudget01 <> src.InitialBudget01 OR
							target.InitialBudget02 <> src.InitialBudget02 OR
							target.InitialBudget03 <> src.InitialBudget03 OR
							target.InitialBudget04 <> src.InitialBudget04 OR
							target.InitialBudget05 <> src.InitialBudget05 OR
							target.InitialBudget06 <> src.InitialBudget06 OR
							target.InitialBudget07 <> src.InitialBudget07 OR
							target.InitialBudget08 <> src.InitialBudget08 OR
							target.InitialBudget09 <> src.InitialBudget09 OR
							target.InitialBudget10 <> src.InitialBudget10 OR
							target.InitialBudget11 <> src.InitialBudget11 OR
							target.InitialBudget12 <> src.InitialBudget12 OR

							target.InitialProjection01 <> src.InitialProjection01 OR
							target.InitialProjection02 <> src.InitialProjection02 OR
							target.InitialProjection03 <> src.InitialProjection03 OR
							target.InitialProjection04 <> src.InitialProjection04 OR
							target.InitialProjection05 <> src.InitialProjection05 OR
							target.InitialProjection06 <> src.InitialProjection06 OR
							target.InitialProjection07 <> src.InitialProjection07 OR
							target.InitialProjection08 <> src.InitialProjection08 OR
							target.InitialProjection09 <> src.InitialProjection09 OR
							target.InitialProjection10 <> src.InitialProjection10 OR
							target.InitialProjection11 <> src.InitialProjection11 OR
							target.InitialProjection12 <> src.InitialProjection12 OR

							target.InitialBudgetNetAsPercentOfCharge01 <> src.InitialBudgetNetAsPercentOfCharge01 OR
							target.InitialBudgetNetAsPercentOfCharge02 <> src.InitialBudgetNetAsPercentOfCharge02 OR
							target.InitialBudgetNetAsPercentOfCharge03 <> src.InitialBudgetNetAsPercentOfCharge03 OR
							target.InitialBudgetNetAsPercentOfCharge04 <> src.InitialBudgetNetAsPercentOfCharge04 OR
							target.InitialBudgetNetAsPercentOfCharge05 <> src.InitialBudgetNetAsPercentOfCharge05 OR
							target.InitialBudgetNetAsPercentOfCharge06 <> src.InitialBudgetNetAsPercentOfCharge06 OR
							target.InitialBudgetNetAsPercentOfCharge07 <> src.InitialBudgetNetAsPercentOfCharge07 OR
							target.InitialBudgetNetAsPercentOfCharge08 <> src.InitialBudgetNetAsPercentOfCharge08 OR
							target.InitialBudgetNetAsPercentOfCharge09 <> src.InitialBudgetNetAsPercentOfCharge09 OR
							target.InitialBudgetNetAsPercentOfCharge10 <> src.InitialBudgetNetAsPercentOfCharge10 OR
							target.InitialBudgetNetAsPercentOfCharge11 <> src.InitialBudgetNetAsPercentOfCharge11 OR
							target.InitialBudgetNetAsPercentOfCharge12 <> src.InitialBudgetNetAsPercentOfCharge12 OR

							target.InitialProjectionNetAsPercentOfCharge01 <> src.InitialProjectionNetAsPercentOfCharge01 OR
							target.InitialProjectionNetAsPercentOfCharge02 <> src.InitialProjectionNetAsPercentOfCharge02 OR
							target.InitialProjectionNetAsPercentOfCharge03 <> src.InitialProjectionNetAsPercentOfCharge03 OR
							target.InitialProjectionNetAsPercentOfCharge04 <> src.InitialProjectionNetAsPercentOfCharge04 OR
							target.InitialProjectionNetAsPercentOfCharge05 <> src.InitialProjectionNetAsPercentOfCharge05 OR
							target.InitialProjectionNetAsPercentOfCharge06 <> src.InitialProjectionNetAsPercentOfCharge06 OR
							target.InitialProjectionNetAsPercentOfCharge07 <> src.InitialProjectionNetAsPercentOfCharge07 OR
							target.InitialProjectionNetAsPercentOfCharge08 <> src.InitialProjectionNetAsPercentOfCharge08 OR
							target.InitialProjectionNetAsPercentOfCharge09 <> src.InitialProjectionNetAsPercentOfCharge09 OR
							target.InitialProjectionNetAsPercentOfCharge10 <> src.InitialProjectionNetAsPercentOfCharge10 OR
							target.InitialProjectionNetAsPercentOfCharge11 <> src.InitialProjectionNetAsPercentOfCharge11 OR
							target.InitialProjectionNetAsPercentOfCharge12 <> src.InitialProjectionNetAsPercentOfCharge12
						 )
		THEN  
			UPDATE SET target.InitialBudget01 = src.InitialBudget01,
					   target.InitialBudget02 = src.InitialBudget02,
					   target.InitialBudget03 = src.InitialBudget03,
					   target.InitialBudget04 = src.InitialBudget04,
					   target.InitialBudget05 = src.InitialBudget05,
					   target.InitialBudget06 = src.InitialBudget06,
					   target.InitialBudget07 = src.InitialBudget07,
					   target.InitialBudget08 = src.InitialBudget08,
					   target.InitialBudget09 = src.InitialBudget09,
					   target.InitialBudget10 = src.InitialBudget10,
					   target.InitialBudget11 = src.InitialBudget11,
					   target.InitialBudget12 = src.InitialBudget12,

					   target.InitialProjection01 = src.InitialProjection01,
					   target.InitialProjection02 = src.InitialProjection02,
					   target.InitialProjection03 = src.InitialProjection03,
					   target.InitialProjection04 = src.InitialProjection04,
					   target.InitialProjection05 = src.InitialProjection05,
					   target.InitialProjection06 = src.InitialProjection06,
					   target.InitialProjection07 = src.InitialProjection07,
					   target.InitialProjection08 = src.InitialProjection08,
					   target.InitialProjection09 = src.InitialProjection09,
					   target.InitialProjection10 = src.InitialProjection10,
					   target.InitialProjection11 = src.InitialProjection11,
					   target.InitialProjection12 = src.InitialProjection12,

					   target.InitialBudgetNetAsPercentOfCharge01 = src.InitialBudgetNetAsPercentOfCharge01,
					   target.InitialBudgetNetAsPercentOfCharge02 = src.InitialBudgetNetAsPercentOfCharge02,
					   target.InitialBudgetNetAsPercentOfCharge03 = src.InitialBudgetNetAsPercentOfCharge03,
					   target.InitialBudgetNetAsPercentOfCharge04 = src.InitialBudgetNetAsPercentOfCharge04,
					   target.InitialBudgetNetAsPercentOfCharge05 = src.InitialBudgetNetAsPercentOfCharge05,
					   target.InitialBudgetNetAsPercentOfCharge06 = src.InitialBudgetNetAsPercentOfCharge06,
					   target.InitialBudgetNetAsPercentOfCharge07 = src.InitialBudgetNetAsPercentOfCharge07,
					   target.InitialBudgetNetAsPercentOfCharge08 = src.InitialBudgetNetAsPercentOfCharge08,
					   target.InitialBudgetNetAsPercentOfCharge09 = src.InitialBudgetNetAsPercentOfCharge09,
					   target.InitialBudgetNetAsPercentOfCharge10 = src.InitialBudgetNetAsPercentOfCharge10,
					   target.InitialBudgetNetAsPercentOfCharge11 = src.InitialBudgetNetAsPercentOfCharge11,
					   target.InitialBudgetNetAsPercentOfCharge12 = src.InitialBudgetNetAsPercentOfCharge12,

					   target.InitialProjectionNetAsPercentOfCharge01 = src.InitialProjectionNetAsPercentOfCharge01,
					   target.InitialProjectionNetAsPercentOfCharge02 = src.InitialProjectionNetAsPercentOfCharge02,
					   target.InitialProjectionNetAsPercentOfCharge03 = src.InitialProjectionNetAsPercentOfCharge03,
					   target.InitialProjectionNetAsPercentOfCharge04 = src.InitialProjectionNetAsPercentOfCharge04,
					   target.InitialProjectionNetAsPercentOfCharge05 = src.InitialProjectionNetAsPercentOfCharge05,
					   target.InitialProjectionNetAsPercentOfCharge06 = src.InitialProjectionNetAsPercentOfCharge06,
					   target.InitialProjectionNetAsPercentOfCharge07 = src.InitialProjectionNetAsPercentOfCharge07,
					   target.InitialProjectionNetAsPercentOfCharge08 = src.InitialProjectionNetAsPercentOfCharge08,
					   target.InitialProjectionNetAsPercentOfCharge09 = src.InitialProjectionNetAsPercentOfCharge09,
					   target.InitialProjectionNetAsPercentOfCharge10 = src.InitialProjectionNetAsPercentOfCharge10,
					   target.InitialProjectionNetAsPercentOfCharge11 = src.InitialProjectionNetAsPercentOfCharge11,
					   target.InitialProjectionNetAsPercentOfCharge12 = src.InitialProjectionNetAsPercentOfCharge12;

	END
END
GO


---------------------------------------------

-- fp.procSamplePercentOfChargeData
CREATE     PROCEDURE [fp].[procSamplePercentOfChargeData]
  @EntityGroupConfigID INT,
  @MonthsLoaded INT,
  @IsAnnualized BIT,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
  @IsDebug BIT = 0
AS
BEGIN
    /**************************************************************
    ** Change History
    **************************************************************
    ** CID  Date        Author  WI              Description
    ** 1     2019-03-26  IP      B-22466        Switch usages of funcGetSourceDimensionalityAsTable to a temp table
    ** 2     2021-03-25  NN      Jazz-14123     Remove null joins
    ** 7     2022-09-07  NT      JAZZ-40956     Include all gross charges accounts and not just variable revenue accounts when calculating percent of charges
    ** 8     12-01-2022  MY      JAZZ-46294     Deductions not calculating when department is set to flex off Total Gross Charges
    ** 9     03-17-2022  MY      JAZZ-51319     Deductions % Not Calculating Appropriately
    ** 10    05-09-2023  NT      JAZZ-54290     Data restructure changes to use new fp.GeneralLedger table
    ** 11    09-13-2023  MY      JAZZ-60768     Add EGC Filter to Update clause
	** 12	 01-18-2024  NT		 JAZZ-64955		Add ROUND() function to mitigate really large numbers during final division calculation to prevent arithmetic overflow
	** 13	 08-28-2024  MD		 JAZZ-75083		Pull precision from fp.SystemSetting for ROUND() functions
    *************************************************************/
    
    IF OBJECT_ID('tempdb..#dollars') IS NOT NULL  DROP TABLE #dollars
    IF OBJECT_ID('tempdb..#deductions') IS NOT NULL  DROP TABLE #deductions
    IF OBJECT_ID('tempdb..#grossCharges') IS NOT NULL  DROP TABLE #grossCharges
    IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL  DROP TABLE #FilterByDepartment
    IF OBJECT_ID('tempdb..#calculatedPercentOfCharge') IS NOT NULL  DROP TABLE #calculatedPercentOfCharge
    IF OBJECT_ID('tempdb..#totals') IS NOT NULL  DROP TABLE #totals
    IF OBJECT_ID('tempdb..#variability') IS NOT NULL  DROP TABLE #variability

	--JAZZ-75083
	--Allows for setting of custom precision as defined by the customer
	--DO NOT UPDATE THIS SETTING WITHOUT EXPRESS PERMISSION FROM THE CUSTOMER
	--We need to make sure the client is okay with the loss in precision before updating this setting
	DECLARE @Precision INT = 8
	SELECT @Precision = CAST(Value AS INT) from fp.SystemSetting
	where Name = 'Set custom precision for select stored procedures'

    CREATE TABLE #FilterByDepartment (DepartmentID int)
    INSERT INTO #FilterByDepartment (DepartmentID)
    SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
    -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements      
    IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
    BEGIN
        INSERT INTO #FilterByDepartment (DepartmentID)
        SELECT DISTINCT DepartmentID
        FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED)
        WHERE d.EntityGroupConfigID = @EntityGroupConfigID
    END
    DECLARE @BudgetConfigID INT
    SELECT @BudgetConfigID = BudgetConfigID 
    FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID 
    WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
    DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0)
    -- Important note: Revenue and Deductions both are either 100% variable or 100% fixed, they do not contain mixed variability like other sections
    -- so we only care about variable deductions. Revenue we want to pull regardless of variability assuming the 'Include All Gross Charges Accounts' is enabled
    -- Calculate the totals at the department/account/variability level. In the event baseline is set to annualized, only pull in months loaded
    -- if the baseline is not annualized, we pull in everything.
    -- For projection, we will only look at months loaded (aka actuals) regardless of baseline setting
    SELECT
        fgl.DepartmentID,
        fgl.AccountID,
        fgl.VariabilityID,
        (
        SUM(CASE WHEN  1 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END +
                CASE WHEN  2 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END +
                CASE WHEN  3 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END +
                CASE WHEN  4 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END +
                CASE WHEN  5 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END +
                CASE WHEN  6 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END +
                CASE WHEN  7 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END +
                CASE WHEN  8 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END +
                CASE WHEN  9 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END +
                CASE WHEN 10 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END +
                CASE WHEN 11 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END +
                CASE WHEN 12 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal,
        (SUM(CASE WHEN  1 <= @MonthsLoaded THEN SampledProjection01 ELSE 0 END +
                CASE WHEN  2 <= @MonthsLoaded THEN SampledProjection02 ELSE 0 END +
                CASE WHEN  3 <= @MonthsLoaded THEN SampledProjection03 ELSE 0 END +
                CASE WHEN  4 <= @MonthsLoaded THEN SampledProjection04 ELSE 0 END +
                CASE WHEN  5 <= @MonthsLoaded THEN SampledProjection05 ELSE 0 END +
                CASE WHEN  6 <= @MonthsLoaded THEN SampledProjection06 ELSE 0 END +
                CASE WHEN  7 <= @MonthsLoaded THEN SampledProjection07 ELSE 0 END +
                CASE WHEN  8 <= @MonthsLoaded THEN SampledProjection08 ELSE 0 END +
                CASE WHEN  9 <= @MonthsLoaded THEN SampledProjection09 ELSE 0 END +
                CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE 0 END +
                CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE 0 END +
                CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE 0 END )) AS SampledProjectionTotal
    INTO #totals
    FROM [fp].[GeneralLedger] fgl
        INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
    GROUP BY
        fgl.DepartmentID,
        fgl.AccountID,
        fgl.VariabilityID
    -- Pull the variability from the variability tables, this is used in the legacy way of calculating Percent of Charge where we only look at the variable portion of the dollars
    -- In the new way, we do not use this table as we want all of the dollars for Revenue whether it's fixed or variable.
    SELECT fav.DepartmentID, 
        fav.AccountID, 
        MAX(FixedPercentage) AS FixedPercentage
    INTO #variability
    FROM [fp].[FactAccountVariability] fav
            INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fav.DepartmentID
            INNER JOIN [fp].[EntityGroupConfig] egc ON
        egc.EntityGroupConfigID = @EntityGroupConfigID
        AND egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID
    GROUP BY fav.DepartmentID, fav.AccountID
    -- We need to recalculate the dollars on the fly because InitialBudget/Projection Dollars will get flexed, otherwise if we don't 
    -- the rate will rise each time.
    SELECT
        fgl.DepartmentID,
        fgl.AccountID,
        fgl.EntityGroupConfigID,
        fgl.APEModelSectionID,
        fgl.VariabilityID, --will apply variability filter later when splitting into deductions and gross charges
        CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledBudgetTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal END AS BudgetDollarTotal,
        CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledProjectionTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionTotal END AS ProjectionDollarTotal
    INTO #dollars
    FROM [fp].[GeneralLedger] fgl
        INNER JOIN #totals AS total ON total.DepartmentID = fgl.DepartmentID
            AND total.AccountID = fgl.AccountID
            AND total.VariabilityID = fgl.VariabilityID
        LEFT JOIN #variability fv ON fv.DepartmentID = fgl.DepartmentID
            AND fv.AccountID = fgl.AccountID
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
 
    -- Find the deductions baseline for variable budget data by department & account
    SELECT fgl.DepartmentID, fgl.AccountID, SUM(fgl.BudgetDollarTotal) AS TotalDeductionsBudget, SUM(fgl.ProjectionDollarTotal) AS TotalDeductionsProjection
    INTO #deductions
    FROM #dollars fgl
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
        AND fgl.APEModelSectionID = 4  -- Deductions
        AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2)
    GROUP BY fgl.DepartmentID, fgl.AccountID
   
   -- Find the gross charges baseline for budget data by department. 
    -- Please note that all accounts (variable & fixed) are included if FF (@IncludeAllGrossChargesFlag) is ON
    SELECT fgl.DepartmentID, ROUND((SUM(BudgetDollarTotal)),@Precision,0) AS TotalGrossChargesBudget, ROUND((SUM(ProjectionDollarTotal)),@Precision,0) AS TotalGrossChargesProjection
    INTO #grossCharges
    FROM #dollars fgl
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
        AND fgl.APEModelSectionID = 1  -- Revenue
        AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2)
    GROUP BY fgl.DepartmentID
    
    SELECT GeneralLedgerID,
        CASE WHEN c.TotalGrossChargesBudget = 0 THEN 0 ELSE d.TotalDeductionsBudget / c.TotalGrossChargesBudget END AS CalculatedBudget,
        CASE WHEN c.TotalGrossChargesProjection = 0 THEN 0 ELSE d.TotalDeductionsProjection / c.TotalGrossChargesProjection END as CalculatedProjection
    INTO #calculatedPercentOfCharge
    FROM [fp].[GeneralLedger] fgl
    INNER JOIN #deductions d ON d.DepartmentID = fgl.DepartmentID AND d.AccountID = fgl.AccountID
    INNER JOIN #grossCharges c ON d.DepartmentID = c.DepartmentID
    WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
    IF @IsDebug = 1
    BEGIN
        SELECT 'Include All Gross Charges Accounts', @IncludeAllGrossChargesFlag
        SELECT '#totals', DepartmentID, AccountID, VariabilityID, SampledBudgetTotal, SampledProjectionTotal FROM #totals
        SELECT '#variability', DepartmentID, AccountID, FixedPercentage FROM #variability
        SELECT '#dollars', DepartmentID, AccountID, EntityGroupConfigID, APEModelSectionID, VariabilityID, BudgetDollarTotal, ProjectionDollarTotal FROM #dollars
        SELECT '#deductions', DepartmentID, AccountID, TotalDeductionsBudget, TotalDeductionsProjection FROM #deductions
        SELECT '#grossCharges', DepartmentID, TotalGrossChargesBudget, TotalGrossChargesProjection FROM #grossCharges
        SELECT '#calculatedPercentOfCharge', GeneralLedgerID, CalculatedBudget, CalculatedProjection, 'TotalDeductions / TotalGrossCharges' AS Calculation FROM #calculatedPercentOfCharge
    END ELSE
    BEGIN
        -- Use already imported values for percentage of charge 
        UPDATE fgl
        SET
            InitialBudgetPercentOfCharge01 = i.Value01,
            InitialBudgetPercentOfCharge02 = i.Value02,
            InitialBudgetPercentOfCharge03 = i.Value03,
            InitialBudgetPercentOfCharge04 = i.Value04,
            InitialBudgetPercentOfCharge05 = i.Value05,
            InitialBudgetPercentOfCharge06 = i.Value06,
            InitialBudgetPercentOfCharge07 = i.Value07,
            InitialBudgetPercentOfCharge08 = i.Value08,
            InitialBudgetPercentOfCharge09 = i.Value09,
            InitialBudgetPercentOfCharge10 = i.Value10,
            InitialBudgetPercentOfCharge11 = i.Value11,
            InitialBudgetPercentOfCharge12 = i.Value12
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 2
        WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
    
        UPDATE fgl
        SET
            InitialProjectionPercentOfCharge01 = IIF(1  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value01),
            InitialProjectionPercentOfCharge02 = IIF(2  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value02),
            InitialProjectionPercentOfCharge03 = IIF(3  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value03),
            InitialProjectionPercentOfCharge04 = IIF(4  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value04),
            InitialProjectionPercentOfCharge05 = IIF(5  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value05),
            InitialProjectionPercentOfCharge06 = IIF(6  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value06),
            InitialProjectionPercentOfCharge07 = IIF(7  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value07),
            InitialProjectionPercentOfCharge08 = IIF(8  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value08),
            InitialProjectionPercentOfCharge09 = IIF(9  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value09),
            InitialProjectionPercentOfCharge10 = IIF(10 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value10),
            InitialProjectionPercentOfCharge11 = IIF(11 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value11),
            InitialProjectionPercentOfCharge12 = IIF(12 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value12)
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID 
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 12
            LEFT JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID
        WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID
        -- Percent of charge is calculated by taking the Sum(Deduction Baseline) / Sum(Gross Charge Baseline)
        UPDATE fgl
        SET
            InitialBudgetPercentOfCharge01 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge02 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge03 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge04 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge05 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge06 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge07 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge08 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge09 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge10 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge11 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge12 = c.CalculatedBudget
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID
            LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID 
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 2
        WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID 
            AND i.BudgetConfigID IS NULL
    
        UPDATE fgl
        SET 
            InitialProjectionPercentOfCharge01 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge02 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge03 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge04 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge05 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge06 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge07 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge08 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge09 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge10 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge11 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge12 = c.CalculatedProjection
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID
            LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID 
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 12
        WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID 
            AND i.BudgetConfigID IS NULL
    
    END
END
GO


---------------------------------------------

-- fp.procSamplePercentOfChargeData_InitialPlan
CREATE   PROCEDURE [fp].[procSamplePercentOfChargeData_InitialPlan]
  @BudgetConfigGUID UNIQUEIDENTIFIER,
  @BudgetConfigID SMALLINT,
  @EntityGroupConfigIDs VARCHAR(MAX),
  @MonthsLoaded INT,
  @IsAnnualized BIT,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
  @IsDebug BIT = 0
AS
BEGIN
    /**************************************************************
    ** Change History
    **************************************************************
    ** CID  	Date        	Author 		WI              	Description
    **  1	2024-05-27	MV		JAZZ-71177		Create SP for Initial plan method baseed on [fp].[procSamplePercentOfChargeData]
    **  2	08-28-2024 	MD 		JAZZ-75083 		Pull precision from fp.SystemSetting for ROUND() functions
    *************************************************************/
    
    IF OBJECT_ID('tempdb..#dollars') IS NOT NULL  DROP TABLE #dollars
    IF OBJECT_ID('tempdb..#deductions') IS NOT NULL  DROP TABLE #deductions
    IF OBJECT_ID('tempdb..#grossCharges') IS NOT NULL  DROP TABLE #grossCharges
    IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL  DROP TABLE #FilterByDepartment
    IF OBJECT_ID('tempdb..#calculatedPercentOfCharge') IS NOT NULL  DROP TABLE #calculatedPercentOfCharge
    IF OBJECT_ID('tempdb..#totals') IS NOT NULL  DROP TABLE #totals
    IF OBJECT_ID('tempdb..#variability') IS NOT NULL  DROP TABLE #variability
	IF OBJECT_ID('tempdb..#FilterByEntityGroupConfig') IS NOT NULL  DROP TABLE #FilterByEntityGroupConfig

	--JAZZ-75083
	--Allows for setting of custom precision as defined by the customer
	--DO NOT UPDATE THIS SETTING WITHOUT EXPRESS PERMISSION FROM THE CUSTOMER
	--We need to make sure the client is okay with the loss in precision before updating this setting
	DECLARE @Precision INT = 8
	SELECT @Precision = CAST(Value AS INT) from fp.SystemSetting
	where Name = 'Set custom precision for select stored procedures'

	CREATE TABLE #FilterByEntityGroupConfig (EntityGroupConfigID int)

	IF @EntityGroupConfigIDs IS NOT NULL AND @EntityGroupConfigIDs <> ''
	BEGIN
		INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID)
		SELECT TRIM([value]) AS EntityGroupConfigID FROM STRING_SPLIT(@EntityGroupConfigIDs, ',' )
	END
	ELSE BEGIN
		INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID)
		SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig]
		WHERE BudgetConfigGUID = @BudgetConfigGUID
	END



    CREATE TABLE #FilterByDepartment (DepartmentID int)
    INSERT INTO #FilterByDepartment (DepartmentID)
    SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
    -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements      
    IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
    BEGIN
        INSERT INTO #FilterByDepartment (DepartmentID)
        SELECT DISTINCT DepartmentID
        FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED)
		INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = d.EntityGroupConfigID
        WHERE d.BudgetConfigID = @BudgetConfigID
    END
    
	DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0)
    -- Important note: Revenue and Deductions both are either 100% variable or 100% fixed, they do not contain mixed variability like other sections
    -- so we only care about variable deductions. Revenue we want to pull regardless of variability assuming the 'Include All Gross Charges Accounts' is enabled
    -- Calculate the totals at the department/account/variability level. In the event baseline is set to annualized, only pull in months loaded
    -- if the baseline is not annualized, we pull in everything.
    -- For projection, we will only look at months loaded (aka actuals) regardless of baseline setting
    SELECT
        fgl.DepartmentID,
        fgl.AccountID,
        fgl.VariabilityID,
        (
        SUM(CASE WHEN  1 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END +
                CASE WHEN  2 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END +
                CASE WHEN  3 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END +
                CASE WHEN  4 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END +
                CASE WHEN  5 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END +
                CASE WHEN  6 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END +
                CASE WHEN  7 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END +
                CASE WHEN  8 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END +
                CASE WHEN  9 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END +
                CASE WHEN 10 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END +
                CASE WHEN 11 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END +
                CASE WHEN 12 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal,
        (SUM(CASE WHEN  1 <= @MonthsLoaded THEN SampledProjection01 ELSE 0 END +
                CASE WHEN  2 <= @MonthsLoaded THEN SampledProjection02 ELSE 0 END +
                CASE WHEN  3 <= @MonthsLoaded THEN SampledProjection03 ELSE 0 END +
                CASE WHEN  4 <= @MonthsLoaded THEN SampledProjection04 ELSE 0 END +
                CASE WHEN  5 <= @MonthsLoaded THEN SampledProjection05 ELSE 0 END +
                CASE WHEN  6 <= @MonthsLoaded THEN SampledProjection06 ELSE 0 END +
                CASE WHEN  7 <= @MonthsLoaded THEN SampledProjection07 ELSE 0 END +
                CASE WHEN  8 <= @MonthsLoaded THEN SampledProjection08 ELSE 0 END +
                CASE WHEN  9 <= @MonthsLoaded THEN SampledProjection09 ELSE 0 END +
                CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE 0 END +
                CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE 0 END +
                CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE 0 END )) AS SampledProjectionTotal
    INTO #totals
    FROM [fp].[GeneralLedger] fgl
        INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID
		INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
    GROUP BY
        fgl.DepartmentID,
        fgl.AccountID,
        fgl.VariabilityID
    -- Pull the variability from the variability tables, this is used in the legacy way of calculating Percent of Charge where we only look at the variable portion of the dollars
    -- In the new way, we do not use this table as we want all of the dollars for Revenue whether it's fixed or variable.
    SELECT fav.DepartmentID, 
        fav.AccountID, 
        MAX(FixedPercentage) AS FixedPercentage
    INTO #variability
    FROM [fp].[FactAccountVariability] fav
            INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fav.DepartmentID
            INNER JOIN [fp].[EntityGroupConfig] egc ON
				egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID
			INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = egc.EntityGroupConfigID
    GROUP BY fav.DepartmentID, fav.AccountID
    -- We need to recalculate the dollars on the fly because InitialBudget/Projection Dollars will get flexed, otherwise if we don't 
    -- the rate will rise each time.
    SELECT
        fgl.DepartmentID,
        fgl.AccountID,
        fgl.EntityGroupConfigID,
        fgl.APEModelSectionID,
        fgl.VariabilityID, --will apply variability filter later when splitting into deductions and gross charges
        CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledBudgetTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal END AS BudgetDollarTotal,
        CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledProjectionTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionTotal END AS ProjectionDollarTotal
    INTO #dollars
    FROM [fp].[GeneralLedger] fgl
        INNER JOIN #totals AS total ON total.DepartmentID = fgl.DepartmentID
            AND total.AccountID = fgl.AccountID
            AND total.VariabilityID = fgl.VariabilityID
		INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
        LEFT JOIN #variability fv ON fv.DepartmentID = fgl.DepartmentID
            AND fv.AccountID = fgl.AccountID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
 
    -- Find the deductions baseline for variable budget data by department & account
    SELECT fgl.DepartmentID, fgl.AccountID, SUM(fgl.BudgetDollarTotal) AS TotalDeductionsBudget, SUM(fgl.ProjectionDollarTotal) AS TotalDeductionsProjection
    INTO #deductions
    FROM #dollars fgl
	INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
    WHERE
        fgl.APEModelSectionID = 4  -- Deductions
        AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2)
    GROUP BY fgl.DepartmentID, fgl.AccountID
   
   -- Find the gross charges baseline for budget data by department. 
    -- Please note that all accounts (variable & fixed) are included if FF (@IncludeAllGrossChargesFlag) is ON
    SELECT fgl.DepartmentID, ROUND((SUM(BudgetDollarTotal)),@Precision,0) AS TotalGrossChargesBudget, ROUND((SUM(ProjectionDollarTotal)),@Precision,0) AS TotalGrossChargesProjection
    INTO #grossCharges
    FROM #dollars fgl
    WHERE
        fgl.APEModelSectionID = 1  -- Revenue
        AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2)
    GROUP BY fgl.DepartmentID
    
    SELECT GeneralLedgerID,
        CASE WHEN c.TotalGrossChargesBudget = 0 THEN 0 ELSE d.TotalDeductionsBudget / c.TotalGrossChargesBudget END AS CalculatedBudget,
        CASE WHEN c.TotalGrossChargesProjection = 0 THEN 0 ELSE d.TotalDeductionsProjection / c.TotalGrossChargesProjection END as CalculatedProjection
    INTO #calculatedPercentOfCharge
    FROM [fp].[GeneralLedger] fgl
    INNER JOIN #deductions d ON d.DepartmentID = fgl.DepartmentID AND d.AccountID = fgl.AccountID
    INNER JOIN #grossCharges c ON d.DepartmentID = c.DepartmentID
	INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
    WHERE fgl.BudgetConfigID = @BudgetConfigID
    IF @IsDebug = 1
    BEGIN
        SELECT 'Include All Gross Charges Accounts', @IncludeAllGrossChargesFlag
        SELECT '#totals', DepartmentID, AccountID, VariabilityID, SampledBudgetTotal, SampledProjectionTotal FROM #totals
        SELECT '#variability', DepartmentID, AccountID, FixedPercentage FROM #variability
        SELECT '#dollars', DepartmentID, AccountID, EntityGroupConfigID, APEModelSectionID, VariabilityID, BudgetDollarTotal, ProjectionDollarTotal FROM #dollars
        SELECT '#deductions', DepartmentID, AccountID, TotalDeductionsBudget, TotalDeductionsProjection FROM #deductions
        SELECT '#grossCharges', DepartmentID, TotalGrossChargesBudget, TotalGrossChargesProjection FROM #grossCharges
        SELECT '#calculatedPercentOfCharge', GeneralLedgerID, CalculatedBudget, CalculatedProjection, 'TotalDeductions / TotalGrossCharges' AS Calculation FROM #calculatedPercentOfCharge
    END ELSE
    BEGIN
        -- Use already imported values for percentage of charge 
        UPDATE fgl
        SET
            InitialBudgetPercentOfCharge01 = i.Value01,
            InitialBudgetPercentOfCharge02 = i.Value02,
            InitialBudgetPercentOfCharge03 = i.Value03,
            InitialBudgetPercentOfCharge04 = i.Value04,
            InitialBudgetPercentOfCharge05 = i.Value05,
            InitialBudgetPercentOfCharge06 = i.Value06,
            InitialBudgetPercentOfCharge07 = i.Value07,
            InitialBudgetPercentOfCharge08 = i.Value08,
            InitialBudgetPercentOfCharge09 = i.Value09,
            InitialBudgetPercentOfCharge10 = i.Value10,
            InitialBudgetPercentOfCharge11 = i.Value11,
            InitialBudgetPercentOfCharge12 = i.Value12
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 2
			INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
        WHERE fgl.BudgetConfigID = @BudgetConfigID
    
        UPDATE fgl
        SET
            InitialProjectionPercentOfCharge01 = IIF(1  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value01),
            InitialProjectionPercentOfCharge02 = IIF(2  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value02),
            InitialProjectionPercentOfCharge03 = IIF(3  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value03),
            InitialProjectionPercentOfCharge04 = IIF(4  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value04),
            InitialProjectionPercentOfCharge05 = IIF(5  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value05),
            InitialProjectionPercentOfCharge06 = IIF(6  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value06),
            InitialProjectionPercentOfCharge07 = IIF(7  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value07),
            InitialProjectionPercentOfCharge08 = IIF(8  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value08),
            InitialProjectionPercentOfCharge09 = IIF(9  <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value09),
            InitialProjectionPercentOfCharge10 = IIF(10 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value10),
            InitialProjectionPercentOfCharge11 = IIF(11 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value11),
            InitialProjectionPercentOfCharge12 = IIF(12 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value12)
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID 
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 12
			INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
            LEFT JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID
		WHERE fgl.BudgetConfigID = @BudgetConfigID
        -- Percent of charge is calculated by taking the Sum(Deduction Baseline) / Sum(Gross Charge Baseline)
        UPDATE fgl
        SET
            InitialBudgetPercentOfCharge01 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge02 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge03 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge04 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge05 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge06 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge07 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge08 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge09 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge10 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge11 = c.CalculatedBudget,
            InitialBudgetPercentOfCharge12 = c.CalculatedBudget
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID
			INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
            LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID 
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 2
		WHERE fgl.BudgetConfigID = @BudgetConfigID
            AND i.BudgetConfigID IS NULL
    
        UPDATE fgl
        SET 
            InitialProjectionPercentOfCharge01 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge02 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge03 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge04 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge05 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge06 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge07 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge08 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge09 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge10 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge11 = c.CalculatedProjection,
            InitialProjectionPercentOfCharge12 = c.CalculatedProjection
        FROM [fp].[GeneralLedger] fgl
            INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID
			INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID
            LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID 
                AND i.DepartmentID = fgl.DepartmentID 
                AND i.AccountID = fgl.AccountID 
                AND i.TimeClassID = 12
		WHERE fgl.BudgetConfigID = @BudgetConfigID
            AND i.BudgetConfigID IS NULL
    
    END
END
GO


---------------------------------------------

-- fp.procSampleReimbursementChargesClearData
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			Description
** 1		2022-03-29		MD		   JAZZ-33794	Initial
***************************************************************/

CREATE PROCEDURE fp.procSampleReimbursementChargesClearData
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END;
	DECLARE @r INT;

	-- delete existing data (have to do value tables first so that we still have EntityGroupConfigID)
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frcb 
			FROM [fp].[FactReimbursementChargesBudget] frcb
			INNER JOIN [fp].[FactReimbursementCharges] frc on frcb.ReimbursementChargesID = frc.ReimbursementChargesID 
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frcp
			FROM [fp].[FactReimbursementChargesProjection] frcp
			INNER JOIN [fp].[FactReimbursementCharges] frc on frcp.ReimbursementChargesID = frc.ReimbursementChargesID 
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frch 
			FROM [fp].[FactReimbursementChargesHistory] frch
			INNER JOIN [fp].[FactReimbursementCharges] frc on frch.ReimbursementChargesID = frc.ReimbursementChargesID 
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frc
			FROM [fp].[FactReimbursementCharges] frc
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

END
GO


---------------------------------------------

-- fp.procSampleReimbursementEncounterClearData
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			Description
** 1		2022-03-29		MD		   JAZZ-33794	Initial
***************************************************************/

CREATE PROCEDURE fp.procSampleReimbursementEncounterClearData
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END;
	DECLARE @r INT;

	-- delete existing data (have to do value tables first so that we still have EntityGroupConfigID)
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frcb 
			FROM [fp].[FactReimbursementEncounterBudget] frcb
			INNER JOIN [fp].[FactReimbursementEncounter] frc on frcb.ReimbursementEncounterID = frc.ReimbursementEncounterID 
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frcp
			FROM [fp].[FactReimbursementEncounterProjection] frcp
			INNER JOIN [fp].[FactReimbursementEncounter] frc on frcp.ReimbursementEncounterID = frc.ReimbursementEncounterID 
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frch 
			FROM [fp].[FactReimbursementEncounterHistory] frch
			INNER JOIN [fp].[FactReimbursementEncounter] frc on frch.ReimbursementEncounterID = frc.ReimbursementEncounterID 
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) frc
			FROM [fp].[FactReimbursementEncounter] frc
			WHERE frc.BudgetConfigID = @BudgetConfigID
	
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

END
GO


---------------------------------------------

-- fp.procSampleServiceLineEncounterClearData
CREATE   PROCEDURE [fp].[procSampleServiceLineEncounterClearData]
	@BudgetConfigGUID uniqueidentifier,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID SMALLINT,
	@SourceFiscalYearID SMALLINT,
	@SourceTimeClassID TINYINT,
	@IsRemoveEntityConfig BIT = 0
AS
BEGIN
/*************************************************************
** Change History
**************************************************************
** CID      Date        Author          WI  		Description
** 1        2021-02-25	lrenadesouza    JAZZ-12907	Added rolling deletes for all tables 
** 2        2023-01-17	bkrehl          JAZZ-48267	New data structure and only delete unneeded records 
** 3        2023-06-30  mdeboer			JAZZ-55672  Remove adjustment delete logic, add remove entity config logic	
** 4        2024-08-30  bwells			JAZZ-75594  Reset historical values to zero	
***************************************************************/
 	IF OBJECT_ID('tempdb..#toDelete') IS NOT NULL DROP TABLE #toDelete

	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END
	DECLARE @r INT; 	
	
	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												WHERE IsHidden = 1 AND BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												WHERE IsHidden = 1 AND BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;


	CREATE TABLE #toDelete (ServiceLineEncounterID INT)

	IF @IsRemoveEntityConfig = 1
	BEGIN
		INSERT INTO #toDelete with (tablock) (ServiceLineEncounterID)
		SELECT ServiceLineEncounterID 
		FROM fp.ServiceLineEncounter
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	ELSE
	BEGIN
		INSERT INTO #toDelete with (tablock) (ServiceLineEncounterID)
			SELECT ServiceLineEncounterID FROM
			(
				SELECT DISTINCT ServiceLineEncounterID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, AgeCohortID--, --leave MedicalSurgicalID and AgeCohortID as they are in the tables
				--DepartmentID, PayorID, PayorGroupID
				FROM [fp].[ServiceLineEncounter]
				WHERE EntityGroupConfigID = @EntityGroupConfigID
				AND IsNew = 0
			) sle  LEFT JOIN
				(SELECT EntityID, PatientClassID, sl.ServiceLineID, sl.RollupID AS ServiceLineRollupID, 
				CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID FROM
				[int].[FactServiceLine] fsl inner join fw.DimServiceLine sl on fsl.ServiceLineID = sl.ServiceLineID
				WHERE 
				((fsl.FiscalYearID = @SourceFiscalYearID AND fsl.TimeclassID = @SourceTimeClassID)		-- baseline
				OR (fsl.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
				OR (fsl.FiscalYearID = @CurrentFiscalYearID - 1 AND fsl.TimeClassID = 1))  				-- prior year, actual & budget
				AND fsl.IsDeleted = 0
				AND fsl.FiscalMonthID != 0				 
				) src
				ON sle.EntityID = src.EntityID
				AND sle.PatientClassID = src.PatientClassID
				AND sle.ServiceLineID = src.ServiceLineID
				AND sle.MedicalSurgicalID = src.MedicalSurgicalID
				AND sle.AgeCohortID = src.AgeCohortID
			WHERE 
				src.EntityID IS NULL
	END
		
	-- We need to wipe the history so that the adjustments can be re-applied aferwards
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) fsch FROM [fp].[ServiceLineEncounterChangeHistory] fsch INNER JOIN [fp].[ServiceLineEncounter] fs on fs.ServiceLineEncounterID = fsch.ServiceLineEncounterID WHERE fs.EntityGroupConfigID = @EntityGroupConfigID;
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
		
		
	-- delete existing data (have to do value tables first so that we still have EntityGroupConfigID)
	
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) sleh FROM [fp].[ServiceLineEncounterHistory] sleh INNER JOIN #toDelete tt on sleh.ServiceLineEncounterID=tt.ServiceLineEncounterID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
	
	SET @r = 1;	
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) sle FROM [fp].[ServiceLineEncounter] sle INNER JOIN #toDelete tt on sle.ServiceLineEncounterID=tt.ServiceLineEncounterID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	IF @IsRemoveEntityConfig = 0
	BEGIN
		-- Reset all values to 0
		UPDATE
			sle
		SET
		SampledBudget01 = 0,
			SampledBudget02 = 0,
			SampledBudget03 = 0,
			SampledBudget04 = 0,
			SampledBudget05 = 0,
			SampledBudget06 = 0,
			SampledBudget07 = 0,
			SampledBudget08 = 0,
			SampledBudget09 = 0,
			SampledBudget10 = 0,
			SampledBudget11 = 0,
			SampledBudget12 = 0,
		SampledProjection01 = 0,
			SampledProjection02 = 0,
			SampledProjection03 = 0,
			SampledProjection04 = 0,
			SampledProjection05 = 0,
			SampledProjection06 = 0,
			SampledProjection07 = 0,
			SampledProjection08 = 0,
			SampledProjection09 = 0,
			SampledProjection10 = 0,
			SampledProjection11 = 0,
			SampledProjection12 = 0,
		InitialBudget01 = 0,
			InitialBudget02 = 0,
			InitialBudget03 = 0,
			InitialBudget04 = 0,
			InitialBudget05 = 0,
			InitialBudget06 = 0,
			InitialBudget07 = 0,
			InitialBudget08 = 0,
			InitialBudget09 = 0,
			InitialBudget10 = 0,
			InitialBudget11 = 0,
			InitialBudget12 = 0,
		InitialProjection01 = 0,
			InitialProjection02 = 0,
			InitialProjection03 = 0,
			InitialProjection04 = 0,
			InitialProjection05 = 0,
			InitialProjection06 = 0,
			InitialProjection07 = 0,
			InitialProjection08 = 0,
			InitialProjection09 = 0,
			InitialProjection10 = 0,
			InitialProjection11 = 0,
			InitialProjection12 = 0,
		TargetAdjusted01 = 0,
			TargetAdjusted02 = 0,
			TargetAdjusted03 = 0,
			TargetAdjusted04 = 0,
			TargetAdjusted05 = 0,
			TargetAdjusted06 = 0,
			TargetAdjusted07 = 0,
			TargetAdjusted08 = 0,
			TargetAdjusted09 = 0,
			TargetAdjusted10 = 0,
			TargetAdjusted11 = 0,
			TargetAdjusted12 = 0,
		BudgetAdjusted01 = 0,
			BudgetAdjusted02 = 0,
			BudgetAdjusted03 = 0,
			BudgetAdjusted04 = 0,
			BudgetAdjusted05 = 0,
			BudgetAdjusted06 = 0,
			BudgetAdjusted07 = 0,
			BudgetAdjusted08 = 0,
			BudgetAdjusted09 = 0,
			BudgetAdjusted10 = 0,
			BudgetAdjusted11 = 0,
			BudgetAdjusted12 = 0,
		ProjectionAdjusted01 = 0,
			ProjectionAdjusted02 = 0,
			ProjectionAdjusted03 = 0,
			ProjectionAdjusted04 = 0,
			ProjectionAdjusted05 = 0,
			ProjectionAdjusted06 = 0,
			ProjectionAdjusted07 = 0,
			ProjectionAdjusted08 = 0,
			ProjectionAdjusted09 = 0,
			ProjectionAdjusted10 = 0,
			ProjectionAdjusted11 = 0,
			ProjectionAdjusted12 = 0
		FROM
			[fp].[ServiceLineEncounter] sle	                
		WHERE  sle.EntityGroupConfigID = @EntityGroupConfigID

		UPDATE
		    sleh
	    SET
		ActualYTDValue01 = 0,
		    ActualYTDValue02 = 0,
		    ActualYTDValue03 = 0,
		    ActualYTDValue04 = 0,
		    ActualYTDValue05 = 0,
		    ActualYTDValue06 = 0,
		    ActualYTDValue07 = 0,
		    ActualYTDValue08 = 0,
		    ActualYTDValue09 = 0,
		    ActualYTDValue10 = 0,
		    ActualYTDValue11 = 0,
		    ActualYTDValue12 = 0,
		PriorYearActualValue01 = 0,
		    PriorYearActualValue02 = 0,
		    PriorYearActualValue03 = 0,
		    PriorYearActualValue04 = 0,
		    PriorYearActualValue05 = 0,
		    PriorYearActualValue06 = 0,
		    PriorYearActualValue07 = 0,
		    PriorYearActualValue08 = 0,
		    PriorYearActualValue09 = 0,
		    PriorYearActualValue10 = 0,
		    PriorYearActualValue11 = 0,
		    PriorYearActualValue12 = 0,
		CurrentYearBudget01 = 0,
		    CurrentYearBudget02 = 0,
		    CurrentYearBudget03 = 0,
		    CurrentYearBudget04 = 0,
		    CurrentYearBudget05 = 0,
		    CurrentYearBudget06 = 0,
		    CurrentYearBudget07 = 0,
		    CurrentYearBudget08 = 0,
		    CurrentYearBudget09 = 0,
		    CurrentYearBudget10 = 0,
		    CurrentYearBudget11 = 0,
		    CurrentYearBudget12 = 0
	    FROM
		    [fp].[ServiceLineEncounterHistory] sleh
		INNER JOIN fp.ServiceLineEncounter sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID
		WHERE  sle.EntityGroupConfigID = @EntityGroupConfigID
	END
END;
GO


---------------------------------------------

-- fp.procSampleServiceLineEncounterDimensionality
/*************************************************************
** Change History
**************************************************************
** CID      Date            Author	   WI			Description
** 1        2022-12-12		DM		   JAZZ-46455   Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
** 2        2023-01-17      bkrehl     JAZZ-48267   New data structure and only delete unneeded records
** 3        2023-01-31      MD		   JAZZ-48529   Update non-DS client sampling for encounters
** 4        2023-05-30      JB		   JAZZ-49631   Section set up update for non-DS clients for encounters
***************************************************************/
CREATE   PROCEDURE [fp].[procSampleServiceLineEncounterDimensionality] 
	@BudgetConfigID int,
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint
AS
BEGIN
	
	DECLARE @IsPayorDisabled BIT;
	SELECT @IsPayorDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsPayorGroupDisabled BIT;
	SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsDepartmentDisabled BIT;
	SELECT @IsDepartmentDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;
	
	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	INSERT INTO 
		[fp].[ServiceLineEncounter]	([BudgetConfigID], [EntityGroupConfigID], [EntityID], 
		[PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], [AgeCohortID], 
		[PayorID], [PayorGroupID], [DepartmentID], [UnitTypeID], 
		BudgetLockType, BudgetLockFlag, TargetLockType, TargetLockFlag, ProjectionLockType, ProjectionLockFlag, IsNew)
	SELECT DISTINCT
		@BudgetConfigID,
		@EntityGroupConfigID,
		fsl.EntityID,
		fsl.PatientClassID,
		fsl.ServiceLineID,
		dsl.RollupID AS ServiceLineRollupID,
		fsl.MedicalSurgicalID,  -- if this is hidden per settings, the select from int.FactServiceLine already has this set to 0 if needed
		fsl.AgeCohortID,        -- same as MedicalSurgicalID
		fsl.PayorID,
		fsl.PayorGroupID,
		fsl.DepartmentID,
		140 AS UnitTypeID,
		0, 0, 0, 0, 0, 0, 0
	FROM(
		SELECT EntityID, PatientClassID, sl.ServiceLineID, sl.RollupID AS ServiceLineRollupID, 
            CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID,
			CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID,
			CASE WHEN @IsPayorDisabled = 1 THEN 0  ELSE PayorID END AS PayorID,
			CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID,
			CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID
		FROM [int].[FactServiceLine] fsl 
		INNER JOIN fw.DimServiceLine sl on fsl.ServiceLineID = sl.ServiceLineID
		WHERE 
			((fsl.FiscalYearID = @SourceFiscalYearID AND fsl.TimeclassID = @SourceTimeClassID)		-- baseline
			OR (fsl.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
			OR (fsl.FiscalYearID = @CurrentFiscalYearID - 1 AND fsl.TimeClassID = 1))  				-- prior year, actual & budget
			AND fsl.IsDeleted = 0
			AND fsl.FiscalMonthID != 0				 
		 ) fsl
		
		INNER JOIN [fw].[DimServiceLine] dsl ON fsl.ServiceLineID = dsl.ServiceLineID
		INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON fsl.EntityID = egcm.EntityID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		LEFT JOIN (
				-- Check for existing dimensionality so we only insert needed dimensionality
				SELECT DISTINCT EntityID, PatientClassID, ServiceLineID, MedicalSurgicalID, AgeCohortID, PayorID, PayorGroupID, DepartmentID
				FROM [fp].[ServiceLineEncounter]
				WHERE EntityGroupConfigID = @EntityGroupConfigID
			) existing
			ON fsl.EntityID = existing.EntityID
			AND fsl.PatientClassID = existing.PatientClassID
			AND fsl.ServiceLineID = existing.ServiceLineID
			AND fsl.MedicalSurgicalID = existing.MedicalSurgicalID
			AND fsl.AgeCohortID = existing.AgeCohortID
			AND fsl.PayorID = existing.PayorID
			AND fsl.PayorGroupID = existing.PayorGroupID
			AND fsl.DepartmentID = existing.DepartmentID
	WHERE 
		 egc.EntityGroupConfigID = @EntityGroupConfigID
		AND existing.EntityID IS NULL
END
GO


---------------------------------------------

-- fp.procSampleServiceLineEncounterHistoricalData
/*************************************************************
** Change History
**************************************************************
** CID    Date          Author      WI           Description
** 1      2022-12-12    DM          JAZZ-46455   Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
** 2      2023-01-17    bkrehl      JAZZ-48267   New data structure 
** 3      2023-01-31    MD			JAZZ-48529   Update non-DS client sampling for encounters
** 4      2023-05-30    JB			JAZZ-49631   Section set up update for non-DS clients for encounters
***************************************************************/
CREATE   PROCEDURE [fp].[procSampleServiceLineEncounterHistoricalData]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
AS
BEGIN

	-- Reset all values to 0 
	 UPDATE
		    sleh
	    SET
		    PriorYearActualValue01 = 0,
		    PriorYearActualValue02 = 0,
		    PriorYearActualValue03 = 0,
		    PriorYearActualValue04 = 0,
		    PriorYearActualValue05 = 0,
		    PriorYearActualValue06 = 0,
		    PriorYearActualValue07 = 0,
		    PriorYearActualValue08 = 0,
		    PriorYearActualValue09 = 0,
		    PriorYearActualValue10 = 0,
		    PriorYearActualValue11 = 0,
		    PriorYearActualValue12 = 0,
			ActualYTDValue01 = 0,
			ActualYTDValue02 = 0,
			ActualYTDValue03 = 0,
			ActualYTDValue04 = 0,
			ActualYTDValue05 = 0,
			ActualYTDValue06 = 0,
			ActualYTDValue07 = 0,
			ActualYTDValue08 = 0,
			ActualYTDValue09 = 0,
			ActualYTDValue10 = 0,
			ActualYTDValue11 = 0,
			ActualYTDValue12 = 0,
			CurrentYearBudget01 = 0,
			CurrentYearBudget02 = 0,
			CurrentYearBudget03 = 0,
			CurrentYearBudget04 = 0,
			CurrentYearBudget05 = 0,
			CurrentYearBudget06 = 0,
			CurrentYearBudget07 = 0,
			CurrentYearBudget08 = 0,
			CurrentYearBudget09 = 0,
			CurrentYearBudget10 = 0,
			CurrentYearBudget11 = 0,
			CurrentYearBudget12 = 0
	    FROM [fp].[ServiceLineEncounterHistory] sleh INNER JOIN [fp].[ServiceLineEncounter] sle on sle.ServiceLineEncounterID = sleh.ServiceLineEncounterID
		WHERE sle.EntityGroupConfigID = @EntityGroupConfigID

	-- Add any new records as needed
	INSERT INTO [fp].[ServiceLineEncounterHistory]([ServiceLineEncounterID])
	SELECT sle.[ServiceLineEncounterID]
	FROM [fp].[ServiceLineEncounter] sle LEFT JOIN [fp].[ServiceLineEncounterHistory] sleh on sle.ServiceLineEncounterID = sleh.ServiceLineEncounterID
	WHERE sle.EntityGroupConfigID = @EntityGroupConfigID AND sleh.ServiceLineEncounterID IS NULL

	DECLARE @IsPayorDisabled BIT;
	SELECT @IsPayorDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsPayorGroupDisabled BIT;
	SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsDepartmentDisabled BIT;
	SELECT @IsDepartmentDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;
	
	DECLARE @IsAgeCohortDisabled BIT;
	SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsMedicalSurgicalDisabled BIT;
	SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;
	
	


	-- set all of the values for prior year actual
	UPDATE
		sleh
	SET
		PriorYearActualValue01 = ISNULL(Month01, 0),
		PriorYearActualValue02 = ISNULL(Month02, 0),
		PriorYearActualValue03 = ISNULL(Month03, 0),
		PriorYearActualValue04 = ISNULL(Month04, 0),
		PriorYearActualValue05 = ISNULL(Month05, 0),
		PriorYearActualValue06 = ISNULL(Month06, 0),
		PriorYearActualValue07 = ISNULL(Month07, 0),
		PriorYearActualValue08 = ISNULL(Month08, 0),
		PriorYearActualValue09 = ISNULL(Month09, 0),
		PriorYearActualValue10 = ISNULL(Month10, 0),
		PriorYearActualValue11 = ISNULL(Month11, 0),
		PriorYearActualValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[ServiceLineEncounterHistory] sleh
		INNER JOIN [fp].[ServiceLineEncounter] sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID
		INNER JOIN (
			SELECT *
			FROM (
				SELECT 
					EntityID,
					PatientClassID,
					ServiceLineID,
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID,
					CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID,
					CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorID END AS PayorID,
					CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID,					
					fm.MonthColumnName,
					SUM(Value) as Value
				FROM [int].[FactServiceLine] src
					INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID
				WHERE 
					FiscalYearID = (@CurrentFiscalYearID - 1)
					AND TimeClassID = 1
					AND src.FiscalMonthID != 0
				GROUP BY
					EntityID,
					PatientClassID,
					ServiceLineID,
					AgeCohortID,
					MedicalSurgicalID,
					PayorGroupID,
					PayorID,
					DepartmentID,
					fm.MonthColumnName
				) data
				PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
		) src
			ON sle.EntityID = src.EntityID
			AND sle.PatientClassID = src.PatientClassID
			AND sle.ServiceLineID = src.ServiceLineID
			AND sle.AgeCohortID = src.AgeCohortID
			AND sle.MedicalSurgicalID = src.MedicalSurgicalID
			AND sle.PayorGroupID = src.PayorGroupID
			AND sle.PayorID = src.PayorID
			AND sle.DepartmentID = src.DepartmentID
	WHERE
		sle.EntityGroupConfigID = @EntityGroupConfigID


	-- set all of the values for current year actual/annualized
	UPDATE
		sleh
	SET
		ActualYTDValue01 = ISNULL(Month01, 0),
		ActualYTDValue02 = ISNULL(Month02, 0),
		ActualYTDValue03 = ISNULL(Month03, 0),
		ActualYTDValue04 = ISNULL(Month04, 0),
		ActualYTDValue05 = ISNULL(Month05, 0),
		ActualYTDValue06 = ISNULL(Month06, 0),
		ActualYTDValue07 = ISNULL(Month07, 0),
		ActualYTDValue08 = ISNULL(Month08, 0),
		ActualYTDValue09 = ISNULL(Month09, 0),
		ActualYTDValue10 = ISNULL(Month10, 0),
		ActualYTDValue11 = ISNULL(Month11, 0),
		ActualYTDValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[ServiceLineEncounterHistory] sleh
		INNER JOIN [fp].[ServiceLineEncounter] sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID
		INNER JOIN (
			SELECT *
			FROM (
				SELECT 
					EntityID,
					PatientClassID,
					ServiceLineID,
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID,	
					CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID,
					CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorID END AS PayorID,
					CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID,
					fm.MonthColumnName,
					SUM(Value) as Value
				FROM [int].[FactServiceLine] src
					INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID
				WHERE 
					FiscalYearID = @CurrentFiscalYearID
					AND TimeClassID = 1
					AND src.FiscalMonthID != 0
					AND fm.SortOrder <= @MonthsLoaded
				GROUP BY
					EntityID,
					PatientClassID,
					ServiceLineID,
					AgeCohortID,
					MedicalSurgicalID,
					PayorGroupID,
					PayorID,
					DepartmentID,
					fm.MonthColumnName
				) data
				PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
		) src
			ON sle.EntityID = src.EntityID
			AND sle.PatientClassID = src.PatientClassID
			AND sle.ServiceLineID = src.ServiceLineID
			AND sle.AgeCohortID = src.AgeCohortID
			AND sle.MedicalSurgicalID = src.MedicalSurgicalID
			AND sle.PayorGroupID = src.PayorGroupID
			AND sle.PayorID = src.PayorID
			AND sle.DepartmentID = src.DepartmentID
	WHERE
		sle.EntityGroupConfigID = @EntityGroupConfigID

	
	-- set all of the values for current year budget
	UPDATE
		sleh
	SET
		CurrentYearBudget01 = ISNULL(Month01, 0),
		CurrentYearBudget02 = ISNULL(Month02, 0),
		CurrentYearBudget03 = ISNULL(Month03, 0),
		CurrentYearBudget04 = ISNULL(Month04, 0),
		CurrentYearBudget05 = ISNULL(Month05, 0),
		CurrentYearBudget06 = ISNULL(Month06, 0),
		CurrentYearBudget07 = ISNULL(Month07, 0),
		CurrentYearBudget08 = ISNULL(Month08, 0),
		CurrentYearBudget09 = ISNULL(Month09, 0),
		CurrentYearBudget10 = ISNULL(Month10, 0),
		CurrentYearBudget11 = ISNULL(Month11, 0),
		CurrentYearBudget12 = ISNULL(Month12, 0)
	FROM
		[fp].[ServiceLineEncounterHistory] sleh
		INNER JOIN [fp].[ServiceLineEncounter] sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID
		INNER JOIN (
			SELECT *
			FROM (
				SELECT 
					EntityID,
					PatientClassID,
					ServiceLineID,
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID,
					CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID,
					CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorID END AS PayorID,
					CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID,
					fm.MonthColumnName,
					SUM(Value) as Value
				FROM [int].[FactServiceLine] src
					INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID
				WHERE 
					FiscalYearID = @CurrentFiscalYearID
					AND TimeClassID = 2
					AND src.FiscalMonthID != 0
				GROUP BY
					EntityID,
					PatientClassID,
					ServiceLineID,
					AgeCohortID,
					MedicalSurgicalID,
					PayorGroupID,
					PayorID,
					DepartmentID,
					fm.MonthColumnName
				) data
				PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
		) src
			ON sle.EntityID = src.EntityID
			AND sle.PatientClassID = src.PatientClassID
			AND sle.ServiceLineID = src.ServiceLineID
			AND sle.AgeCohortID = src.AgeCohortID
			AND sle.MedicalSurgicalID = src.MedicalSurgicalID
			AND sle.PayorGroupID = src.PayorGroupID
			AND sle.PayorID = src.PayorID
			AND sle.DepartmentID = src.DepartmentID
	WHERE
		sle.EntityGroupConfigID = @EntityGroupConfigID	
 
 
END
GO


---------------------------------------------

-- fp.procSampleServiceLineEncounterOriginalBudgetVolume
/*************************************************************
** Change History
**************************************************************
** CID      Date            Author	   WI			Description
** 1        2022-12-12		DM		   JAZZ-46455   Age Cohort and Medical/Surgical is linked to Section Setup checkboxes
** 2        2023-01-17      bkrehl     JAZZ-48267   New data structure and only delete unneeded records
** 3        2023-01-31      MD		   JAZZ-48529   Update non-DS client sampling for encounters
** 4        2023-05-30      JB		   JAZZ-49631   Section set up update for non-DS clients for encounters
***************************************************************/
CREATE   PROCEDURE [fp].[procSampleServiceLineEncounterOriginalBudgetVolume]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN

DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END)

DECLARE @IsPayorDisabled BIT;
	SELECT @IsPayorDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsPayorGroupDisabled BIT;
	SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	DECLARE @IsDepartmentDisabled BIT;
	SELECT @IsDepartmentDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;


DECLARE @IsAgeCohortDisabled BIT;
SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
						SELECT *
						FROM fp.SectionSetup ss
											INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
											INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
											WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0
						 )
						THEN CAST(1 AS BIT)
						ELSE CAST(0 AS BIT) END;

DECLARE @IsMedicalSurgicalDisabled BIT;
SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
						SELECT *
						FROM fp.SectionSetup ss
											INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
											INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
											WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0
						 )
						THEN CAST(1 AS BIT)
						ELSE CAST(0 AS BIT) END;
	UPDATE sle
	SET
			SampledBudget01 = ISNULL(Month01, 0),
			SampledBudget02 = ISNULL(Month02, 0),
			SampledBudget03 = ISNULL(Month03, 0),
			SampledBudget04 = ISNULL(Month04, 0),
			SampledBudget05 = ISNULL(Month05, 0),
			SampledBudget06 = ISNULL(Month06, 0),
			SampledBudget07 = ISNULL(Month07, 0),
			SampledBudget08 = ISNULL(Month08, 0),
			SampledBudget09 = ISNULL(Month09, 0),
			SampledBudget10 = ISNULL(Month10, 0),
			SampledBudget11 = ISNULL(Month11, 0),
			SampledBudget12 = ISNULL(Month12, 0)
	FROM [fp].[ServiceLineEncounter] sle
		INNER JOIN (
			SELECT *
			FROM (
				SELECT 
					EntityID,
					PatientClassID,
					ServiceLineID,
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID,
					CASE WHEN @IsPayorDisabled = 1 THEN 0  ELSE PayorID END AS PayorID,
					CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID,
					CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID,				
					fm.MonthColumnName,
					SUM(Value) as Value
				FROM [int].[FactServiceLine] src
					INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID
				WHERE 
					FiscalYearID = @SourceFiscalYearID
					AND TimeClassID = @SourceTimeClassID
					AND src.FiscalMonthID != 0
					AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
				GROUP BY
					EntityID,
					PatientClassID,
					ServiceLineID,
					AgeCohortID,
					MedicalSurgicalID,
					PayorGroupID,
					PayorID,
					DepartmentID,
					fm.MonthColumnName
				) data
				PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
		) src
			ON sle.EntityID = src.EntityID
			AND sle.PatientClassID = src.PatientClassID
			AND sle.ServiceLineID = src.ServiceLineID
			AND sle.AgeCohortID = src.AgeCohortID
			AND sle.MedicalSurgicalID = src.MedicalSurgicalID
			AND sle.PayorGroupID = src.PayorGroupID
			AND sle.PayorID = src.PayorID
			AND sle.DepartmentID = src.DepartmentID
	WHERE
		sle.EntityGroupConfigID = @EntityGroupConfigID


	-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data
	IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) 
	BEGIN
		-- per stackoverflow
		DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
		DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
		DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded)
        	
		UPDATE fs
	    SET
	        -- not doing month 1 because it wouldn't really make sense to annualize without at least 1 month of actual data
	        SampledBudget02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget02 END,
	        SampledBudget03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget03 END,
	        SampledBudget04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget04 END,
	        SampledBudget05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget05 END,
	        SampledBudget06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget06 END,
	        SampledBudget07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget07 END,
	        SampledBudget08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget08 END,
	        SampledBudget09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget09 END,
	        SampledBudget10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget10 END,
	        SampledBudget11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget11 END,
	        SampledBudget12 = CASE WHEN @MonthsLoaded < 12 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget12 END
        FROM [fp].[ServiceLineEncounter] fs
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
	END

	-- update the initial values to be equal to the sampled values on the dimensionality table
	UPDATE
		fs
	SET
		InitialBudget01 = SampledBudgetTotal / 12,
		InitialBudget02 = SampledBudgetTotal / 12,
		InitialBudget03 = SampledBudgetTotal / 12,
		InitialBudget04 = SampledBudgetTotal / 12,
		InitialBudget05 = SampledBudgetTotal / 12,
		InitialBudget06 = SampledBudgetTotal / 12,
		InitialBudget07 = SampledBudgetTotal / 12,
		InitialBudget08 = SampledBudgetTotal / 12,
		InitialBudget09 = SampledBudgetTotal / 12,
		InitialBudget10 = SampledBudgetTotal / 12,
		InitialBudget11 = SampledBudgetTotal / 12,
		InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12)
											  + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12))
	FROM [fp].[ServiceLineEncounter] fs
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID

END
GO


---------------------------------------------

-- fp.procSampleServiceLineEncounterOriginalProjectionVolume
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			Description
** 1		2022-12-12		DM		   JAZZ-46455	Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes
** 2		2023-01-17    bkrehl      JAZZ-48267  New data structure and only delete unneeded records
** 3        2023-01-31      MD		   JAZZ-48529   Update non-DS client sampling for encounters
** 4        2023-05-30      JB		   JAZZ-49631   Section set up update for non-DS clients for encounters
***************************************************************/
CREATE   PROCEDURE [fp].[procSampleServiceLineEncounterOriginalProjectionVolume]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
AS
BEGIN

IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals

DECLARE @IsPayorDisabled BIT;
SELECT @IsPayorDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

DECLARE @IsPayorGroupDisabled BIT;
SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

DECLARE @IsDepartmentDisabled BIT;
SELECT @IsDepartmentDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;
	
DECLARE @IsAgeCohortDisabled BIT;
SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS (
						SELECT *
						FROM fp.SectionSetup ss
											INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
											INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
											WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0
						 )
						THEN CAST(1 AS BIT)
						ELSE CAST(0 AS BIT) END;

DECLARE @IsMedicalSurgicalDisabled BIT;
SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS (
						SELECT *
						FROM fp.SectionSetup ss
											INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
											INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
											WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0
						 )
						THEN CAST(1 AS BIT)
						ELSE CAST(0 AS BIT) END;

	UPDATE sle
	SET
			SampledProjection01 = ISNULL(Month01, 0),
			SampledProjection02 = ISNULL(Month02, 0),
			SampledProjection03 = ISNULL(Month03, 0),
			SampledProjection04 = ISNULL(Month04, 0),
			SampledProjection05 = ISNULL(Month05, 0),
			SampledProjection06 = ISNULL(Month06, 0),
			SampledProjection07 = ISNULL(Month07, 0),
			SampledProjection08 = ISNULL(Month08, 0),
			SampledProjection09 = ISNULL(Month09, 0),
			SampledProjection10 = ISNULL(Month10, 0),
			SampledProjection11 = ISNULL(Month11, 0),
			SampledProjection12 = ISNULL(Month12, 0)
	FROM [fp].[ServiceLineEncounter] sle
		INNER JOIN (
			SELECT *
			FROM (
				SELECT 
					EntityID,
					PatientClassID,
					ServiceLineID,
					CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID,
					CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID,
					CASE WHEN @IsPayorDisabled = 1 THEN 0  ELSE PayorID END AS PayorID,
					CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID,
					CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID,
					fm.MonthColumnName,
					SUM(Value) as Value
				FROM [int].[FactServiceLine] src
					INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID
				WHERE 
					FiscalYearID = @CurrentFiscalYearID
					AND TimeClassID = 1
					AND src.FiscalMonthID != 0
					AND fm.SortOrder <= @MonthsLoaded
				GROUP BY
					EntityID,
					PatientClassID,
					ServiceLineID,
					AgeCohortID,
					MedicalSurgicalID,
					PayorGroupID,
					PayorID,
					DepartmentID,
					fm.MonthColumnName
				) data
				PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
		) src
			ON sle.EntityID = src.EntityID
			AND sle.PatientClassID = src.PatientClassID
			AND sle.ServiceLineID = src.ServiceLineID
			AND sle.AgeCohortID = src.AgeCohortID
			AND sle.MedicalSurgicalID = src.MedicalSurgicalID
			AND sle.PayorGroupID = src.PayorGroupID
			AND sle.PayorID = src.PayorID
			AND sle.DepartmentID = src.DepartmentID
	WHERE
		sle.EntityGroupConfigID = @EntityGroupConfigID


	-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	-- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize
	UPDATE
		sle
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END,
		SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END
	FROM
		[fp].[ServiceLineEncounter] sle
	WHERE
		sle.EntityGroupConfigID = @EntityGroupConfigID

	CREATE TABLE #Totals (ServiceLineEncounterID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)); 
		INSERT INTO #Totals (ServiceLineEncounterID, SampledProjectionTotal)
		SELECT ServiceLineEncounterID, 
			CASE WHEN @MonthsLoaded = 11 THEN sle.SampledProjection12  
					WHEN @MonthsLoaded = 10 THEN sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 9 THEN sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 8 THEN sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 7 THEN sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 6 THEN sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 5 THEN sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 4 THEN sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 3 THEN sle.SampledProjection04 + sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10  + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 2 THEN sle.SampledProjection03 + sle.SampledProjection04 + sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12
					WHEN @MonthsLoaded = 1 THEN sle.SampledProjection02 + sle.SampledProjection03 + sle.SampledProjection04 + sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12  
					ELSE 0
			END
			FROM [fp].[ServiceLineEncounter] sle
		WHERE sle.EntityGroupConfigID = @EntityGroupConfigID
		     
		      
		UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded)
		FROM #Totals a
		   
	UPDATE
		sle
	SET
		InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN sle.SampledProjection01 ELSE t.NewValue END,
		InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN sle.SampledProjection02 ELSE t.NewValue END,
		InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN sle.SampledProjection03 ELSE t.NewValue END,
		InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN sle.SampledProjection04 ELSE t.NewValue END,
		InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN sle.SampledProjection05 ELSE t.NewValue END,
		InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN sle.SampledProjection06 ELSE t.NewValue END,
		InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN sle.SampledProjection07 ELSE t.NewValue END,
		InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN sle.SampledProjection08 ELSE t.NewValue END,
		InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN sle.SampledProjection09 ELSE t.NewValue END,
		InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN sle.SampledProjection10 ELSE t.NewValue END,
		InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN sle.SampledProjection11 ELSE t.NewValue END,
		InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN sle.SampledProjection12 ELSE t.NewValue END
	FROM [fp].[ServiceLineEncounter] sle INNER JOIN #Totals t on sle.ServiceLineEncounterID = t.ServiceLineEncounterID
	WHERE sle.EntityGroupConfigID  = @EntityGroupConfigID 

END
GO


---------------------------------------------

-- fp.procSampleStaffingAdjustedData
CREATE     PROCEDURE [fp].[procSampleStaffingAdjustedData]	
	@EntityGroupConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	EXEC [dbo].[procSysDropTempTable] '#filterTable'

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	
	-- Update all target, budget, and projection adjusted
	UPDATE staff
		SET 
		  TargetAdjustedDollars01 = InitialBudgetDollars01
		, TargetAdjustedDollars02 = InitialBudgetDollars02
		, TargetAdjustedDollars03 = InitialBudgetDollars03
		, TargetAdjustedDollars04 = InitialBudgetDollars04
		, TargetAdjustedDollars05 = InitialBudgetDollars05
		, TargetAdjustedDollars06 = InitialBudgetDollars06
		, TargetAdjustedDollars07 = InitialBudgetDollars07
		, TargetAdjustedDollars08 = InitialBudgetDollars08
		, TargetAdjustedDollars09 = InitialBudgetDollars09
		, TargetAdjustedDollars10 = InitialBudgetDollars10
		, TargetAdjustedDollars11 = InitialBudgetDollars11
		, TargetAdjustedDollars12 = InitialBudgetDollars12
		, BudgetAdjustedDollars01 = InitialBudgetDollars01
		, BudgetAdjustedDollars02 = InitialBudgetDollars02
		, BudgetAdjustedDollars03 = InitialBudgetDollars03
		, BudgetAdjustedDollars04 = InitialBudgetDollars04
		, BudgetAdjustedDollars05 = InitialBudgetDollars05
		, BudgetAdjustedDollars06 = InitialBudgetDollars06
		, BudgetAdjustedDollars07 = InitialBudgetDollars07
		, BudgetAdjustedDollars08 = InitialBudgetDollars08
		, BudgetAdjustedDollars09 = InitialBudgetDollars09
		, BudgetAdjustedDollars10 = InitialBudgetDollars10
		, BudgetAdjustedDollars11 = InitialBudgetDollars11
		, BudgetAdjustedDollars12 = InitialBudgetDollars12
		, ProjectionAdjustedDollars01 = InitialProjectionDollars01
		, ProjectionAdjustedDollars02 = InitialProjectionDollars02
		, ProjectionAdjustedDollars03 = InitialProjectionDollars03
		, ProjectionAdjustedDollars04 = InitialProjectionDollars04
		, ProjectionAdjustedDollars05 = InitialProjectionDollars05
		, ProjectionAdjustedDollars06 = InitialProjectionDollars06
		, ProjectionAdjustedDollars07 = InitialProjectionDollars07
		, ProjectionAdjustedDollars08 = InitialProjectionDollars08
		, ProjectionAdjustedDollars09 = InitialProjectionDollars09
		, ProjectionAdjustedDollars10 = InitialProjectionDollars10
		, ProjectionAdjustedDollars11 = InitialProjectionDollars11
		, ProjectionAdjustedDollars12 = InitialProjectionDollars12

		, TargetAdjustedHours01 = InitialBudgetHours01
		, TargetAdjustedHours02 = InitialBudgetHours02
		, TargetAdjustedHours03 = InitialBudgetHours03
		, TargetAdjustedHours04 = InitialBudgetHours04
		, TargetAdjustedHours05 = InitialBudgetHours05
		, TargetAdjustedHours06 = InitialBudgetHours06
		, TargetAdjustedHours07 = InitialBudgetHours07
		, TargetAdjustedHours08 = InitialBudgetHours08
		, TargetAdjustedHours09 = InitialBudgetHours09
		, TargetAdjustedHours10 = InitialBudgetHours10
		, TargetAdjustedHours11 = InitialBudgetHours11
		, TargetAdjustedHours12 = InitialBudgetHours12
		, BudgetAdjustedHours01 = InitialBudgetHours01
		, BudgetAdjustedHours02 = InitialBudgetHours02
		, BudgetAdjustedHours03 = InitialBudgetHours03
		, BudgetAdjustedHours04 = InitialBudgetHours04
		, BudgetAdjustedHours05 = InitialBudgetHours05
		, BudgetAdjustedHours06 = InitialBudgetHours06
		, BudgetAdjustedHours07 = InitialBudgetHours07
		, BudgetAdjustedHours08 = InitialBudgetHours08
		, BudgetAdjustedHours09 = InitialBudgetHours09
		, BudgetAdjustedHours10 = InitialBudgetHours10
		, BudgetAdjustedHours11 = InitialBudgetHours11
		, BudgetAdjustedHours12 = InitialBudgetHours12
		, ProjectionAdjustedHours01 = InitialProjectionHours01
		, ProjectionAdjustedHours02 = InitialProjectionHours02
		, ProjectionAdjustedHours03 = InitialProjectionHours03
		, ProjectionAdjustedHours04 = InitialProjectionHours04
		, ProjectionAdjustedHours05 = InitialProjectionHours05
		, ProjectionAdjustedHours06 = InitialProjectionHours06
		, ProjectionAdjustedHours07 = InitialProjectionHours07
		, ProjectionAdjustedHours08 = InitialProjectionHours08
		, ProjectionAdjustedHours09 = InitialProjectionHours09
		, ProjectionAdjustedHours10 = InitialProjectionHours10
		, ProjectionAdjustedHours11 = InitialProjectionHours11
		, ProjectionAdjustedHours12 = InitialProjectionHours12

		, TargetAdjustedFTEs01 = InitialBudgetFTEs01
		, TargetAdjustedFTEs02 = InitialBudgetFTEs02
		, TargetAdjustedFTEs03 = InitialBudgetFTEs03
		, TargetAdjustedFTEs04 = InitialBudgetFTEs04
		, TargetAdjustedFTEs05 = InitialBudgetFTEs05
		, TargetAdjustedFTEs06 = InitialBudgetFTEs06
		, TargetAdjustedFTEs07 = InitialBudgetFTEs07
		, TargetAdjustedFTEs08 = InitialBudgetFTEs08
		, TargetAdjustedFTEs09 = InitialBudgetFTEs09
		, TargetAdjustedFTEs10 = InitialBudgetFTEs10
		, TargetAdjustedFTEs11 = InitialBudgetFTEs11
		, TargetAdjustedFTEs12 = InitialBudgetFTEs12
		, BudgetAdjustedFTEs01 = InitialBudgetFTEs01
		, BudgetAdjustedFTEs02 = InitialBudgetFTEs02
		, BudgetAdjustedFTEs03 = InitialBudgetFTEs03
		, BudgetAdjustedFTEs04 = InitialBudgetFTEs04
		, BudgetAdjustedFTEs05 = InitialBudgetFTEs05
		, BudgetAdjustedFTEs06 = InitialBudgetFTEs06
		, BudgetAdjustedFTEs07 = InitialBudgetFTEs07
		, BudgetAdjustedFTEs08 = InitialBudgetFTEs08
		, BudgetAdjustedFTEs09 = InitialBudgetFTEs09
		, BudgetAdjustedFTEs10 = InitialBudgetFTEs10
		, BudgetAdjustedFTEs11 = InitialBudgetFTEs11
		, BudgetAdjustedFTEs12 = InitialBudgetFTEs12
		, ProjectionAdjustedFTEs01 = InitialProjectionFTEs01
		, ProjectionAdjustedFTEs02 = InitialProjectionFTEs02
		, ProjectionAdjustedFTEs03 = InitialProjectionFTEs03
		, ProjectionAdjustedFTEs04 = InitialProjectionFTEs04
		, ProjectionAdjustedFTEs05 = InitialProjectionFTEs05
		, ProjectionAdjustedFTEs06 = InitialProjectionFTEs06
		, ProjectionAdjustedFTEs07 = InitialProjectionFTEs07
		, ProjectionAdjustedFTEs08 = InitialProjectionFTEs08
		, ProjectionAdjustedFTEs09 = InitialProjectionFTEs09
		, ProjectionAdjustedFTEs10 = InitialProjectionFTEs10
		, ProjectionAdjustedFTEs11 = InitialProjectionFTEs11
		, ProjectionAdjustedFTEs12 = InitialProjectionFTEs12

		, TargetAdjustedRate01 = InitialBudgetRate01
		, TargetAdjustedRate02 = InitialBudgetRate02
		, TargetAdjustedRate03 = InitialBudgetRate03
		, TargetAdjustedRate04 = InitialBudgetRate04
		, TargetAdjustedRate05 = InitialBudgetRate05
		, TargetAdjustedRate06 = InitialBudgetRate06
		, TargetAdjustedRate07 = InitialBudgetRate07
		, TargetAdjustedRate08 = InitialBudgetRate08
		, TargetAdjustedRate09 = InitialBudgetRate09
		, TargetAdjustedRate10 = InitialBudgetRate10
		, TargetAdjustedRate11 = InitialBudgetRate11
		, TargetAdjustedRate12 = InitialBudgetRate12
		, BudgetAdjustedRate01 = InitialBudgetRate01
		, BudgetAdjustedRate02 = InitialBudgetRate02
		, BudgetAdjustedRate03 = InitialBudgetRate03
		, BudgetAdjustedRate04 = InitialBudgetRate04
		, BudgetAdjustedRate05 = InitialBudgetRate05
		, BudgetAdjustedRate06 = InitialBudgetRate06
		, BudgetAdjustedRate07 = InitialBudgetRate07
		, BudgetAdjustedRate08 = InitialBudgetRate08
		, BudgetAdjustedRate09 = InitialBudgetRate09
		, BudgetAdjustedRate10 = InitialBudgetRate10
		, BudgetAdjustedRate11 = InitialBudgetRate11
		, BudgetAdjustedRate12 = InitialBudgetRate12
		, ProjectionAdjustedRate01 = InitialProjectionRate01
		, ProjectionAdjustedRate02 = InitialProjectionRate02
		, ProjectionAdjustedRate03 = InitialProjectionRate03
		, ProjectionAdjustedRate04 = InitialProjectionRate04
		, ProjectionAdjustedRate05 = InitialProjectionRate05
		, ProjectionAdjustedRate06 = InitialProjectionRate06
		, ProjectionAdjustedRate07 = InitialProjectionRate07
		, ProjectionAdjustedRate08 = InitialProjectionRate08
		, ProjectionAdjustedRate09 = InitialProjectionRate09
		, ProjectionAdjustedRate10 = InitialProjectionRate10
		, ProjectionAdjustedRate11 = InitialProjectionRate11
		, ProjectionAdjustedRate12 = InitialProjectionRate12

		FROM [fp].[Staffing]  staff
		INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID  AND IsNew = 0
	
END;
GO


---------------------------------------------

-- fp.procSampleStaffingClearData
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author			WI			   Description
** 1		2021-02-24		lrenadesouza	JAZZ-12907	Added FTERequest clean up and rolling deletes
** 2		2023-04-18		mdeboer		JAZZ-53496	Remove adjustment delete logic
** 3		2023-07-05		mdeboer		JAZZ-55672	Add remove config logic
** 4		2023-09-20		bkrehl			JAZZ-60973	Staffing restructure
** 5		2023-12-11      nthomas		JAZZ-64522     Add missing fp.StaffingWageRate table
***************************************************************/
CREATE   PROCEDURE [fp].[procSampleStaffingClearData]
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@EntityGroupConfigID INT,
	@IsRemoveConfig BIT = 0,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN	
	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END;
	DECLARE @r INT;

	CREATE TABLE #filterTable (DepartmentID int)
		INSERT INTO #filterTable (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing]
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END	

	CREATE TABLE #StaffingToDelete(StaffingID INT)

	IF @IsRemoveConfig = 1
	BEGIN
		INSERT #StaffingToDelete with (tablock) (StaffingID)
		SELECT StaffingID FROM fp.Staffing
		WHERE EntityGroupConfigID = @EntityGroupConfigID 
	END
	ELSE
	BEGIN
		INSERT #StaffingToDelete with (tablock) (StaffingID)
		SELECT StaffingID 
		FROM fp.Staffing fs
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0
	END
	
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;	
			--Delete all change history for reapply adjustments
			DELETE hist FROM [fp].[StaffingChangeHistory] hist 
			INNER JOIN [fp].[Staffing] staff on hist.StaffingID = staff.StaffingID 
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			WHERE staff.EntityGroupConfigID = @EntityGroupConfigID;
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) hist
			FROM [fp].[StaffingHistory] hist 
			INNER JOIN [fp].[Staffing] staff on staff.StaffingID = hist.StaffingID 
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			INNER JOIN #StaffingToDelete std on hist.StaffingID = std.StaffingID
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
		
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) wg
			FROM [fp].[StaffingWageRate] wg 
			INNER JOIN [fp].[Staffing] staff on staff.StaffingWageRateID = wg.StaffingWageRateID 
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
		
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN		
		BEGIN TRANSACTION;			  
			DELETE TOP (@ChunkCount) staff 
			FROM [fp].[Staffing] staff
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
END
GO


---------------------------------------------

-- fp.procSampleStaffingClearData_InitialPlan
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author			WI				Description
** 1		2024-05-01		MD				JAZZ-63557		Initial
***************************************************************/
CREATE    PROCEDURE [fp].[procSampleStaffingClearData_InitialPlan]
	@BudgetConfigGUID UNIQUEIDENTIFIER,
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN	
	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END;
	DECLARE @r INT;

	CREATE TABLE #filterTable (DepartmentID int)
		INSERT INTO #filterTable (DepartmentID)
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing]
		WHERE BudgetConfigID = @BudgetConfigID
	END	

	CREATE TABLE #StaffingToDelete(StaffingID INT)

	INSERT #StaffingToDelete with (tablock) (StaffingID)
		SELECT StaffingID 
		FROM fp.Staffing fs
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		WHERE fs.BudgetConfigID = @BudgetConfigID AND IsNew = 0
	
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;	
			--Delete all change history for reapply adjustments
			DELETE hist FROM [fp].[StaffingChangeHistory] hist 
			INNER JOIN [fp].[Staffing] staff on hist.StaffingID = staff.StaffingID 
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			WHERE staff.BudgetConfigID = @BudgetConfigID;
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) hist
			FROM [fp].[StaffingHistory] hist 
			INNER JOIN [fp].[Staffing] staff on staff.StaffingID = hist.StaffingID 
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			INNER JOIN #StaffingToDelete std on hist.StaffingID = std.StaffingID
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
		
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;		
			DELETE TOP (@ChunkCount) wg
			FROM [fp].[StaffingWageRate] wg 
			INNER JOIN [fp].[Staffing] staff on staff.StaffingWageRateID = wg.StaffingWageRateID 
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
		
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN		
		BEGIN TRANSACTION;			  
			DELETE TOP (@ChunkCount) staff 
			FROM [fp].[Staffing] staff
			INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
			INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
END
GO


---------------------------------------------

-- fp.procSampleStaffingCollapseVariableData
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-11-07  MY      JAZZ-35951		Add EmployeeID to FactStaffingVariabilityDetail
** 2    2023-09-20  BK      JAZZ-60973      Update for new data structure
*************************************************************/
CREATE PROCEDURE [fp].[procSampleStaffingCollapseVariableData]  
@BudgetConfigID int,  
@EntityGroupConfigID int,  
@EntityGroupConfigGUID uniqueidentifier,
@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY    
AS  
  
	SET NOCOUNT ON;   

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	  
	SELECT fs.BudgetConfigID, fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, min(fs.EmployeeID) as MinEmployeeID  
	INTO #tempData  
	FROM fp.Staffing fs  
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		INNER JOIN fp.EntityGroupConfig egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID  
		INNER JOIN fw.DimPayCode pc ON fs.PayCodeGroupID = pc.PayCodeGroupID  
		LEFT JOIN fp.FactStaffingVariabilityDetail fsvd ON fs.DepartmentID = fsvd.DepartmentID  
			AND fs.JobCodeID = fsvd.JobCodeID  
			AND fsvd.PayCodeID = pc.PayCodeID
			AND fs.EmployeeID = fsvd.EmployeeID
			AND fsvd.EntityGroupConfigGUID = @EntityGroupConfigGUID 
	WHERE fs.BudgetConfigID = @BudgetConfigID  
		AND fs.EntityGroupConfigID = @EntityGroupConfigID  
		AND fsvd.FixedPercentage < 1  
	GROUP BY fs.BudgetConfigID,fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID
  
	DELETE fs  
	FROM fp.Staffing fs  
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID  
			AND fs.EntityGroupConfigID = td.EntityGroupConfigID  
			AND fs.EntityID = td.EntityID  
			AND fs.DepartmentID = td.DepartmentID   
			AND fs.JobCodeID = td.JobCodeID  
			AND fs.PayCodeGroupID = td.PayCodeGroupID  
			AND fs.ProductiveClassID = td.ProductiveClassID  
			AND fs.VariabilityID = td.VariabilityID 
			AND fs.ProviderID = td.ProviderID  
			AND fs.ProviderTypeID = td.ProviderTypeID  
			AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID  
			AND fs.ProviderLineItemID = td.ProviderLineItemID  
			AND fs.SubsectionID = td.SubsectionID   
	AND fs.EmployeeID > td.MinEmployeeID  
  
	UPDATE fs  
	SET EmployeeID = 0  
	FROM fp.Staffing fs  
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID  
			AND fs.EntityGroupConfigID = td.EntityGroupConfigID  
			AND fs.EntityID = td.EntityID  
			AND fs.DepartmentID = td.DepartmentID   
			AND fs.JobCodeID = td.JobCodeID  
			AND fs.PayCodeGroupID = td.PayCodeGroupID  
			AND fs.ProductiveClassID = td.ProductiveClassID  
			AND fs.VariabilityID = td.VariabilityID  
			AND fs.ProviderID = td.ProviderID  
			AND fs.ProviderTypeID = td.ProviderTypeID  
			AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID  
			AND fs.ProviderLineItemID = td.ProviderLineItemID  
			AND fs.SubsectionID = td.SubsectionID 
	WHERE EmployeeID <> 0 
		AND fs.ProviderID = 0 -- Provider sampling will include EmployeeID, so we need to exclude provider records from this
GO


---------------------------------------------

-- fp.procSampleStaffingCollapseVariableData_InitialPlan
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI				Description
** 1	2022-11-07  MY      JAZZ-35951		Add EmployeeID to FactStaffingVariabilityDetail
** 2    2023-09-20  BK      JAZZ-60973      Update for new data structure
** 3    2024-04-26  MD      JAZZ-63557      Update to be at budget config level
*************************************************************/
CREATE   PROCEDURE [fp].[procSampleStaffingCollapseVariableData_InitialPlan]  
@BudgetConfigGUID UNIQUEIDENTIFIER,  
@BudgetConfigID INT,  
@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY    
AS  
  
	SET NOCOUNT ON;   

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE BudgetConfigID = @BudgetConfigID
	END
	  
	SELECT fs.BudgetConfigID, fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, min(fs.EmployeeID) as MinEmployeeID  
	INTO #tempData  
	FROM fp.Staffing fs  
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		INNER JOIN fp.EntityGroupConfig egc 
			ON egc.BudgetConfigGUID = @BudgetConfigGUID
			AND fs.EntityGroupConfigID = egc.EntityGroupConfigID  
		INNER JOIN fw.DimPayCode pc ON fs.PayCodeGroupID = pc.PayCodeGroupID  
		LEFT JOIN fp.FactStaffingVariabilityDetail fsvd ON fs.DepartmentID = fsvd.DepartmentID  
			AND fs.JobCodeID = fsvd.JobCodeID  
			AND fsvd.PayCodeID = pc.PayCodeID
			AND fs.EmployeeID = fsvd.EmployeeID
			AND fsvd.EntityGroupConfigGUID = egc.EntityGroupConfigGUID 
	WHERE fs.BudgetConfigID = @BudgetConfigID  
		AND fsvd.FixedPercentage < 1  
	GROUP BY fs.BudgetConfigID,fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID
  
	DELETE fs  
	FROM fp.Staffing fs  
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID  
			AND fs.EntityGroupConfigID = td.EntityGroupConfigID  
			AND fs.EntityID = td.EntityID  
			AND fs.DepartmentID = td.DepartmentID   
			AND fs.JobCodeID = td.JobCodeID  
			AND fs.PayCodeGroupID = td.PayCodeGroupID  
			AND fs.ProductiveClassID = td.ProductiveClassID  
			AND fs.VariabilityID = td.VariabilityID 
			AND fs.ProviderID = td.ProviderID  
			AND fs.ProviderTypeID = td.ProviderTypeID  
			AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID  
			AND fs.ProviderLineItemID = td.ProviderLineItemID  
			AND fs.SubsectionID = td.SubsectionID   
	AND fs.EmployeeID > td.MinEmployeeID  
  
	UPDATE fs  
	SET EmployeeID = 0  
	FROM fp.Staffing fs  
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID  
			AND fs.EntityGroupConfigID = td.EntityGroupConfigID  
			AND fs.EntityID = td.EntityID  
			AND fs.DepartmentID = td.DepartmentID   
			AND fs.JobCodeID = td.JobCodeID  
			AND fs.PayCodeGroupID = td.PayCodeGroupID  
			AND fs.ProductiveClassID = td.ProductiveClassID  
			AND fs.VariabilityID = td.VariabilityID  
			AND fs.ProviderID = td.ProviderID  
			AND fs.ProviderTypeID = td.ProviderTypeID  
			AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID  
			AND fs.ProviderLineItemID = td.ProviderLineItemID  
			AND fs.SubsectionID = td.SubsectionID 
	WHERE EmployeeID <> 0 
		AND fs.ProviderID = 0 -- Provider sampling will include EmployeeID, so we need to exclude provider records from this
GO


---------------------------------------------

-- fp.procSampleStaffingDimensionality
CREATE   PROCEDURE [fp].[procSampleStaffingDimensionality]  
	@BudgetConfigID int,  
	@EntityGroupConfigID int,  
	@CurrentFiscalYearID smallint,  
	@SourceFiscalYearID smallint,  
	@SourceTimeClassID tinyint,  
	@IsEmployeeBudgeting bit,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS  
BEGIN  

	 /**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI             Description
	 ** 4 	 2021-03-22  NT  	 JAZZ-15374		Use NPI instead of EmployeID for Provider Comp Sampling
	 ** 5 	 2021-06-30  BW  	 JAZZ-21627		Update selects for EmployeID for variablity
	 ** 6 	 2021-09-07  BW  	 JAZZ-25863     Check for dept. usage of Employee Budgeting when sampling
	 ** 7 	 2021-12-01  OP		 JAZZ-29466     removed empty users check for prov comp data
	 ** 8 	 2022-03-02  MZ		 JAZZ-30547     improved checks in order to sample valid Employees with valid NPI
	 ** 9 	 2022-05-31  BW		 JAZZ-37832     If IsHoursIgnored and IsDollarsIgnored are both true, then the dimensionality should not be pulled in
	 ** 10	 2022-08-08  BK		 JAZZ-38357     Make sure IsFP records are correctly sampled depending on if true or false
	 ** 11   2022-10-07  AO      JAZZ-42868     Non-provider department samples correct staffing values when provider sampling feature is turned on.
	 ** 12   2022-10-26  MZ      JAZZ-42873     Departments and employees extended by projection (current year actuals) and prior year, actual
	 ** 13   2022-11-07  MZ		 JAZZ-35344		improved checks in order to sample valid Employees with valid NPI from FactProvider
	 ** 14	 11-7-2022   MY      JAZZ-35951		Add EmployeeID to FactStaffingVariabilityDetail
	 ** 15	 2022-12-12	 DM		 JAZZ-46455		Samplimg of Provider Type and Provider Specialty is linked to Section Setup
	 ** 16	 2023-09-26	 BK		 JAZZ-61239		Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing
	 ** 17	 2023-09-30	 BK		 JAZZ-60973		Update for new data structure
	 ** 18   2023-12-07	 NT		 JAZZ-64522		Fix INSERT into fp.StaffingWageRate that is causing Sampling to fail
	 ** 19   2024-02-01	 MD		 JAZZ-67072		Fix INSERT into fp.StaffingWageRate that is causing Sampling to fail - Part 2: Electric Boogaloo
	 ** 20	 2024-02-02	 NH		 JAZZ-64064		Move Provider Planning FF as a setting in Plan Config
	 ** 21   2024-03-25  MY      JAZZ-69661		Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
	 ** 22   2024-06-18  AO      JAZZ-72231		Added Source Provider Sampling
	 ** 23   2024-10-22	 VZ		  JAZZ-76243		Extended condition for int.factStaffing for populating provider compensation data
	 *************************************************************/

	--D-09416
	--Updated data pull to be two separate temp tables so I can join them on EmployeeID after the case statement is run 
	IF OBJECT_ID('tempdb..#rawStaffingData') IS NOT NULL DROP TABLE #rawStaffingData
	IF OBJECT_ID('tempdb..#newStaffingData') IS NOT NULL DROP TABLE #newStaffingData
	IF OBJECT_ID('tempdb..#dimensions') IS NOT NULL DROP TABLE #dimensions
	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable
	IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims


	CREATE TABLE #rawStaffingData  (EntityID INT, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, ProviderLineItemID INT, SubsectionID INT)  
	CREATE TABLE #newStaffingData (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, ProviderLineItemID INT, SubsectionID INT)  
	CREATE TABLE #dimensions (EntityID INT, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, ProviderLineItemID INT, SubsectionID INT)  

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED)
		INNER JOIN [fp].[EntityGroupConfigMapping] egcm on egcm.EntityID = d.EntityID
		INNER JOIN [fp].[EntityGroupConfig] egc ON  egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
		WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
	END

	DECLARE @StaffingSubsectionID INT = 3;
	DECLARE @ProviderSubsectionID INT = 4;

	DECLARE @IsProviderPlanningEnabled BIT;
	DECLARE @UseProviderSource BIT;
	DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT;

	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

	SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID


	INSERT INTO #newStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID)
	SELECT DISTINCT 
		fs.DepartmentID, 
		fs.JobCodeID, 
		fs.PayCodeGroupID, 
		fs.ProductiveClassID,
		CASE WHEN @IsEmployeeBudgeting = 0 THEN 0 ELSE fs.EmployeeID END AS EmployeeID, 
		fs.ProviderID, 
		fs.ProviderTypeID, 
		fs.ProviderSpecialtyID, 
		fs.ProviderLineItemID, 
		fs.SubsectionID
	FROM [fp].[Staffing] fs
	INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID  
	AND fs.IsNew = 1 

	DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER;
	SELECT @EntityGroupConfigGUID = EntityGroupConfigGUID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID  

	IF @IsProviderPlanningEnabled = 0 -- Is Provider Sampling Enabled
	BEGIN
		-------------------------------------------------------
		-- Provider is disabled
		-------------------------------------------------------

		INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, 
			ProviderSpecialtyID, ProviderLineItemID, SubsectionID)  
		SELECT DISTINCT  
			dept.EntityID,  
			fs.DepartmentID,   
			fs.JobCodeID,  
			pcg.PayCodeGroupID,  
			pcg.ProductiveClassID,  
			CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE fs.EmployeeID
				END
			END as EmployeeID,
			0, 
			0, 
			0, 
			0, 
			3 -- Staffing
		FROM  
		[int].[FactStaffing] fs
			INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimJobCode] dj on dj.JobCodeID = fs.JobCodeID  
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID  
			INNER JOIN [fw].[DimDepartment] dept ON fs.DepartmentID = dept.DepartmentID  
			INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID  
			INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID  
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID  
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = fs.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = fs.DepartmentID    
				AND fv.JobCodeID = fs.JobCodeID     
				AND fv.PayCodeID = fs.PayCodeID   
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE fs.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID  
		WHERE   
			((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID)  -- baseline  
			OR (fs.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
			OR (fs.FiscalYearID = @CurrentFiscalYearID - 1  AND fs.TimeClassID = 1))       -- prior year, actual  
			AND fs.IsDeleted = 0  
			AND fs.FiscalMonthID != 0  
			AND egc.EntityGroupConfigID = @EntityGroupConfigID  
			AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0)

	END ELSE BEGIN  
	
		-------------------------------------------------------
		-- Provider is enabled
		-------------------------------------------------------

		IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
		IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept
		CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT)
		CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)
		CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT)

		DECLARE @IsProviderTypeDisabled BIT;
		SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1
									)
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

	
		DECLARE @IsProviderSpecialtyDisabled BIT;
		SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
									)
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END; 

		-- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
		DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 
							FROM fp.BudgetConfigSetting setting 
								INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
							WHERE def.Name = 'Enable Department Level Provider For Sampling'
						   		AND setting.BudgetConfigID = @BudgetConfigID
			  					AND setting.Value = 1), 0)

		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN
			
			-------------------------------------------------------
			-- BudgetConfigSetting is disabled
			-------------------------------------------------------

			-- Get all departments that use Provider Staffing
			-- Get all employees that are providers
			-- Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling
			-- Sample regular data for non provider employees and departments that are not configured to use provider sampling
	
			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID)
				OR (staff.FiscalYearID = @CurrentFiscalYearID)
				OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1))
				AND staff.IsDeleted = 0 
				AND staff.FiscalMonthID != 0 				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID)  -- baseline  
				OR (prov.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
				OR (prov.FiscalYearID = @CurrentFiscalYearID - 1  AND prov.TimeClassID = 1))       -- prior year, actual  
				AND prov.IsDeleted = 0
				AND prov.FiscalMonthID != 0				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
				emp.EmployeeID, 
				phys.PhysicianID,
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID)
				OR (staff.FiscalYearID = @CurrentFiscalYearID)
				OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1))
				AND staff.IsDeleted = 0 
				AND staff.FiscalMonthID != 0 				 				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')
			UNION		
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
				phys.EmployeeID, 
				phys.PhysicianID,
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID)  -- baseline  
				OR (prov.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
				OR (prov.FiscalYearID = @CurrentFiscalYearID - 1  AND prov.TimeClassID = 1))       -- prior year, actual  
				AND prov.IsDeleted = 0
				AND prov.FiscalMonthID != 0					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')
				AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later
					
			-- Provider from int.FactProvider
			INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID)  		  
				SELECT
				DISTINCT
				dept.EntityID,
				fs.DepartmentID, 
				0 as JobCodeID,  
				0 as PayCodeGroupID,  
				0 as ProductiveClassID,
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fs.ProviderLineItemID,
				@ProviderSubsectionID
			FROM
				[int].[FactProvider] fs
				INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fs.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fs.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID			
			WHERE 
				((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID)  -- baseline  
				OR (fs.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
				OR (fs.FiscalYearID = @CurrentFiscalYearID - 1  AND fs.TimeClassID = 1))       -- prior year, actual  
				AND fs.IsDeleted = 0  
				AND fs.FiscalMonthID != 0  
				AND ps.Description = 'Staffing'
				AND emp.IsFP = 1
				AND fs.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

			INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #rawStaffingData

			-- Provider from int.FactStaffing
			INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID)  		  
			SELECT
				DISTINCT
				dept.EntityID,
				fs.DepartmentID, 
				fs.JobCodeID,  
				pcg.PayCodeGroupID,  
				pcg.ProductiveClassID,
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				@ProviderSubsectionID
			FROM
				[int].[FactStaffing] fs
				INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fs.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID  
				INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID  
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
				LEFT JOIN #provDims pd ON fs.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID
			WHERE 
				((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID)  -- baseline  
				OR (fs.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
				OR (fs.FiscalYearID = @CurrentFiscalYearID - 1  AND fs.TimeClassID = 1))       -- prior year, actual  
				AND fs.IsDeleted = 0  
				AND fs.FiscalMonthID != 0  
				AND ps.Description = 'Staffing'
				AND pd.DepartmentID IS NULL
				AND emp.IsFP = 1
				AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0)
		END ELSE BEGIN
			
			-------------------------------------------------------
			-- BudgetConfigSetting is enabled
			-------------------------------------------------------

			IF @UseProviderSource = 0
			BEGIN
				
				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is disabled
				-------------------------------------------------------
				
				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID)
					OR (staff.FiscalYearID = @CurrentFiscalYearID)
					OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1))
					AND staff.IsDeleted = 0 
					AND staff.FiscalMonthID != 0 				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1 
				
				-- 2. Employees from staffing 
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
					emp.EmployeeID, 
					phys.PhysicianID,
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
					INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID)
					OR (staff.FiscalYearID = @CurrentFiscalYearID)
					OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1))
					AND staff.IsDeleted = 0 
					AND staff.FiscalMonthID != 0 				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND staff.EmployeeID > 0
					AND emp.NPI NOT IN ('Not Specified', '0', '')


				-- Provider from int.FactStaffing
				INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID)  		  
				SELECT
					DISTINCT
					dept.EntityID,
					fs.DepartmentID, 
					fs.JobCodeID,  
					pcg.PayCodeGroupID,  
					pcg.ProductiveClassID,
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					pc.ProviderLineItemID,
					@ProviderSubsectionID
				FROM
					[int].[FactStaffing] fs
					INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fs.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID  
					INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID  
					INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
				WHERE 
					((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID)  -- baseline  
					OR (fs.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
					OR (fs.FiscalYearID = @CurrentFiscalYearID - 1  AND fs.TimeClassID = 1))       -- prior year, actual  
					AND fs.IsDeleted = 0  
					AND fs.FiscalMonthID != 0  
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
					AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0)

			END ELSE BEGIN
			
				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is enabled
				-------------------------------------------------------

				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID)  -- baseline  
					OR (prov.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
					OR (prov.FiscalYearID = @CurrentFiscalYearID - 1  AND prov.TimeClassID = 1))       -- prior year, actual  
					AND prov.IsDeleted = 0
					AND prov.FiscalMonthID != 0				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later

				-- 2. Employees from provider 
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)		
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
					phys.EmployeeID, 
					phys.PhysicianID,
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
					INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID)  -- baseline  
					OR (prov.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
					OR (prov.FiscalYearID = @CurrentFiscalYearID - 1  AND prov.TimeClassID = 1))       -- prior year, actual  
					AND prov.IsDeleted = 0
					AND prov.FiscalMonthID != 0					
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND phys.NPI NOT IN ('Not Specified', '0', '')
					AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later
					
				-- Provider from int.FactProvider
				INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID)  		  
					SELECT
					DISTINCT
					dept.EntityID,
					fs.DepartmentID, 
					0 as JobCodeID,  
					0 as PayCodeGroupID,  
					0 as ProductiveClassID,
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					fs.ProviderLineItemID,
					@ProviderSubsectionID
				FROM
					[int].[FactProvider] fs
					INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fs.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID   
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fs.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID			
				WHERE 
					((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID)  -- baseline  
					OR (fs.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
					OR (fs.FiscalYearID = @CurrentFiscalYearID - 1  AND fs.TimeClassID = 1))       -- prior year, actual  
					AND fs.IsDeleted = 0  
					AND fs.FiscalMonthID != 0  
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
					AND fs.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
			END
		END

		-- All non-provider records here, regular staffing
		INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID)  		  
			SELECT
			DISTINCT
			d.EntityID,
			fs.DepartmentID, 
			fs.JobCodeID,  
			pcg.PayCodeGroupID,  
			pcg.ProductiveClassID,
			CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE fs.EmployeeID
				END
			END as EmployeeID,
			0, --ProviderID
			0, --ProviderTypeID
			0, --ProviderSpecialtyID
			0, --ProviderLineItemID
			@StaffingSubsectionID
		FROM
			[int].[FactStaffing] fs
			INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
			LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON fs.EmployeeID = emp.EmployeeID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON fs.EmployeeID = NotFpEmp.EmployeeID
			INNER JOIN [fw].[DimDepartment] d ON tmp.DepartmentID = d.DepartmentID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID  
			INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID  
			INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID 
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg ON sefg.DepartmentID = fs.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = fs.DepartmentID 
				AND fv.JobCodeID = fs.JobCodeID     
				AND fv.PayCodeID = fs.PayCodeID   
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE fs.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
		WHERE 
			((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID)  -- baseline  
			OR (fs.FiscalYearID = @CurrentFiscalYearID)             -- projection (current year actuals)  
			OR (fs.FiscalYearID = @CurrentFiscalYearID - 1  AND fs.TimeClassID = 1))       -- prior year, actual  
			AND fs.IsDeleted = 0  
			AND fs.FiscalMonthID != 0  
			AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0)))
			AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0)	
	END

	INSERT INTO #dimensions (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) 
	SELECT rs.EntityID,  
		rs.DepartmentID,   
		rs.JobCodeID,  
		rs.PayCodeGroupID,  
		rs.ProductiveClassID,
		rs.EmployeeID,
		rs.ProviderID,
		rs.ProviderTypeID,
		rs.ProviderSpecialtyID,
		rs.ProviderLineItemID,
		rs.SubsectionID
	FROM #rawStaffingData rs
		LEFT JOIN #newStaffingData ns ON rs.DepartmentID = ns.DepartmentID  
			AND rs.JobCodeID = ns.JobCodeID  
			AND rs.PayCodeGroupID = ns.PayCodeGroupID  
			AND rs.ProductiveClassID = ns.ProductiveClassID  
			AND rs.EmployeeID = ns.EmployeeID  
			AND rs.ProviderID = ns.ProviderID  
			AND rs.ProviderTypeID = ns.ProviderTypeID  
			AND rs.ProviderSpecialtyID = ns.ProviderSpecialtyID  
			AND rs.ProviderLineItemID = ns.ProviderLineItemID  
			AND rs.SubsectionID = ns.SubsectionID  
	WHERE ns.DepartmentID IS NULL  

	INSERT INTO [fp].[Staffing]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [EmployeeID], [VariabilityID], 
									ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID)  
	SELECT DISTINCT  
		@BudgetConfigID,  
		@EntityGroupConfigID,  
		d.EntityID,  
		d.DepartmentID,   
		d.JobCodeID,  
		d.PayCodeGroupID,  
		d.ProductiveClassID,  
		d.EmployeeID,  
		vari.VariabilityID,  
		d.ProviderID,
		d.ProviderTypeID,
		d.ProviderSpecialtyID,
		d.ProviderLineItemID,
		d.SubsectionID 
	FROM  
	#dimensions d        
	CROSS APPLY (VALUES (1),(2)) vari(VariabilityID)  
  
	--Wage Rate  
	INSERT INTO [fp].[StaffingWageRate] (StaffingWageRateID)   
	SELECT StaffingID 
	FROM fp.Staffing staff
	JOIN #filterTable ft on staff.DepartmentID = ft.DepartmentID
	WHERE BudgetConfigID = @BudgetConfigID
	  AND EntityGroupConfigID = @EntityGroupConfigID
	  AND VariabilityID = 1
	  AND IsNew = 0

	UPDATE staff 
	SET StaffingWageRateID = StaffingID
	FROM fp.Staffing staff
	JOIN #filterTable ft on staff.DepartmentID = ft.DepartmentID
	WHERE BudgetConfigID = @BudgetConfigID
	  AND EntityGroupConfigID = @EntityGroupConfigID
	  AND VariabilityID = 1
	  AND IsNew = 0
	  
	UPDATE a SET StaffingWageRateID = fixed.StaffingID 
	FROM fp.Staffing a 
	JOIN #filterTable ft on a.DepartmentID = ft.DepartmentID
	INNER JOIN fp.Staffing fixed 
	  ON  a.DepartmentID = fixed.DepartmentID
	  AND a.JobCodeID = fixed.JobCodeID
	  AND a.PayCodeGroupID = fixed.PayCodeGroupID
	  AND a.BudgetConfigID = fixed.BudgetConfigID
	  AND a.EntityGroupConfigID = fixed.EntityGroupConfigID
	  AND a.EntityID = fixed.EntityID
	  AND a.ProductiveClassID = fixed.ProductiveClassID
	  AND a.ProviderID = fixed.ProviderID
	  AND a.ProviderLineItemID = fixed.ProviderLineItemID
	  AND a.ProviderTypeID = fixed.ProviderTypeID
	  AND a.ProviderSpecialtyID = fixed.ProviderSpecialtyID
	  AND a.EmployeeID = fixed.EmployeeID
	WHERE a.VariabilityID = 2 AND fixed.VariabilityID = 1
	 AND a.IsNew = 0
      
END
GO


---------------------------------------------

-- fp.procSampleStaffingDollarsPerUOS
CREATE PROCEDURE [fp].[procSampleStaffingDollarsPerUOS]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@StaffingFiscalYearID INT,
	@StaffingTimeClassID INT,
	@CurrentFiscalYearID INT,
	@MonthsLoaded INT,	
	@IsEmployeeBudgeting BIT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS 
BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI				Description
	 ** 1 	 2021-01-14  MY  	 JAZZ-12607		Initial
	 ** 2 	 2021-12-09  BK		 JAZZ-30703		Use fp.FactStatisticsHistory historicals instead of int.FactStatistic
	 ** 3 	 2022-03-02  MZ		 JAZZ-30547		improved checks in order to sample valid Employees with valid NPI
	 ** 4    2022-05-17  OP      JAZZ-34114		improved sampling in order to support Dollars per UOS for Provider Comp
	 ** 5    2022-11-07  MZ		 JAZZ-35344		improved checks in order to sample valid Employees with valid NPI from FactProvider
	 ** 6	 2022-12-12	 DM		 JAZZ-46455		Sampling of Provider Type and Provider Specialty is linked to Section Setup
	 ** 7	 2023-03-13	 MY		 JAZZ-48981		Update sampling for cross department flexing
     ** 8    2023-09-20  BK      JAZZ-60973     Update for new data structure
	 ** 9    2024-08-19  AO      JAZZ-75410     Added Source Provider Sampling
	 *************************************************************/

	-- Clearing temp tables for next run
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData;
	IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData;
	IF OBJECT_ID('tempdb..#departmentsConfiguredToFlex') IS NOT NULL DROP TABLE #departmentsConfiguredToFlex;
	IF OBJECT_ID('tempdb..#flexConfigMapping') IS NOT NULL DROP TABLE #flexConfigMapping;
	IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims;
	IF OBJECT_ID('tempdb..#staffingConfiguredToFlex') IS NOT NULL DROP TABLE #staffingConfiguredToFlex;
	IF OBJECT_ID('tempdb..#uniqueStatMapping') IS NOT NULL DROP TABLE #uniqueStatMapping;
	IF OBJECT_ID('tempdb..#statsBudget') IS NOT NULL DROP TABLE #statsBudget;

	-- Create temp tables to store manipulated data
	CREATE TABLE #TempIntStaffingData (
		DepartmentID INT,  
		JobCodeID INT,  
		PayCodeGroupID INT,  
		EmployeeID INT, 
		ProviderID INT, 
		ProviderTypeID INT, 
		ProviderSpecialtyID INT, 
		ProviderLineItemID INT,  
		Value DECIMAL (19,4)  
	) 

	CREATE TABLE #IntStaffingData (
		DepartmentID INT,  
		JobCodeID INT,  
		PayCodeGroupID INT,  
		EmployeeID INT, 
		ProviderID INT, 
		ProviderTypeID INT, 
		ProviderSpecialtyID INT, 
		ProviderLineItemID INT,   
		BudgetDollarTotal DECIMAL (19,4)  
	)

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	CREATE TABLE #departmentsConfiguredToFlex (DepartmentID int)
	CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT)
	CREATE TABLE #flexConfigMapping(DepartmentID INT, PRJobCodeID INT, StatAccountID INT, ProviderLineItemID INT, SourceDepartmentID INT)
	CREATE TABLE #staffingConfiguredToFlex(DepartmentID INT, PRJobCodeID INT, ProviderLineItemID INT)
	CREATE TABLE #uniqueStatMapping(DepartmentID INT, StatAccountID INT, ProviderLineItemID INT, SourceDepartmentID INT)
	CREATE TABLE #statsBudget (DepartmentID INT, ProviderLineItemID INT, ProviderID INT, StatTotal INT)
	
	DECLARE @IsAnnualized BIT = (CASE WHEN @StaffingFiscalYearID = @CurrentFiscalYearID AND @StaffingTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)
	DECLARE @ProviderSubsection INT = 4

	-- Convert source dim to temp table for performance
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- Build out #FilterByDepartment if targeting is empty
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT d.DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED) 
		WHERE d.BudgetConfigID = @BudgetConfigID
			AND d.SubsectionID = @ProviderSubSection
			AND d.FlexingTypeID = 9
	END
		
	-- Load mapping from flex config mapping table. FlexingType is 9 for Provider By Stats
	INSERT INTO #flexConfigMapping (DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID)
	SELECT DISTINCT mapping.DepartmentID, mapping.PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID
	FROM [fp].[FlexConfigMapping] mapping
		INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = mapping.DepartmentID
	WHERE mapping.FlexingTypeID = 9
		AND mapping.EntityGroupConfigID = @EntityGroupConfigID
		
	-- Build a temp table to quickly get just the departments that are being flexed
	INSERT INTO #departmentsConfiguredToFlex
	SELECT DISTINCT mapping.DepartmentID 
	FROM #flexConfigMapping mapping

	-- Get all of the department/jobcode/providerLineItem Combinations
	INSERT INTO #staffingConfiguredToFlex
	SELECT DISTINCT mapping.DepartmentID, mapping.PRJobCodeID, mapping.ProviderLineItemID
	FROM #flexConfigMapping mapping

	-------------------------------------
	-- Get statistic data
	-------------------------------------
	INSERT INTO #uniqueStatMapping (DepartmentID, StatAccountID, ProviderLineItemID, SourceDepartmentID)
	SELECT DISTINCT mapping.DepartmentID, StatAccountID, ProviderLineItemID, SourceDepartmentID
	FROM #flexConfigMapping mapping

	DECLARE @UsePriorYear BIT = 0;
	DECLARE @UseActualYTD BIT = 0;
	DECLARE @UseCurrentYearBudget BIT = 0;
	
	IF @StaffingTimeClassID = 2 BEGIN
		SET @UseCurrentYearBudget = 1;
	END ELSE BEGIN
		IF @CurrentFiscalYearID = @StaffingFiscalYearID BEGIN
			SET @UseActualYTD = 1;
		END ELSE BEGIN
			SET @UsePriorYear = 1
			END
	END		
	
	INSERT INTO #statsBudget (DepartmentID, ProviderLineItemID, ProviderID, StatTotal)
	SELECT 
		map.DepartmentID,
		map.ProviderLineItemID,   -- this is the ProviderLineItemID for staffing flexing (not stats) - we will use this later to flex staffing
		stat.ProviderID,
		CASE 
			WHEN @UseActualYTD = 1 THEN ISNULL(SUM(statHist.ActualYTDValueTotal), 0)
			WHEN @UseCurrentYearBudget = 1 THEN ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0)
			WHEN @UsePriorYear = 1 THEN ISNULL(SUM(statHist.PriorYearActualValueTotal), 0)
		END AS StatTotal
	FROM #uniqueStatMapping map
		LEFT JOIN fp.[FactStatistics] stat ON stat.DepartmentID = map.SourceDepartmentID AND stat.AccountID = map.StatAccountID
		LEFT JOIN fp.[FactStatisticsHistory] statHist ON stat.StatisticsID = statHist.StatisticsID
	WHERE stat.BudgetConfigID = @BudgetConfigID -- We need the entire budget, not just EGC because stats can be cross EGC for X Department flexing
	GROUP BY
		map.DepartmentID, 
		map.ProviderLineItemID, 
		stat.ProviderID

	-------------------------------------
	-- Get staffing data
	-------------------------------------

	DECLARE @ProviderSubsectionID INT = 4;

	DECLARE @UseProviderSource BIT;
	DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT;

	SELECT @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

	SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID

	IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
	IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept

	CREATE TABLE #emp (EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT)
	CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)
	
	DECLARE @IsProviderTypeDisabled BIT;
	SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
								INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
							WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubsectionID = 1
								)
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	
	DECLARE @IsProviderSpecialtyDisabled BIT;
	SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
								)
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	-- NOTE: THIS SHOULD MATCH WHAT IS PULLED FROM STAFFING DOLLARS SAMPLING TO GET THE DOLLARS. THIS IS BECAUSE
	-- WE CAN GET DOLLARS FROM MULTIPLE PLACES AND NEED TO MAKE SURE WE'RE GRABBING EVERYTHING CORRECTLY.

	-- Get all departments that use Provider Staffing
	-- Get all employees that are providers
	-- (not doing this step for anything other than dollars yet) Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling
	-- Sample regular data for non provider employees and departments that are not configured to use provider sampling
		
	IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
	BEGIN
		-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
		INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
		SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
		FROM [fp].[DepartmentLevelConfiguration] config 
			INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
			INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
			INNER JOIN #FilterByDepartment ft on ft.DepartmentID = staff.DepartmentID
			INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE 
			staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID 
			AND staff.IsDeleted = 0
			AND staff.FiscalMonthID != 0
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND config.BudgetConfigID = @BudgetConfigID
			AND config.IsUsingProviderStaffing = 1
			AND staff.UnitTypeID = 34
		UNION
		SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
		FROM [fp].[DepartmentLevelConfiguration] config  
			INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
			INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID
			INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
			INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE 			 
			prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND config.BudgetConfigID = @BudgetConfigID
			AND config.IsUsingProviderStaffing = 1
			AND prov.UnitTypeID = 34

		-- 2. all employees that are providers
		INSERT INTO #emp (EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID)
		SELECT DISTINCT 
			emp.EmployeeID, 
			phys.PhysicianID,
			CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
			CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID
		FROM [fp].[DepartmentLevelConfiguration] config  
			INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
			INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
			INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
			INNER JOIN [dss].[DimPhysician]	phys ON emp.NPI = phys.NPI
			INNER JOIN #FilterByDepartment tmp on staff.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
			INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
			INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
			INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE 
			staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID 
			AND staff.IsDeleted = 0
			AND staff.FiscalMonthID != 0			
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND config.BudgetConfigID = @BudgetConfigID
			AND config.IsUsingProviderStaffing = 1
			AND ps.Description = 'Staffing'
			AND staff.EmployeeID > 0
			AND staff.UnitTypeID = 34
			AND emp.NPI NOT IN ('Not Specified', '0', '')	
		UNION		
		SELECT DISTINCT 
			phys.EmployeeID, 
			phys.PhysicianID, 
			CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
			CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID
		FROM [fp].[DepartmentLevelConfiguration] config  
			INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
			INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID
			INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
			LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
			INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
			INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
			INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE
			prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND config.BudgetConfigID = @BudgetConfigID
			AND config.IsUsingProviderStaffing = 1
			AND ps.Description = 'Staffing'
			AND prov.UnitTypeID = 34
			AND phys.NPI NOT IN ('Not Specified', '0', '')
	  
		-- Provider from int.FactProvider
		INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
			ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value)   
		SELECT
			DISTINCT
			fp.DepartmentID, 
			0 as JobCodeID,  
			0 as PayCodeGroupID,  
			0 as EmployeeID,
			emp.ProviderID,
			emp.ProviderTypeID,
			emp.ProviderSpecialtyID,
			fp.ProviderLineItemID, 
			SUM(ISNULL(fp.Value, 0)) as Value
		FROM
			[int].[FactProvider] fp
			INNER JOIN #staffingConfiguredToFlex fcm ON fp.DepartmentID = fcm.DepartmentID AND fp.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex
			INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
			INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
			INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
			INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID        	
		WHERE 
			fp.FiscalYearID = @StaffingFiscalYearID 
			AND fp.TimeclassID = @StaffingTimeClassID 
			AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
			AND fp.IsDeleted = 0 
			AND fp.FiscalMonthID != 0 
			AND fp.UnitTypeID = 34   
			AND ps.Description = 'Staffing'
		GROUP BY fp.DepartmentID, emp.EmployeeID,
			emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

		INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData
		
		-- Provider from int.FactStaffing
		INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
			ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value)   
		SELECT
			DISTINCT
			src.DepartmentID, 
			src.JobCodeID,  
			pcg.PayCodeGroupID,  
			0 as EmployeeID,
			emp.ProviderID,
			emp.ProviderTypeID,
			emp.ProviderSpecialtyID,
			pc.ProviderLineItemID,
			SUM(ISNULL(src.Value, 0)) as Value
		FROM
			[int].[FactStaffing] src
			INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
			INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
			INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
			INNER JOIN #staffingConfiguredToFlex fcm ON src.DepartmentID = fcm.DepartmentID AND pc.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex
			INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
			INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
			INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		       	
			LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID
		WHERE 
			src.FiscalYearID = @StaffingFiscalYearID 
			AND src.TimeclassID = @StaffingTimeClassID 
			AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 34        
			AND pc.IsDollarsIgnored = 0 
			AND ps.Description = 'Staffing'
			AND pd.DepartmentID IS NULL
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			pcg.PayCodeGroupID,
			emp.EmployeeID,
			emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

	END ELSE BEGIN
		IF @UseProviderSource = 0
		BEGIN

			-------------------------------------------------------
			-- BudgetConfig UseProviderSource is disabled
			-------------------------------------------------------

			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config 
				INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN #FilterByDepartment ft on ft.DepartmentID = staff.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 
				staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND staff.UnitTypeID = 34

			INSERT INTO #emp (EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID)
			SELECT DISTINCT 
				emp.EmployeeID, 
				phys.PhysicianID,
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician]	phys ON emp.NPI = phys.NPI
				INNER JOIN #FilterByDepartment tmp on staff.DepartmentID = tmp.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 
				staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0			
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND staff.UnitTypeID = 34
				AND emp.NPI NOT IN ('Not Specified', '0', '')	

			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
				ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value)   
			SELECT
				DISTINCT
				src.DepartmentID, 
				src.JobCodeID,  
				pcg.PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				SUM(ISNULL(src.Value, 0)) as Value
			FROM
				[int].[FactStaffing] src
				INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
				INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
				INNER JOIN #staffingConfiguredToFlex fcm ON src.DepartmentID = fcm.DepartmentID AND pc.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
			WHERE 
				src.FiscalYearID = @StaffingFiscalYearID 
				AND src.TimeclassID = @StaffingTimeClassID 
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
				AND src.IsDeleted = 0 
				AND src.FiscalMonthID != 0 
				AND src.UnitTypeID = 34        
				AND pc.IsDollarsIgnored = 0 
				AND ps.Description = 'Staffing'
			GROUP BY src.DepartmentID,   
				src.JobCodeID,   
				pcg.PayCodeGroupID,
				emp.EmployeeID,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

		END ELSE BEGIN
			
			-------------------------------------------------------
			-- BudgetConfig UseProviderSource is enabled
			-------------------------------------------------------

			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
				INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND prov.UnitTypeID = 34

			-- 2. all employees that are providers
			INSERT INTO #emp (EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID)
			SELECT DISTINCT 
				phys.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID
				INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND prov.UnitTypeID = 34
				AND phys.NPI NOT IN ('Not Specified', '0', '')
	  
			-- Provider from int.FactProvider
			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
				ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value)   
			SELECT
				DISTINCT
				fp.DepartmentID, 
				0 as JobCodeID,  
				0 as PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fp.ProviderLineItemID, 
				SUM(ISNULL(fp.Value, 0)) as Value
			FROM
				[int].[FactProvider] fp
				INNER JOIN #staffingConfiguredToFlex fcm ON fp.DepartmentID = fcm.DepartmentID AND fp.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex
				INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID        	
			WHERE 
				fp.FiscalYearID = @StaffingFiscalYearID 
				AND fp.TimeclassID = @StaffingTimeClassID 
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
				AND fp.IsDeleted = 0 
				AND fp.FiscalMonthID != 0 
				AND fp.UnitTypeID = 34   
				AND ps.Description = 'Staffing'
			GROUP BY fp.DepartmentID, emp.EmployeeID,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID
		END
	END
	-- Get any of the variable dollars, we don't care about fixed dollars for this. This should already be filtered to Variable based on the join with
	-- flex config mapping.
	INSERT INTO #IntStaffingData    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, 
		CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID,
		ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SUM(ISNULL(Value, 0)) AS BudgetDollarTotal   
	FROM #TempIntStaffingData     
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, ProviderID, 
		ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID,  
		CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END          
	
	IF @IsDebug = 1 
	BEGIN
		
		SELECT @UsePriorYear AS '@UsePriorYear', @UseActualYTD AS '@UseActualYTD', @UseCurrentYearBudget AS '@UseCurrentYearBudget'
		SELECT '#FilterByDepartment', * FROM #FilterByDepartment
		SELECT '#flexConfigMapping', * FROM #flexConfigMapping
		SELECT '#staffingConfiguredToFlex', * FROM #staffingConfiguredToFlex
		SELECT '#departmentsConfiguredToFlex', * FROM #departmentsConfiguredToFlex
		SELECT '#uniqueStatMapping', * FROM #uniqueStatMapping
		SELECT '#statsBudget', * FROM #statsBudget
		SELECT '#dept', * FROM #dept
		SELECT '#emp', * FROM #emp
		SELECT '#provDims', * FROM #provDims
		SELECT '#TempIntStaffingData', * FROM #TempIntStaffingData
		SELECT '#IntStaffingData', * FROM #IntStaffingData

		SELECT staffing.DepartmentID, staffing.JobCodeID, staffing.PayCodeGroupID, staffing.ProviderID,
			staffing.ProviderTypeID, staffing.ProviderSpecialtyID, staffing.ProviderLineItemID, staffing.EmployeeID, 
			COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) AS Calculation,
			staffing.BudgetDollarTotal AS BudgetDollarTotal,
			stat.StatTotal AS StatTotal
		FROM [fp].[Staffing] fs
			INNER JOIN #IntStaffingData staffing ON 
				staffing.DepartmentID = fs.DepartmentID
				AND staffing.JobCodeID = fs.JobCodeID
				AND staffing.PayCodeGroupID = FS.PayCodeGroupID
				AND staffing.ProviderID = fs.ProviderID
				AND staffing.ProviderTypeID = fs.ProviderTypeID
				AND staffing.ProviderSpecialtyID = fs.ProviderSpecialtyID
				AND staffing.ProviderLineItemID = fs.ProviderLineItemID
				AND staffing.EmployeeID = fs.EmployeeID
			INNER JOIN #statsBudget stat
				ON stat.DepartmentID = fs.DepartmentID
				AND stat.ProviderID = fs.ProviderID
				AND stat.ProviderLineItemID = fs.ProviderLineItemID
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID

	END ELSE BEGIN

		-- set the Dollars/UOS values on Staffing table
		UPDATE
			fs
		SET
			InitialBudgetRate01 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate02 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate03 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate04 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate05 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate06 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate07 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate08 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate09 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate10 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate11 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate12 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			
		
			-- Projection rates should match the budget rates and use the budget baseline to calculate
			InitialProjectionRate01 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate02 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate03 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate04 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate05 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate06 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate07 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate08 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate09 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate10 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate11 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate12 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0)
		FROM [fp].[Staffing] fs
			INNER JOIN #IntStaffingData staffing ON 
				staffing.DepartmentID = fs.DepartmentID
				AND staffing.JobCodeID = fs.JobCodeID
				AND staffing.PayCodeGroupID = FS.PayCodeGroupID
				AND staffing.ProviderID = fs.ProviderID
				AND staffing.ProviderTypeID = fs.ProviderTypeID
				AND staffing.ProviderSpecialtyID = fs.ProviderSpecialtyID
				AND staffing.ProviderLineItemID = fs.ProviderLineItemID
				AND staffing.EmployeeID = fs.EmployeeID
			INNER JOIN #statsBudget stat
				ON stat.DepartmentID = fs.DepartmentID
				AND stat.ProviderID = fs.ProviderID
				AND stat.ProviderLineItemID = fs.ProviderLineItemID
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID
			AND (
					
					fs.InitialBudgetRate01 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate02 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate03 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate04 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate05 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate06 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate07 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate08 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate09 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate10 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate11 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate12 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR
					fs.InitialProjectionRate01 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate02 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate03 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate04 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate05 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate06 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate07 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate08 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate09 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate10 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate11 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate12 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0))

	END
	
END
GO


---------------------------------------------

-- fp.procSampleStaffingFTE
CREATE PROCEDURE [fp].[procSampleStaffingFTE]  
 @EntityGroupConfigID int,  
 @FiscalYearID int,  
 @ProjectionFiscalYearID int,
 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE   
AS  
BEGIN  
/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1    2023-02-16  BK      JAZZ-50052  Update to copy SampledProjecton to InitialProjection for MonthsNotLoaded when baseline is Current Year Budget
	**                                      instead of getting average of MonthsNotLoaded dollars and hours and flattening the wage rate
    ** 2    2023-09-20  BK      JAZZ-60973  Update for new data structure
	*************************************************************/ 

 
CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	
 IF OBJECT_ID('tempdb..#StaffFteTotal') IS NOT NULL DROP TABLE #StaffFteTotal  
   
 DECLARE @MonthsLoaded INT, @StaffingTimeClassID INT, @StaffingFiscalYearID INT;
 
 SELECT @MonthsLoaded = MonthsLoaded, @StaffingTimeClassID = PayrollTimeClassID, @StaffingFiscalYearID = PayrollFiscalYearID 
 FROM fp.EntityGroupConfig egc  
 INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID  
 WHERE EntityGroupConfigID = @EntityGroupConfigID  
  
   
  UPDATE fte SET 
          fte.SampledBudgetFTEs01 = fte.SampledBudgetHours01 / wh.Month01  
        , fte.SampledBudgetFTEs02 = fte.SampledBudgetHours02 / wh.Month02  
        , fte.SampledBudgetFTEs03 = fte.SampledBudgetHours03 / wh.Month03  
        , fte.SampledBudgetFTEs04 = fte.SampledBudgetHours04 / wh.Month04  
        , fte.SampledBudgetFTEs05 = fte.SampledBudgetHours05 / wh.Month05  
        , fte.SampledBudgetFTEs06 = fte.SampledBudgetHours06 / wh.Month06  
        , fte.SampledBudgetFTEs07 = fte.SampledBudgetHours07 / wh.Month07  
        , fte.SampledBudgetFTEs08 = fte.SampledBudgetHours08 / wh.Month08  
        , fte.SampledBudgetFTEs09 = fte.SampledBudgetHours09 / wh.Month09  
        , fte.SampledBudgetFTEs10 = fte.SampledBudgetHours10 / wh.Month10  
        , fte.SampledBudgetFTEs11 = fte.SampledBudgetHours11 / wh.Month11  
        , fte.SampledBudgetFTEs12 = fte.SampledBudgetHours12 / wh.Month12    
          
        , fte.InitialBudgetFTEs01 = fte.InitialBudgetHours01 / wh.Month01  
        , fte.InitialBudgetFTEs02 = fte.InitialBudgetHours02 / wh.Month02  
        , fte.InitialBudgetFTEs03 = fte.InitialBudgetHours03 / wh.Month03  
        , fte.InitialBudgetFTEs04 = fte.InitialBudgetHours04 / wh.Month04  
        , fte.InitialBudgetFTEs05 = fte.InitialBudgetHours05 / wh.Month05  
        , fte.InitialBudgetFTEs06 = fte.InitialBudgetHours06 / wh.Month06  
        , fte.InitialBudgetFTEs07 = fte.InitialBudgetHours07 / wh.Month07  
        , fte.InitialBudgetFTEs08 = fte.InitialBudgetHours08 / wh.Month08  
        , fte.InitialBudgetFTEs09 = fte.InitialBudgetHours09 / wh.Month09  
        , fte.InitialBudgetFTEs10 = fte.InitialBudgetHours10 / wh.Month10  
        , fte.InitialBudgetFTEs11 = fte.InitialBudgetHours11 / wh.Month11  
        , fte.InitialBudgetFTEs12 = fte.InitialBudgetHours12 / wh.Month12          
        ---  
        , fte.SampledProjectionFTEs01 = fte.SampledProjectionHours01 / pwh.Month01  
        , fte.SampledProjectionFTEs02 = fte.SampledProjectionHours02 / pwh.Month02  
        , fte.SampledProjectionFTEs03 = fte.SampledProjectionHours03 / pwh.Month03  
        , fte.SampledProjectionFTEs04 = fte.SampledProjectionHours04 / pwh.Month04  
        , fte.SampledProjectionFTEs05 = fte.SampledProjectionHours05 / pwh.Month05  
        , fte.SampledProjectionFTEs06 = fte.SampledProjectionHours06 / pwh.Month06  
        , fte.SampledProjectionFTEs07 = fte.SampledProjectionHours07 / pwh.Month07  
        , fte.SampledProjectionFTEs08 = fte.SampledProjectionHours08 / pwh.Month08  
        , fte.SampledProjectionFTEs09 = fte.SampledProjectionHours09 / pwh.Month09  
        , fte.SampledProjectionFTEs10 = fte.SampledProjectionHours10 / pwh.Month10  
        , fte.SampledProjectionFTEs11 = fte.SampledProjectionHours11 / pwh.Month11  
        , fte.SampledProjectionFTEs12 = fte.SampledProjectionHours12 / pwh.Month12  
  
        FROM [fp].[Staffing] fte  
		  INNER JOIN #filterTable tmp on fte.DepartmentID = tmp.DepartmentID
           LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fte.PayCodeGroupID = exc.PayCodeGroupID  
          INNER JOIN [fw].[DimJobCode] jc on fte.JobCodeID = jc.JobCodeID  
          INNER JOIN [fw].[DimDepartment] dept on fte.DepartmentID = dept.DepartmentID  
          INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)  
          INNER JOIN [client].[FactWorkingHoursPerMonth] pwh on pwh.FiscalYearID = @ProjectionFiscalYearID and pwh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)  
        WHERE fte.EntityGroupConfigID = @EntityGroupConfigID AND exc.PayCodeGroupID IS NULL  
       
     
     IF @StaffingTimeClassID = 2 AND @StaffingFiscalYearID = @ProjectionFiscalYearID BEGIN
     	-- Current Year Budget only
		UPDATE fs    
		SET    
			InitialProjectionFTEs01 = fs.SampledProjectionFTEs01,    
			InitialProjectionFTEs02 = fs.SampledProjectionFTEs02,
			InitialProjectionFTEs03 = fs.SampledProjectionFTEs03,
			InitialProjectionFTEs04 = fs.SampledProjectionFTEs04,
			InitialProjectionFTEs05 = fs.SampledProjectionFTEs05,
			InitialProjectionFTEs06 = fs.SampledProjectionFTEs06,
			InitialProjectionFTEs07 = fs.SampledProjectionFTEs07,
			InitialProjectionFTEs08 = fs.SampledProjectionFTEs08,
			InitialProjectionFTEs09 = fs.SampledProjectionFTEs09,
			InitialProjectionFTEs10 = fs.SampledProjectionFTEs10,
			InitialProjectionFTEs11 = fs.SampledProjectionFTEs11,
			InitialProjectionFTEs12 = fs.SampledProjectionFTEs12
	   FROM [fp].[Staffing] fs 
			INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID 
		WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID
		
     END ELSE BEGIN
     
	 	CREATE TABLE #StaffFteTotal (StaffingID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)) 
	 	
	    INSERT INTO #StaffFteTotal (StaffingID, SampledProjectionTotal)  
	    SELECT fs.StaffingID,   
	    CASE WHEN @MonthsLoaded = 11 THEN fs.SampledProjectionFTEs12    
	    WHEN @MonthsLoaded = 10 THEN fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12  
	    WHEN @MonthsLoaded = 9 THEN fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12  
	    WHEN @MonthsLoaded = 8 THEN fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12  
	    WHEN @MonthsLoaded = 7 THEN fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12  
	    WHEN @MonthsLoaded = 6 THEN fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12  
	    WHEN @MonthsLoaded = 5 THEN fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12  
	    WHEN @MonthsLoaded = 4 THEN fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12  
	    WHEN @MonthsLoaded = 3 THEN fs.SampledProjectionFTEs04 + fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10  + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12
	  
	    WHEN @MonthsLoaded = 2 THEN fs.SampledProjectionFTEs03 + fs.SampledProjectionFTEs04 + fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 
			+ fs.SampledProjectionFTEs12  
			    WHEN @MonthsLoaded = 1 THEN fs.SampledProjectionFTEs02 + fs.SampledProjectionFTEs03 + fs.SampledProjectionFTEs04 + fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 
			+ fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12    
			     ELSE 0  
			  END    
		 FROM [fp].[Staffing] fs  
		 INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		 LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID  
		 WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND exc.PayCodeGroupID IS NULL  
			         
	          
	    UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded)  
	        FROM #StaffFteTotal a  
	   
	   -- update the initial projection values   
		 UPDATE  
		  fs  
		 SET  
		  InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1  THEN SampledProjectionFTEs01 ELSE NewValue END,  
		  InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2  THEN SampledProjectionFTEs02 ELSE NewValue END,  
		  InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3  THEN SampledProjectionFTEs03 ELSE NewValue END,  
		  InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4  THEN SampledProjectionFTEs04 ELSE NewValue END,  
		  InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5  THEN SampledProjectionFTEs05 ELSE NewValue END,  
		  InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6  THEN SampledProjectionFTEs06 ELSE NewValue END,  
		  InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7  THEN SampledProjectionFTEs07 ELSE NewValue END,  
		  InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8  THEN SampledProjectionFTEs08 ELSE NewValue END,  
		  InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9  THEN SampledProjectionFTEs09 ELSE NewValue END,  
		  InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN SampledProjectionFTEs10 ELSE NewValue END,  
		  InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN SampledProjectionFTEs11 ELSE NewValue END,  
		  InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN SampledProjectionFTEs12 ELSE NewValue END  
		 FROM [fp].[Staffing] fs  
		 INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		 INNER JOIN #StaffFteTotal IPA ON IPA.StaffingID = fs.StaffingID  
		 WHERE fs.EntityGroupConfigID = @EntityGroupConfigID  
	END 
	           
END
GO


---------------------------------------------

-- fp.procSampleStaffingHistoricalData
CREATE   PROCEDURE [fp].[procSampleStaffingHistoricalData]        
	@EntityGroupConfigGUID uniqueidentifier,          
	@EntityGroupConfigID int,       
	@CurrentFiscalYearID smallint,          
	@MonthsLoaded int,
	@IsEmployeeBudgeting bit,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS          
BEGIN   
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author   WI   	     Description
** 4   2021-03-22  NT        JAZZ-15374  Use NPI instead of EmployeID for Provider Comp Sampling
** 5   2021-06-30  BW        JAZZ-21627  Update selects and group by for EmployeID for variablity
** 6   2021-12-01  OP        JAZZ-29466  removed empty users check for prov comp data
** 7   2022-01-12  OP        JAZZ-30834  sample provider data
** 8   2022-02-09  BK        JAZZ-33248  respect department setting for employee budgeting
** 9   2022-03-02  MZ        JAZZ-30547  improved checks in order to sample valid Employees with valid NPI
** 10  2022-03-18  AO        JAZZ-33623  hours always sample fixed
** 11  2022-06-30  MY        JAZZ-39047	 Added Option Recompile
** 12  2022-08-08  BK        JAZZ-38357	 make sure IsFP records are sampled to correct Subsection
** 13  2022-09-13  MZ        JAZZ-41652  Restricted Prov Comp Wage Rate sampling
** 14  2022-10-07  AO        JAZZ-42868  Non-provider department samples correct Actual YTD staffing values when provider sampling feature is turned on.
** 15  2022-11-07  MZ        JAZZ-35344  improved checks in order to sample valid Employees with valid NPI from FactProvider
** 16  2022-11-07  MY        JAZZ-35951	 Add EmployeeID to FactStaffingVariabilityDetail
** 17  2022-12-12  DM        JAZZ-46455  Samplimg of Provider Type and Provider Specialty is linked to Section Setup
** 18  2023-04-11  MZ        JAZZ-53130  Used NPI for PY Actuals and CY Budget instead of EmployeeID as a join to DimPhysician
** 19  2023-09-26  BK        JAZZ-61239  Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing
** 20  2023-09-30  BK        JAZZ-60973  Update for new data structure
** 21  2023-12-07  NT        JAZZ-64522  Fix column CurrentBudgetFTE column names
** 22  2023-12-26  NH/NT     JAZZ-64324  Remove 'Use Hours and FTE on Provider Compensation' (doing this in restructure branch on behalf of Softserve)
** 23  2024-01-31  NH        JAZZ-64064  Move Provider Planning FF as a setting in Plan Config
** 24  2024-03-25  MY        JAZZ-69661		Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
** 25  2024-06-19  AO        JAZZ-72231  Added Source Provider Sampling
*************************************************************/

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
          
	INSERT INTO [fp].[StaffingHistory] ([StaffingID])          
	SELECT [fs].[StaffingID]          
	FROM [fp].[Staffing] fs          
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0          
      
	IF OBJECT_ID('tempdb..#IntStaffingDataRolledUp') IS NOT NULL DROP TABLE #IntStaffingDataRolledUp      
	IF OBJECT_ID('tempdb..#IntStaffingDataRolledUpRaw') IS NOT NULL DROP TABLE #IntStaffingDataRolledUpRaw  
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved  
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals 
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget 
    
	CREATE TABLE #IntStaffingDataRolledUpRaw (      
		DepartmentID int,      
		JobCodeID int,      
		PayCodeGroupID int,      
		EmployeeID int,      
		UnitTypeID int, 
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,      
		MonthColumnName varchar(50),      
		FixedPercentage decimal(38,6),      
		Value decimal (19,4)      
	)      
    
	CREATE TABLE #IntStaffingDataRolledUp (      
		DepartmentID int,      
		JobCodeID int,      
		PayCodeGroupID int,      
		EmployeeID int,      
		UnitTypeID int,   
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,    
		MonthColumnName varchar(50),      
		FixedPercentage decimal(38,6),    
		Value decimal (19,4)      
	)  

	IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
	IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept
	IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims

	CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT)
	CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)
	CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT)

	DECLARE @StaffingSubsectionID INT = 3;
	DECLARE @ProviderSubsectionID INT = 4;

	DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID)    

	DECLARE @IsProviderPlanningEnabled BIT;
	DECLARE @UseProviderSource BIT;
	DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT;

	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

	SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID

	DECLARE @IsProviderTypeDisabled BIT;
	SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	
	DECLARE @IsProviderSpecialtyDisabled BIT;
	SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	-- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
	DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 
						   FROM fp.BudgetConfigSetting setting 
						      INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
						   WHERE def.Name = 'Enable Department Level Provider For Sampling'
			  				  AND setting.BudgetConfigID = @BudgetConfigID
							  AND setting.Value = 1), 0)

	IF @IsProviderPlanningEnabled = 0 
	BEGIN    

		----------------------------------------------------
		-- Provider is disabled
		----------------------------------------------------
	
		-- Resolve EmployeeID up front so we don't have to do it every time.
		SELECT
			src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeID,
			pc.PayCodeGroupID,
			pc.IsDollarsIgnored,
			pc.IsHoursIgnored,
			CASE
			WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
			END as EmployeeID,
			0 AS ProviderID, 
			0 AS ProviderTypeID, 
			0 AS ProviderSpecialtyID, 
			0 AS ProviderLineItemID,
			src.FiscalYearID,
			src.TimeClassID,
			src.UnitTypeID,
			src.FiscalMonthID,
			fm.MonthColumnName,
			fm.SortOrder,
			src.IsDeleted,
			Value
		INTO #intFactStaffingWithEmployeeResolved
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID        
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID      
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0.
					    WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID 
		WHERE 1 = 1
			AND (	-- Need all 3 for the different time class/years we sample in. This is used more than just the following statement
					(src.FiscalYearID = @CurrentFiscalYearID AND src.TimeClassID = 1) OR
					(src.FiscalYearID = @CurrentFiscalYearID - 1 AND src.TimeClassID = 1) OR
					(src.FiscalYearID = @CurrentFiscalYearID AND src.TimeClassID = 2)
				)
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0

		INSERT INTO #IntStaffingDataRolledUpRaw  
			(DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		     
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,       
			hist.PayCodeGroupID,       
			hist.EmployeeID,
			hist.UnitTypeID,  
			0 as ProviderID, 
			0 as ProviderTypeID, 
			0 as ProviderSpecialtyID, 
			0 as ProviderLineItemID, 
			3 as SubsectionID,     
			hist.MonthColumnName,   
			ISNULL(fv.FixedPercentage,1) as FixedPercentage,
			SUM(ISNULL(hist.Value, 0)) as Value  
		FROM #intFactStaffingWithEmployeeResolved hist           
		INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
		LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
			AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID			
		LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv ON fv.DepartmentID = hist.DepartmentID 
			AND fv.JobCodeID = hist.JobCodeID 
			AND fv.PayCodeID = hist.PayCodeID    
			AND fv.EmployeeID = hist.EmployeeID   
			AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID 
		WHERE hist.FiscalYearID = @CurrentFiscalYearID 
			AND hist.TimeClassID = 1 
			AND hist.SortOrder <= @MonthsLoaded   
			AND ((hist.UnitTypeID = 34 AND hist.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND hist.IsHoursIgnored = 0)) 
		GROUP BY hist.DepartmentID,   
			hist.JobCodeID,   
			hist.PayCodeGroupID,
			hist.EmployeeID,
			hist.UnitTypeID,  
			hist.MonthColumnName,
			FixedPercentage  
	END ELSE 
	BEGIN
	
		----------------------------------------------------
		-- Provider is enabled
		----------------------------------------------------
		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN
			
			-------------------------------------------------------
			-- BudgetConfigSetting is disabled
			-------------------------------------------------------

			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0  AND fm.SortOrder <= @MonthsLoaded				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
				emp.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')
			UNION		
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
				phys.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
				INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')
				AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
			
			-- Provider from int.FactProvider
			INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
			SELECT
				DISTINCT
				fp.DepartmentID, 
				0 as JobCodeID,  
				0 as PayCodeGroupID, 
				0 as EmployeeID,
				fp.UnitTypeID, 
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fp.ProviderLineItemID,
				@ProviderSubsectionID, 
				fm.MonthColumnName,     
				1 as FixedPercentage,
				CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value
			FROM
				[int].[FactProvider] fp
				INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
			WHERE 
				fp.FiscalYearID = @CurrentFiscalYearID 
				AND fp.TimeClassID = 1 
				AND fp.IsDeleted = 0 
				AND fp.FiscalMonthID != 0 
				AND fm.SortOrder <= @MonthsLoaded         
				AND ps.Description = 'Staffing'
				AND emp.IsFP = 1
				AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
			GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID
				
			INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #IntStaffingDataRolledUpRaw

			-- Provider from int.FactStaffing
			INSERT INTO #IntStaffingDataRolledUpRaw  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
			SELECT       
				hist.DepartmentID,       
				hist.JobCodeID,       
				pc.PayCodeGroupID,    
				0 as EmployeeID,  
				hist.UnitTypeID,  
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				@ProviderSubsectionID,   
				fm.MonthColumnName,   
				CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage,
				CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value
			FROM [int].[FactStaffing] hist           
				INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
				INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
				INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID  
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID	
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
					AND fv.JobCodeID = hist.JobCodeID 
					AND fv.PayCodeID = hist.PayCodeID 
					AND fv.EmployeeID = 0
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          
				LEFT JOIN #provDims pd ON hist.DepartmentID = pd.DepartmentID 
					AND emp.ProviderID = pd.ProviderID 
					AND pd.ProviderLineItemID = pli.ProviderLineItemID
			WHERE hist.FiscalYearID = @CurrentFiscalYearID AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded   
				AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))         
				AND emp.IsFP = 1
			GROUP BY hist.DepartmentID,   
				hist.JobCodeID,   
				pc.PayCodeGroupID,
				emp.EmployeeID,
				hist.UnitTypeID,  
				fm.MonthColumnName,
				FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

		END ELSE BEGIN
			
			-------------------------------------------------------
			-- BudgetConfigSetting is enabled
			-------------------------------------------------------
			IF @UseProviderSource = 0
			BEGIN

				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is disabled
				-------------------------------------------------------

				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0  AND fm.SortOrder <= @MonthsLoaded				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

				-- 2. all employees from staffing
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
					emp.EmployeeID, 
					phys.PhysicianID, 
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
					INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
					INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND staff.EmployeeID > 0
					AND emp.NPI NOT IN ('Not Specified', '0', '')

				INSERT INTO #IntStaffingDataRolledUpRaw  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
				SELECT       
					hist.DepartmentID,       
					hist.JobCodeID,       
					pc.PayCodeGroupID,    
					0 as EmployeeID,  
					hist.UnitTypeID,  
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					pc.ProviderLineItemID,
					@ProviderSubsectionID,   
					fm.MonthColumnName,   
					CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage,
					CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value
				FROM [int].[FactStaffing] hist           
					INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
					INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
					INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID  
					INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID	
					LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
						AND fv.JobCodeID = hist.JobCodeID 
						AND fv.PayCodeID = hist.PayCodeID 
						AND fv.EmployeeID = 0
						AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          
				WHERE hist.FiscalYearID = @CurrentFiscalYearID AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded   
					AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))         
					AND emp.IsFP = 1
				GROUP BY hist.DepartmentID,   
					hist.JobCodeID,   
					pc.PayCodeGroupID,
					emp.EmployeeID,
					hist.UnitTypeID,  
					fm.MonthColumnName,
					FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

			END ELSE BEGIN

				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is enabled
				-------------------------------------------------------

				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

				-- 2. all employees that are providers
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
					phys.EmployeeID, 
					phys.PhysicianID, 
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
					INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded 					
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND phys.NPI NOT IN ('Not Specified', '0', '')
					AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

				-- Provider from int.FactProvider
				INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
				SELECT
					DISTINCT
					fp.DepartmentID, 
					0 as JobCodeID,  
					0 as PayCodeGroupID, 
					0 as EmployeeID,
					fp.UnitTypeID, 
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					fp.ProviderLineItemID,
					@ProviderSubsectionID, 
					fm.MonthColumnName,     
					1 as FixedPercentage,
					CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value
				FROM
					[int].[FactProvider] fp
					INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
				WHERE 
					fp.FiscalYearID = @CurrentFiscalYearID 
					AND fp.TimeClassID = 1 
					AND fp.IsDeleted = 0 
					AND fp.FiscalMonthID != 0 
					AND fm.SortOrder <= @MonthsLoaded         
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
					AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
				GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID,
					emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID
				
			END
		END

		-- Non-Provider from int.FactStaffing
		-- Populate into a temp table before summing up to deal with issues with the dynamic employee join
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,     
			hist.PayCodeID,
			pc.PayCodeGroupID,       
			CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE hist.EmployeeID
				END
			END as EmployeeID,
			hist.UnitTypeID,    
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			@StaffingSubsectionID as SubsectionID,   
			fm.MonthColumnName,   
			ISNULL(fv.FixedPercentage, 1) as FixedPercentage,
			ISNULL(hist.Value, 0) as Value 
		INTO #intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals
		FROM [int].[FactStaffing] hist           
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
			LEFT JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON hist.EmployeeID = emp.EmployeeID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON hist.EmployeeID = NotFpEmp.EmployeeID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
			INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID        
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				AND fv.JobCodeID = hist.JobCodeID 
				AND fv.PayCodeID = hist.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE hist.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID     
		WHERE hist.FiscalYearID = @CurrentFiscalYearID 
			AND hist.TimeClassID = 1 
			AND hist.IsDeleted = 0 
			AND hist.FiscalMonthID != 0 
			AND fm.SortOrder <= @MonthsLoaded   
			AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))         
			AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0)))       
			
		-- Provider from int.FactStaffing
		INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		      
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,       
			hist.PayCodeGroupID,       
			hist.EmployeeID,
			hist.UnitTypeID,    
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			@StaffingSubsectionID as SubsectionID,   
			hist.MonthColumnName,   
			ISNULL(fv.FixedPercentage, 1) as FixedPercentage,
			SUM(ISNULL(hist.Value, 0)) as Value  
		FROM #intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals hist           
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID      
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				AND fv.JobCodeID = hist.JobCodeID 
				AND fv.PayCodeID = hist.PayCodeID 
				AND fv.EmployeeID = hist.EmployeeID      
		GROUP BY hist.DepartmentID,   
			hist.JobCodeID,   
			hist.PayCodeGroupID,
			hist.EmployeeID,
			hist.UnitTypeID,  
			hist.MonthColumnName,
			fv.FixedPercentage 
	END
	      	      
	INSERT INTO #IntStaffingDataRolledUp 
		 ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value      
	FROM #IntStaffingDataRolledUpRaw    
	WHERE FixedPercentage = 1       
       
	INSERT INTO #IntStaffingDataRolledUp      
		 ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID,
																UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0))      
	FROM #IntStaffingDataRolledUpRaw      
	WHERE FixedPercentage <> 1      
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, 
	CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END     
	          
	 -- set all of the values for current year actual/annualized          
	 UPDATE          
	  fsh          
	 SET          
	  ActualYTDHours01 = CASE          
		 WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)          
		  END,          
	  ActualYTDHours02 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)          
		  END,          
	  ActualYTDHours03 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)          
		  END,          
	  ActualYTDHours04 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)          
	 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)          
		  END,          
	  ActualYTDHours05 = CASE          
	   WHEN VariabilityID = 1          
	   THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)          
		  END,          
	  ActualYTDHours06 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)          
		  END,          
	  ActualYTDHours07 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)          
		  END,          
	  ActualYTDHours08 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)          
		  END,          
	  ActualYTDHours09 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)          
		  END,          
	  ActualYTDHours10 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)          
		  END,          
	  ActualYTDHours11 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)          
		  END,          
	  ActualYTDHours12 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)          
		  END          
	FROM [fp].[StaffingHistory] fsh          
		INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID        
		INNER JOIN           
		(SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data          
	  PIVOT          
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv          
	   ON fs.DepartmentID = pv.DepartmentID          
	   AND fs.JobCodeID = pv.JobCodeID          
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID          
	   AND fs.EmployeeID = pv.EmployeeID           
	   AND fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID          
	 WHERE          
	  fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 51      
	  
	UPDATE          
	  fsh          
	 SET          
	  ActualYTDDollars01 = CASE          
		 WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)          
		  END,          
	  ActualYTDDollars02 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)          
		  END,          
	  ActualYTDDollars03 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)          
		  END,          
	  ActualYTDDollars04 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)          
	 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)          
		  END,          
	  ActualYTDDollars05 = CASE          
	   WHEN VariabilityID = 1          
	   THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)          
		  END,          
	  ActualYTDDollars06 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)          
		  END,          
	  ActualYTDDollars07 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)          
		  END,          
	  ActualYTDDollars08 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)          
		  END,          
	  ActualYTDDollars09 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)          
		  END,          
	  ActualYTDDollars10 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)          
		  END,          
	  ActualYTDDollars11 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)          
		  END,          
	  ActualYTDDollars12 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)          
		  END          
	FROM [fp].[StaffingHistory] fsh          
		INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID        
		INNER JOIN           
		(SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data          
	  PIVOT          
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv          
	   ON fs.DepartmentID = pv.DepartmentID          
	   AND fs.JobCodeID = pv.JobCodeID          
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID          
	   AND fs.EmployeeID = pv.EmployeeID           
	   AND fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID          
	 WHERE          
	  fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 34        
     
      
	DELETE FROM #IntStaffingDataRolledUpRaw      
	DELETE FROM #IntStaffingDataRolledUp      
	DELETE FROM #dept      
	DELETE FROM #emp    
	DELETE FROM #provDims  
   
	IF @IsProviderPlanningEnabled = 0
	BEGIN 
			
		----------------------------------------------------
		-- Provider is disabled
		----------------------------------------------------

		INSERT INTO #IntStaffingDataRolledUpRaw     
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,      
			hist.PayCodeGroupID,       
			hist.EmployeeID,      
			hist.UnitTypeID, 
			0 as ProviderID, 
			0 as ProviderTypeID, 
			0 as ProviderSpecialtyID, 
			0 as ProviderLineItemID, 
			3 as SubsectionID,       
			hist.MonthColumnName,       
			ISNULL(fv.FixedPercentage,1) as FixedPercentage,
			SUM(ISNULL(hist.Value, 0)) as Value  
		FROM #intFactStaffingWithEmployeeResolved hist     
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID   
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID 
				AND fv.JobCodeID = hist.JobCodeID 
				AND fv.PayCodeID = hist.PayCodeID  
				AND fv.EmployeeID = hist.EmployeeID  
		WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 
			AND hist.TimeclassID = 1 
			AND hist.IsDeleted = 0 
			AND hist.FiscalMonthID != 0           
			AND ((hist.UnitTypeID = 34 AND hist.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND hist.IsHoursIgnored = 0))        
		GROUP BY hist.DepartmentID,   
			hist.JobCodeID,   
			hist.PayCodeGroupID,
			hist.EmployeeID,
			hist.UnitTypeID,  
			hist.MonthColumnName,
			FixedPercentage   
	END ELSE BEGIN
	
		----------------------------------------------------
		-- Provider is enabled
		----------------------------------------------------
		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN
			
			-------------------------------------------------------
			-- BudgetConfigSetting is disabled
			-------------------------------------------------------

			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0			
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT 
				staff.DepartmentID,
				emp.EmployeeID, 
				phys.PhysicianID,
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID    
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')
			UNION		
			SELECT DISTINCT 
				prov.DepartmentID,
				phys.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
				LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')
				AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
			
			-- Provider from int.FactProvider
			INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
			SELECT
				DISTINCT
				fp.DepartmentID, 
				0 as JobCodeID,  
				0 as PayCodeGroupID, 
				0 as EmployeeID,
				fp.UnitTypeID, 
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fp.ProviderLineItemID,
				@ProviderSubsectionID, 
				fm.MonthColumnName,     
				1 as FixedPercentage,
				CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value
			FROM
				[int].[FactProvider] fp
				INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
			WHERE 
				fp.FiscalYearID = @CurrentFiscalYearID - 1
				AND fp.TimeClassID = 1 
				AND fp.IsDeleted = 0 
				AND fp.FiscalMonthID != 0      
				AND ps.Description = 'Staffing'
				AND emp.IsFP = 1
				AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
			GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID
			
			INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #IntStaffingDataRolledUpRaw

			-- Provider from int.FactStaffing
			INSERT INTO #IntStaffingDataRolledUpRaw  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
				SELECT       
				hist.DepartmentID,       
				hist.JobCodeID,       
				pc.PayCodeGroupID,    
				0 as EmployeeID, 
				hist.UnitTypeID,   
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				@ProviderSubsectionID,   
				fm.MonthColumnName,   
				CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage,
				CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value
			FROM [int].[FactStaffing] hist           
				INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
				INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
				INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID  
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID	
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID
					AND fv.JobCodeID = hist.JobCodeID 
					AND fv.PayCodeID = hist.PayCodeID 
					AND fv.EmployeeID = 0
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          
				LEFT JOIN #provDims pd ON hist.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID
			WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0
				AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))   
				AND emp.IsFP = 1      
			GROUP BY hist.DepartmentID,   
				hist.JobCodeID,   
				pc.PayCodeGroupID,
				emp.EmployeeID,
				hist.UnitTypeID,  
				fm.MonthColumnName,
				FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID
	
		END ELSE BEGIN

			-------------------------------------------------------
			-- BudgetConfigSetting is enabled
			-------------------------------------------------------
			IF @UseProviderSource = 0
			BEGIN

				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is disabled
				-------------------------------------------------------
				
				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0			
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

				-- 2. all employees from staffing
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					staff.DepartmentID,
					emp.EmployeeID, 
					phys.PhysicianID,
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID    
					INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
					INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND staff.EmployeeID > 0
					AND emp.NPI NOT IN ('Not Specified', '0', '')

				-- Provider from int.FactStaffing
				INSERT INTO #IntStaffingDataRolledUpRaw  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
					SELECT       
					hist.DepartmentID,       
					hist.JobCodeID,       
					pc.PayCodeGroupID,    
					0 as EmployeeID, 
					hist.UnitTypeID,   
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					pc.ProviderLineItemID,
					@ProviderSubsectionID,   
					fm.MonthColumnName,   
					CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage,
					CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value
				FROM [int].[FactStaffing] hist           
					INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
					INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
					INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID  
					INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID	
					LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID
						AND fv.JobCodeID = hist.JobCodeID 
						AND fv.PayCodeID = hist.PayCodeID 
						AND fv.EmployeeID = 0
						AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          
				WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0
					AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))   
					AND emp.IsFP = 1      
				GROUP BY hist.DepartmentID,   
					hist.JobCodeID,   
					pc.PayCodeGroupID,
					emp.EmployeeID,
					hist.UnitTypeID,  
					fm.MonthColumnName,
					FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

			END ELSE BEGIN

				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is enabled
				-------------------------------------------------------

				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider 
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

				-- 2. all employees that are providers
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					prov.DepartmentID,
					phys.EmployeeID, 
					phys.PhysicianID, 
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
					LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND phys.NPI NOT IN ('Not Specified', '0', '')
					AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

				-- Provider from int.FactProvider
				INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
				SELECT
					DISTINCT
					fp.DepartmentID, 
					0 as JobCodeID,  
					0 as PayCodeGroupID, 
					0 as EmployeeID,
					fp.UnitTypeID, 
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					fp.ProviderLineItemID,
					@ProviderSubsectionID, 
					fm.MonthColumnName,     
					1 as FixedPercentage,
					CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value
				FROM
					[int].[FactProvider] fp
					INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
				WHERE 
					fp.FiscalYearID = @CurrentFiscalYearID - 1
					AND fp.TimeClassID = 1 
					AND fp.IsDeleted = 0 
					AND fp.FiscalMonthID != 0      
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
					AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
				GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID,
					emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID
						
			END

		END

		-- Non-Provider from int.FactStaffing
		-- Populate into a temp table before summing up to deal with issues with the dynamic employee join
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,     
			hist.PayCodeID,
			pc.PayCodeGroupID,       
			CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE hist.EmployeeID
				END
			END as EmployeeID,
			hist.UnitTypeID,    
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			@StaffingSubsectionID as SubsectionID,   
			fm.MonthColumnName,   
			ISNULL(fv.FixedPercentage, 1) as FixedPercentage,
			ISNULL(hist.Value, 0) as Value 
		INTO #intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals
		FROM [int].[FactStaffing] hist           
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
			LEFT JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON hist.EmployeeID = emp.EmployeeID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON hist.EmployeeID = NotFpEmp.EmployeeID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
			INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID        
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				AND fv.JobCodeID = hist.JobCodeID 
				AND fv.PayCodeID = hist.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.						
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE hist.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID     
		WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 
			AND hist.TimeClassID = 1 
			AND hist.IsDeleted = 0 
			AND hist.FiscalMonthID != 0
			AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))         
			AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0)))   

		INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		      
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,       
			hist.PayCodeGroupID,       
			hist.EmployeeID,
			hist.UnitTypeID,    
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			@StaffingSubsectionID as SubsectionID,   
			hist.MonthColumnName,   
			ISNULL(fv.FixedPercentage,1) as FixedPercentage,
			SUM(ISNULL(hist.Value, 0)) as Value  
		FROM #intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals hist           
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
				AND fv.JobCodeID = hist.JobCodeID 
				AND fv.PayCodeID = hist.PayCodeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				AND fv.EmployeeID = hist.EmployeeID
		GROUP BY hist.DepartmentID,   
			hist.JobCodeID,   
			hist.PayCodeGroupID,
			hist.EmployeeID,
			hist.UnitTypeID,  
			hist.MonthColumnName,
			fv.FixedPercentage

	END
      
	INSERT INTO #IntStaffingDataRolledUp 
		 ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value      
	FROM #IntStaffingDataRolledUpRaw    
	WHERE FixedPercentage = 1       
       
	INSERT INTO #IntStaffingDataRolledUp      
		 ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID,
																UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0))      
	FROM #IntStaffingDataRolledUpRaw      
	WHERE FixedPercentage <> 1      
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, 
	CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END      
      
	 UPDATE          
	  fsh          
	 SET          
	  PriorYearActualHours01 = CASE          
		 WHEN VariabilityID = 1     
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)          
		  END,          
	  PriorYearActualHours02 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)          
		  END,          
	  PriorYearActualHours03 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)          
		  END,          
	  PriorYearActualHours04 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)          
		  END,          
	  PriorYearActualHours05 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)          
		  END,          
	  PriorYearActualHours06 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)          
			   ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)          
		  END,          
	  PriorYearActualHours07 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)          
		  END,          
	  PriorYearActualHours08 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)          
		  END,          
	  PriorYearActualHours09 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)          
		  END,          
	  PriorYearActualHours10 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)          
		  END,          
	  PriorYearActualHours11 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)          
		  END,          
	  PriorYearActualHours12 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)          
		  END           
	 FROM          
	  [fp].[StaffingHistory] fsh          
		INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID     
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID  
		INNER JOIN           
	  (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data          
	  PIVOT          
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv          
	   ON fs.DepartmentID = pv.DepartmentID          
	   AND fs.JobCodeID = pv.JobCodeID          
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID          
	   AND fs.EmployeeID = pv.EmployeeID          
		and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID          
	 WHERE          
	  fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 51
        
	 UPDATE          
	  fsh          
	 SET          
	  PriorYearActualDollars01 = CASE          
		 WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)          
		  END,          
	  PriorYearActualDollars02 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)          
		  END,          
	  PriorYearActualDollars03 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)          
		  END,          
	  PriorYearActualDollars04 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)          
		  END,          
	  PriorYearActualDollars05 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)          
		  END,          
	  PriorYearActualDollars06 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)          
			   ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)          
		  END,          
	  PriorYearActualDollars07 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)          
		  END,          
	  PriorYearActualDollars08 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)          
		  END,          
	  PriorYearActualDollars09 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)          
		  END,          
	  PriorYearActualDollars10 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)          
		  END,          
	  PriorYearActualDollars11 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)          
		  END,          
	  PriorYearActualDollars12 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)          
		  END           
	 FROM          
	  [fp].[StaffingHistory] fsh          
		INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID     
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID  
		INNER JOIN           
	  (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data          
	  PIVOT          
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv          
	   ON fs.DepartmentID = pv.DepartmentID          
	   AND fs.JobCodeID = pv.JobCodeID          
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID          
	   AND fs.EmployeeID = pv.EmployeeID          
		and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID          
	 WHERE          
	  fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 34    
        
	DELETE FROM #IntStaffingDataRolledUpRaw      
	DELETE FROM #IntStaffingDataRolledUp         
	DELETE FROM #dept      
	DELETE FROM #emp    
	DELETE FROM #provDims  
   
	IF @IsProviderPlanningEnabled = 0 BEGIN

		----------------------------------------------------
		-- Provider is disabled
		----------------------------------------------------

		INSERT INTO #IntStaffingDataRolledUpRaw     
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,       
			hist.PayCodeGroupID,       
			hist.EmployeeID,     
			hist.UnitTypeID, 
			0 as ProviderID, 
			0 as ProviderTypeID, 
			0 as ProviderSpecialtyID, 
			0 as ProviderLineItemID, 
			3 as SubsectionID,       
			hist.MonthColumnName,       
			ISNULL(fv.FixedPercentage, 1) as FixedPercentage,
			SUM(ISNULL(hist.Value, 0)) as Value
		FROM #intFactStaffingWithEmployeeResolved hist     
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID     
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID    
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
				AND fv.JobCodeID = hist.JobCodeID 
				AND fv.PayCodeID = hist.PayCodeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID   
				AND fv.EmployeeID = hist.EmployeeID     
		WHERE hist.FiscalYearID = @CurrentFiscalYearID 
			AND hist.TimeclassID = 2 
			AND hist.IsDeleted = 0
			AND hist.FiscalMonthID != 0           
			AND ((hist.UnitTypeID = 34 AND hist.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND hist.IsHoursIgnored = 0))     
		GROUP BY hist.DepartmentID,   
			hist.JobCodeID,   
			hist.PayCodeGroupID,
			hist.EmployeeID,
			hist.UnitTypeID,  
			hist.MonthColumnName,
			FixedPercentage  
	END ELSE BEGIN

		----------------------------------------------------
		-- Provider is enabled
		----------------------------------------------------
		
		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN
			
			-------------------------------------------------------
			-- BudgetConfigSetting is disabled
			-------------------------------------------------------

			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0			
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT 
				staff.DepartmentID,
				emp.EmployeeID, 
				phys.PhysicianID,
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, 
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')
			UNION		
			SELECT DISTINCT 
				prov.DepartmentID,
				phys.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, 
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
				LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')
				AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
			
			-- Provider from int.FactProvider
			INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
			SELECT
				DISTINCT
				fp.DepartmentID, 
				0 as JobCodeID,  
				0 as PayCodeGroupID, 
				0 as EmployeeID,
				fp.UnitTypeID, 
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fp.ProviderLineItemID,
				@ProviderSubsectionID, 
				fm.MonthColumnName,     
				1 as FixedPercentage,
				CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value
			FROM
				[int].[FactProvider] fp
				INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
			WHERE 
				fp.FiscalYearID = @CurrentFiscalYearID
				AND fp.TimeClassID = 2 
				AND fp.IsDeleted = 0 
				AND fp.FiscalMonthID != 0      
				AND ps.Description = 'Staffing'
				AND emp.IsFP = 1
				AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
			GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID


			INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #IntStaffingDataRolledUpRaw

			-- Provider from int.FactStaffing
			INSERT INTO #IntStaffingDataRolledUpRaw  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
			SELECT       
				hist.DepartmentID,       
				hist.JobCodeID,       
				pc.PayCodeGroupID, 
				0 as EmployeeID,   
				hist.UnitTypeID,    
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				@ProviderSubsectionID,   
				fm.MonthColumnName,   
				CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage,
				CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value
			FROM [int].[FactStaffing] hist           
				INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
				INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
				INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID  
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID	
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
					AND fv.JobCodeID = hist.JobCodeID 
					AND fv.PayCodeID = hist.PayCodeID 
					AND fv.EmployeeID = 0
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          
				LEFT JOIN #provDims pd ON hist.DepartmentID = pd.DepartmentID 
					AND emp.ProviderID = pd.ProviderID 
					and pd.ProviderLineItemID = pli.ProviderLineItemID
			WHERE hist.FiscalYearID = @CurrentFiscalYearID 
				AND hist.TimeClassID = 2 
				AND hist.IsDeleted = 0 
				AND hist.FiscalMonthID != 0
				AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))         
				AND emp.IsFP = 1
			GROUP BY hist.DepartmentID,   
				hist.JobCodeID,   
				pc.PayCodeGroupID,
				emp.EmployeeID,
				hist.UnitTypeID,  
				fm.MonthColumnName,
				FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

		END ELSE BEGIN
		
			-------------------------------------------------------
			-- BudgetConfigSetting is enabled
			-------------------------------------------------------
			IF @UseProviderSource = 0
			BEGIN

				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is disabled
				-------------------------------------------------------

				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0			
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

				-- 2. all employees from staffing
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					staff.DepartmentID,
					emp.EmployeeID, 
					phys.PhysicianID,
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, 
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID          
					INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
					INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND staff.EmployeeID > 0
					AND emp.NPI NOT IN ('Not Specified', '0', '')

				-- Provider from int.FactStaffing
				INSERT INTO #IntStaffingDataRolledUpRaw  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
				SELECT       
					hist.DepartmentID,       
					hist.JobCodeID,       
					pc.PayCodeGroupID, 
					0 as EmployeeID,   
					hist.UnitTypeID,    
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					pc.ProviderLineItemID,
					@ProviderSubsectionID,   
					fm.MonthColumnName,   
					CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage,
					CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value
				FROM [int].[FactStaffing] hist           
					INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
					INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
					INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID  
					INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID	
					LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
						AND fv.JobCodeID = hist.JobCodeID 
						AND fv.PayCodeID = hist.PayCodeID 
						AND fv.EmployeeID = 0
						AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          
				WHERE hist.FiscalYearID = @CurrentFiscalYearID 
					AND hist.TimeClassID = 2 
					AND hist.IsDeleted = 0 
					AND hist.FiscalMonthID != 0
					AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))         
					AND emp.IsFP = 1
				GROUP BY hist.DepartmentID,   
					hist.JobCodeID,   
					pc.PayCodeGroupID,
					emp.EmployeeID,
					hist.UnitTypeID,  
					fm.MonthColumnName,
					FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

			END ELSE BEGIN

				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is enabled
				-------------------------------------------------------

				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider 
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0				
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

				-- 2. all employees that are providers
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)	
				SELECT DISTINCT 
					prov.DepartmentID,
					phys.EmployeeID, 
					phys.PhysicianID, 
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, 
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID          
					LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND phys.NPI NOT IN ('Not Specified', '0', '')
					AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later

				-- Provider from int.FactProvider
				INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
				SELECT
					DISTINCT
					fp.DepartmentID, 
					0 as JobCodeID,  
					0 as PayCodeGroupID, 
					0 as EmployeeID,
					fp.UnitTypeID, 
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					fp.ProviderLineItemID,
					@ProviderSubsectionID, 
					fm.MonthColumnName,     
					1 as FixedPercentage,
					CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value
				FROM
					[int].[FactProvider] fp
					INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
				WHERE 
					fp.FiscalYearID = @CurrentFiscalYearID
					AND fp.TimeClassID = 2 
					AND fp.IsDeleted = 0 
					AND fp.FiscalMonthID != 0      
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
					AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later
				GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID,
					emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

			END

		END

		-- Non-Provider from int.FactStaffing
		-- Populate into a temp table before summing up to deal with issues with the dynamic employee join
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,     
			hist.PayCodeID,
			pc.PayCodeGroupID,       
			CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE hist.EmployeeID
				END
			END as EmployeeID,
			hist.UnitTypeID,    
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			@StaffingSubsectionID as SubsectionID,   
			fm.MonthColumnName,   
			ISNULL(fv.FixedPercentage, 1) as FixedPercentage,
			ISNULL(hist.Value, 0) as Value 
		INTO #intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget
		FROM [int].[FactStaffing] hist           
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
			LEFT JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON hist.EmployeeID = emp.EmployeeID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON hist.EmployeeID = NotFpEmp.EmployeeID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID    
			INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID        
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
				AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				AND fv.JobCodeID = hist.JobCodeID 
				AND fv.PayCodeID = hist.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					    ELSE hist.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID     
		WHERE hist.FiscalYearID = @CurrentFiscalYearID 
			AND hist.TimeClassID = 2 
			AND hist.IsDeleted = 0 
			AND hist.FiscalMonthID != 0
			AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0))         
			AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0)))  

		INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		      
		SELECT       
			hist.DepartmentID,       
			hist.JobCodeID,       
			hist.PayCodeGroupID,       
			hist.EmployeeID,
			hist.UnitTypeID,    
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			@StaffingSubsectionID as SubsectionID,   
			hist.MonthColumnName,   
			ISNULL(fv.FixedPercentage,1) as FixedPercentage,
			SUM(ISNULL(hist.Value, 0)) as Value  
		FROM #intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget hist           
			INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID 
			    AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID 
				AND fv.JobCodeID = hist.JobCodeID
				AND fv.PayCodeID = hist.PayCodeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID     
				AND fv.EmployeeID = hist.EmployeeID
		GROUP BY hist.DepartmentID,   
			hist.JobCodeID,   
			hist.PayCodeGroupID,
			hist.EmployeeID,
			hist.UnitTypeID,  
			hist.MonthColumnName,
			fv.FixedPercentage, 
			hist.UnitTypeID
	END     
      
	INSERT INTO #IntStaffingDataRolledUp 
		 ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value      
	FROM #IntStaffingDataRolledUpRaw    
	WHERE FixedPercentage = 1       
       
	INSERT INTO #IntStaffingDataRolledUp      
		 ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID,
																UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0))      
	FROM #IntStaffingDataRolledUpRaw    
	WHERE FixedPercentage <> 1      
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, 
	CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END   
           
            
	 UPDATE          
	  fsh          
	 SET          
	  CurrentYearBudgetHours01 = CASE          
		 WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)          
		  END,          
	  CurrentYearBudgetHours02 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)          
		  END,          
	  CurrentYearBudgetHours03 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)          
		  END,          
	  CurrentYearBudgetHours04 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)          
		  END,          
	  CurrentYearBudgetHours05 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)          
		  END,          
	  CurrentYearBudgetHours06 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)          
		  END,          
	  CurrentYearBudgetHours07 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)          
		  END,          
	  CurrentYearBudgetHours08 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)          
		  END,          
	  CurrentYearBudgetHours09 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)          
		  END,          
	  CurrentYearBudgetHours10 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)          
		  END,          
	  CurrentYearBudgetHours11 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)          
		  END,          
	  CurrentYearBudgetHours12 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)          
		  END           
	 FROM          
	  [fp].[StaffingHistory] fsh          
		INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID         
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID  
		INNER JOIN           
	  (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data          
	  PIVOT          
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv          
	   ON fs.DepartmentID = pv.DepartmentID          
	   AND fs.JobCodeID = pv.JobCodeID          
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID          
	   AND fs.EmployeeID = pv.EmployeeID   
		and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID          
	 WHERE          
	  fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 51    
	  
	  
	 UPDATE          
	  fsh          
	 SET          
	  CurrentYearBudgetDollars01 = CASE          
		 WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)          
		  END,          
	  CurrentYearBudgetDollars02 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)          
		  END,          
	  CurrentYearBudgetDollars03 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)          
		  END,          
	  CurrentYearBudgetDollars04 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)          
		  END,          
	  CurrentYearBudgetDollars05 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)          
		  END,          
	  CurrentYearBudgetDollars06 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)          
		  END,          
	  CurrentYearBudgetDollars07 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)          
		  END,          
	  CurrentYearBudgetDollars08 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)          
		  END,          
	  CurrentYearBudgetDollars09 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)          
		  END,          
	  CurrentYearBudgetDollars10 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)          
		  END,          
	  CurrentYearBudgetDollars11 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)          
		  END,          
	  CurrentYearBudgetDollars12 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)          
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)          
		  END           
	 FROM          
	  [fp].[StaffingHistory] fsh          
		INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID         
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID  
		INNER JOIN           
	  (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data          
	  PIVOT          
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv          
	   ON fs.DepartmentID = pv.DepartmentID          
	   AND fs.JobCodeID = pv.JobCodeID          
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID          
	   AND fs.EmployeeID = pv.EmployeeID   
		and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID          
	 WHERE          
	  fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 34
            
	 -- After the dollars and hours have been sampled in, need to recalculate the FTEs          
	 UPDATE fteHist           
	 SET           
	        fteHist.ActualYTDFTEs01 = fteHist.ActualYTDHours01 / currentWorkingHours.Month01          
		  , fteHist.ActualYTDFTEs02 = fteHist.ActualYTDHours02 / currentWorkingHours.Month02          
		  , fteHist.ActualYTDFTEs03 = fteHist.ActualYTDHours03 / currentWorkingHours.Month03          
		  , fteHist.ActualYTDFTEs04 = fteHist.ActualYTDHours04 / currentWorkingHours.Month04          
		  , fteHist.ActualYTDFTEs05 = fteHist.ActualYTDHours05 / currentWorkingHours.Month05          
		  , fteHist.ActualYTDFTEs06 = fteHist.ActualYTDHours06 / currentWorkingHours.Month06          
		  , fteHist.ActualYTDFTEs07 = fteHist.ActualYTDHours07 / currentWorkingHours.Month07          
		  , fteHist.ActualYTDFTEs08 = fteHist.ActualYTDHours08 / currentWorkingHours.Month08          
		  , fteHist.ActualYTDFTEs09 = fteHist.ActualYTDHours09 / currentWorkingHours.Month09          
		  , fteHist.ActualYTDFTEs10 = fteHist.ActualYTDHours10 / currentWorkingHours.Month10          
		  , fteHist.ActualYTDFTEs11 = fteHist.ActualYTDHours11 / currentWorkingHours.Month11          
		  , fteHist.ActualYTDFTEs12 = fteHist.ActualYTDHours12 / currentWorkingHours.Month12           
                
	      , fteHist.PriorYearActualFTEs01 = fteHist.PriorYearActualHours01 / priorWorkingHours.Month01          
		  , fteHist.PriorYearActualFTEs02 = fteHist.PriorYearActualHours02 / priorWorkingHours.Month02          
		  , fteHist.PriorYearActualFTEs03 = fteHist.PriorYearActualHours03 / priorWorkingHours.Month03          
		  , fteHist.PriorYearActualFTEs04 = fteHist.PriorYearActualHours04 / priorWorkingHours.Month04          
		  , fteHist.PriorYearActualFTEs05 = fteHist.PriorYearActualHours05 / priorWorkingHours.Month05          
		  , fteHist.PriorYearActualFTEs06 = fteHist.PriorYearActualHours06 / priorWorkingHours.Month06          
		  , fteHist.PriorYearActualFTEs07 = fteHist.PriorYearActualHours07 / priorWorkingHours.Month07          
		  , fteHist.PriorYearActualFTEs08 = fteHist.PriorYearActualHours08 / priorWorkingHours.Month08          
		  , fteHist.PriorYearActualFTEs09 = fteHist.PriorYearActualHours09 / priorWorkingHours.Month09          
		  , fteHist.PriorYearActualFTEs10 = fteHist.PriorYearActualHours10 / priorWorkingHours.Month10          
		  , fteHist.PriorYearActualFTEs11 = fteHist.PriorYearActualHours11 / priorWorkingHours.Month11          
		  , fteHist.PriorYearActualFTEs12 = fteHist.PriorYearActualHours12 / priorWorkingHours.Month12          
          
	      , fteHist.CurrentYearBudgetFTEs01 = fteHist.CurrentYearBudgetHours01 / currentWorkingHours.Month01          
		  , fteHist.CurrentYearBudgetFTEs02 = fteHist.CurrentYearBudgetHours02 / currentWorkingHours.Month02          
		  , fteHist.CurrentYearBudgetFTEs03 = fteHist.CurrentYearBudgetHours03 / currentWorkingHours.Month03          
		  , fteHist.CurrentYearBudgetFTEs04 = fteHist.CurrentYearBudgetHours04 / currentWorkingHours.Month04          
		  , fteHist.CurrentYearBudgetFTEs05 = fteHist.CurrentYearBudgetHours05 / currentWorkingHours.Month05          
		  , fteHist.CurrentYearBudgetFTEs06 = fteHist.CurrentYearBudgetHours06 / currentWorkingHours.Month06          
		  , fteHist.CurrentYearBudgetFTEs07 = fteHist.CurrentYearBudgetHours07 / currentWorkingHours.Month07          
		  , fteHist.CurrentYearBudgetFTEs08 = fteHist.CurrentYearBudgetHours08 / currentWorkingHours.Month08          
		  , fteHist.CurrentYearBudgetFTEs09 = fteHist.CurrentYearBudgetHours09 / currentWorkingHours.Month09          
		  , fteHist.CurrentYearBudgetFTEs10 = fteHist.CurrentYearBudgetHours10 / currentWorkingHours.Month10          
		  , fteHist.CurrentYearBudgetFTEs11 = fteHist.CurrentYearBudgetHours11 / currentWorkingHours.Month11          
		  , fteHist.CurrentYearBudgetFTEs12 = fteHist.CurrentYearBudgetHours12 / currentWorkingHours.Month12          
          
		FROM [fp].[Staffing] fte          
		  INNER JOIN #filterTable tmp on fte.DepartmentID = tmp.DepartmentID
		  INNER JOIN [fp].[StaffingHistory] fteHist ON fte.StaffingID = fteHist.StaffingID          
		  INNER JOIN [fw].[DimJobCode] jc on fte.JobCodeID = jc.JobCodeID          
		  INNER JOIN [fw].[DimDepartment] dept on fte.DepartmentID = dept.DepartmentID          
		  INNER JOIN [client].[FactWorkingHoursPerMonth] currentWorkingHours on currentWorkingHours.FiscalYearID = @CurrentFiscalYearID and currentWorkingHours.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)          
		  INNER JOIN [client].[FactWorkingHoursPerMonth] priorWorkingHours on priorWorkingHours.FiscalYearID = @CurrentFiscalYearID - 1 and priorWorkingHours.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)          
		  LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fte.PayCodeGroupID = exc.PayCodeGroupID           
		WHERE fte.EntityGroupConfigID = @EntityGroupConfigID AND exc.PayCodeGroupID IS NULL          
		option (recompile)

	 -- No longer storing historical wage rates           
	 
           
END;
GO


---------------------------------------------

-- fp.procSampleStaffingHistoryFTETotals
/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1	2021-01-21	BK		JAZZ-61724	Convert logic from old procSampleFactStaffingHistoryFTETotals
	** 2	2024-05-22	VZ		JAZZ-71605	Performance Optimization
	*************************************************************/

CREATE   PROCEDURE [fp].[procSampleStaffingHistoryFTETotals]

  @BudgetConfigID INT,
  @EntityGroupConfigID INT,
  @CurrentFiscalYearID INT,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment
	IF OBJECT_ID('tempdb..#FilteredData') IS NOT NULL DROP TABLE #FilteredData

	CREATE TABLE #FilterByDepartment (DepartmentID INT)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID 
	FROM @SourceDimensionality

	--JAZZ-3774
	--Updated insert statement to pull in DepartmentID and JobCodeID for joining purposes in the update statement
	CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT)
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT [staff].[StaffingID], [staff].[DepartmentID], [staff].[JobCodeID], [staff].[PayCodeGroupID]
		FROM [fp].[Staffing] staff
		INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = staff.DepartmentID
		INNER JOIN [fw].[DimDepartment] dd ON ft.DepartmentID = dd.DepartmentID
		INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON dd.EntityID = egcm.EntityID
		INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID 
			AND egc.EntityGroupConfigID = staff.EntityGroupConfigID
	    WHERE staff.EntityGroupConfigID = @EntityGroupConfigID
	END 
	ELSE 
	BEGIN
		INSERT INTO #FilteredData
		SELECT [staff].[StaffingID], [staff].[DepartmentID], [staff].[JobCodeID], [staff].[PayCodeGroupID]
		FROM [fp].[Staffing] staff	
		WHERE staff.EntityGroupConfigID = @EntityGroupConfigID
	END

	--If no records, don't even go into the next part
	IF(EXISTS(SELECT 1 FROM #FilteredData))
	BEGIN
		
		
		UPDATE fte
		SET fte.ActualYTDFTEsTotal = fte.ActualYTDHoursTotal / currentWorkingHours.MonthYearly,
			fte.PriorYearActualFTEsTotal = fte.PriorYearActualHoursTotal / priorWorkingHours.MonthYearly,
			fte.CurrentYearBudgetFTEsTotal = fte.CurrentYearBudgetHoursTotal / currentWorkingHours.MonthYearly
		FROM [fp].[StaffingHistory] fte
		INNER JOIN #FilteredData fdata ON fte.StaffingID = fdata.StaffingID
		INNER JOIN [fw].[DimJobCode] jc ON fdata.JobCodeID = jc.JobCodeID
		INNER JOIN [fw].[DimDepartment] dept ON fdata.DepartmentID = dept.DepartmentID
		INNER JOIN [client].[FactWorkingHoursPerMonth] currentWorkingHours ON currentWorkingHours.FiscalYearID = @CurrentFiscalYearID 
			AND currentWorkingHours.WorkWeekID = 
			(
				CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID 
				ELSE dept.WorkWeekID END
			)
		INNER JOIN [client].[FactWorkingHoursPerMonth] priorWorkingHours ON priorWorkingHours.FiscalYearID = @CurrentFiscalYearID - 1 
			AND priorWorkingHours.WorkWeekID = 
			(
				CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID 
				ELSE dept.WorkWeekID END
			)
		LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON fdata.PayCodeGroupID = exc.PayCodeGroupID
		WHERE  exc.PayCodeGroupID IS NULL
		AND EXISTS (
		SELECT fte.ActualYTDFTEsTotal,fte.PriorYearActualFTEsTotal,fte.CurrentYearBudgetFTEsTotal
		EXCEPT 
		SELECT CAST(fte.ActualYTDHoursTotal / currentWorkingHours.MonthYearly AS DECIMAL(19,8)), CAST(fte.PriorYearActualHoursTotal / priorWorkingHours.MonthYearly AS DECIMAL(19,8)),CAST(fte.CurrentYearBudgetHoursTotal / currentWorkingHours.MonthYearly AS DECIMAL(19,8))
		)
	END
END
GO


---------------------------------------------

-- fp.procSampleStaffingHoursPerUOS
CREATE   PROCEDURE [fp].[procSampleStaffingHoursPerUOS]
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@StaffingFiscalYearID INT,
	@StaffingTimeClassID INT,
	@CurrentFiscalYearID INT,
	@ActualTimeClassID INT,
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS 
BEGIN
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI            Description
	 ** 1 	 2019-03-26  IP  	 B-22466	   Switch usages of funcGetSourceDimensionalityAsTable to a temp table
	 ** 2 	 2019-04-08  BK  	 Failing Test  Fix previous update of proc that incorrectly included old projection code
	 ** 3 	 2020-05-12  BK  	 D-09757       Change projection hours/uos calc to use int.FactStaffing so that we don't use variable staffing hours that used working hours to potential leap year adjustment (what is in fp.FactStaffing)
	 ** 4 	 2021-02-10  BK  	 -------       Found incorrect reference to SubsectionID = 0
	 ** 5 	 2021-06-08  LR		 JAZZ-20116    Moving feature flag to plan config level		
	 ** 6 	 2021-12-09  BK		 JAZZ-30703    Use fp.FactStatisticsHistory historicals instead of int.FactStatistic
	 ** 7 	 2022-03-14  NT		 JAZZ-33622    Improve performance by replacing LEFT by INNER join and add missing FlexingTypeID filter
	 ** 8 	 2022-04-29  MY		 JAZZ-28395    Cache Variability Percentage on FactStaffing
	 ** 9 	 2022-10-04  MY		 JAZZ-37262    Remove Feature Flag 'Use Variability From FactStaffing Table'
	 ** 10	 11-7-2022   MY      JAZZ-35951	   Add EmployeeID to FactStaffingVariabilityDetail
	 ** 11	 2023-03-13	 MY		 JAZZ-48981	   Update sampling for cross department flexing
	 ** 12	 2023-09-19  JB  	 JAZZ-59196	   Remove FF Use int.FactStaffing to calculate Hours Per UOS
     ** 13   2023-09-20  BK      JAZZ-60973    Update for new data structure
	 ** 14   2024-01-31  NH      JAZZ-64064    Move Provider Planning FF as a setting in Plan Config
	 ** 15	 2024-08-26	 MY		 JAZZ-76040	   Adjust Statistics for Leap Year
	 ** 16	 2024-08-28	 NH		 JAZZ-74968	   JobCodeID updates
	 *************************************************************/
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#variableHours') IS NOT NULL DROP TABLE #variableHours;
	IF OBJECT_ID('tempdb..#statsBudget') IS NOT NULL DROP TABLE #statsBudget;

	DECLARE @EnableLeapYearAdjustedStatistics BIT = ISNULL((SELECT bcs.Value 
										FROM fp.viewBudgetConfigSetting bcs
											INNER JOIN fp.BudgetConfig bc ON bcs.BudgetConfigID = bc.BudgetConfigID
											INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
										WHERE bcs.Name = 'Enable Leap Year Adjusted Statistics for Calculating Rates' 
											AND egc.EntityGroupConfigID = @EntityGroupConfigID), 0);

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	CREATE TABLE #statsBudget (DepartmentID INT, JobCodeID INT, StatTotal DECIMAL(19,8))

	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM [fp].[Staffing] d WITH (READUNCOMMITTED) 
		WHERE BudgetConfigID = @BudgetConfigID
			AND FlexingTypeID = 3 -- Staffing
	END

	DECLARE @IsAnnualized BIT = (CASE WHEN @StaffingFiscalYearID = @CurrentFiscalYearID AND @StaffingTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)	
	DECLARE @UsePriorYear BIT = 0;
	DECLARE @UseActualYTD BIT = 0;
	DECLARE @UseCurrentYearBudget BIT = 0;
	DECLARE @IsCurrentYearALeapYear BIT = (CASE WHEN (@CurrentFiscalYearID % 4 = 0 AND @CurrentFiscalYearID % 100 <> 0) OR @CurrentFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
	DECLARE @AdjustStatisticsForLeapYear BIT = CASE WHEN @EnableLeapYearAdjustedStatistics = 1 AND @IsAnnualized = 1 AND @IsCurrentYearALeapYear = 1 THEN 1 ELSE 0 END;

	IF @StaffingTimeClassID = 2 BEGIN
		SET @UseCurrentYearBudget = 1;
	END ELSE BEGIN
		IF @CurrentFiscalYearID = @StaffingFiscalYearID BEGIN
			SET @UseActualYTD = 1;
		END ELSE BEGIN
			SET @UsePriorYear = 1
			END
	END		


	INSERT INTO #statsBudget
	SELECT 
		map.DepartmentID,
		map.PRJobCodeID as JobCodeID,
		CASE 
			WHEN @UseActualYTD = 1 AND @EnableLeapYearAdjustedStatistics = 1 THEN ISNULL(SUM(statHist.ActualYTDValueTotal), 0)
			WHEN @UseCurrentYearBudget = 1 AND @EnableLeapYearAdjustedStatistics = 1 THEN ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0)
			WHEN @UsePriorYear = 1 AND @EnableLeapYearAdjustedStatistics = 1 THEN ISNULL(SUM(statHist.PriorYearActualValueTotal), 0)
			-- JAZZ-76040: This isn't really related, but it was fixed as part of this story. Wrapping this in a feature flag
			-- because otherwise rates will change 
			WHEN @UseActualYTD = 1 AND @EnableLeapYearAdjustedStatistics = 0 THEN CAST(ISNULL(SUM(statHist.ActualYTDValueTotal), 0) AS INT)
			WHEN @UseCurrentYearBudget = 1 AND @EnableLeapYearAdjustedStatistics = 0 THEN CAST(ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0) AS INT)
			WHEN @UsePriorYear = 1 AND @EnableLeapYearAdjustedStatistics = 0 THEN CAST(ISNULL(SUM(statHist.PriorYearActualValueTotal), 0) AS INT)
		END AS StatTotal
	FROM [fp].[FlexConfigMapping] map
		INNER JOIN fp.[FactStatistics] stat ON stat.DepartmentID = map.SourceDepartmentID AND stat.AccountID = map.StatAccountID AND stat.BudgetConfigID = @BudgetConfigID
		INNER JOIN fp.[FactStatisticsHistory] statHist ON stat.StatisticsID = statHist.StatisticsID
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = map.DepartmentID
	WHERE map.EntityGroupConfigID = @EntityGroupConfigID
	  AND map.FlexingTypeID = 3 -- Staffing
	GROUP BY
		map.DepartmentID, 
		map.PRJobCodeID

	CREATE TABLE #variableHours (StaffingID int, --DepartmentID int, JobCodeID smallint, PayCodeGroupID int, EntityGroupConfigID int, ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, 
	                             BudgetHourTotal decimal(19,8))

	CREATE TABLE #staffingVariability (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6))

	INSERT INTO #staffingVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, FixedPercentage)
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage
	FROM [fp].[viewFactStaffingVariability] fav
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigID = @EntityGroupConfigID AND egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID
	WHERE ProviderLineItemID = 0 -- ProviderLineItems do not have
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID


		DECLARE @IsProviderPlanningEnabled BIT;
		SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;	
		DECLARE @ProviderSubsectionID INT = 4;

		INSERT INTO #variableHours
		SELECT fs.StaffingID,
			/*fs.DepartmentID,
			fs.JobCodeID,
			fs.PayCodeGroupID,
			fs.EntityGroupConfigID,
			fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,*/
			COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal AS BudgetHourTotal
		FROM [fp].[Staffing] fs
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fs.DepartmentID)
		INNER JOIN (
			SELECT   
			 src.DepartmentID,  src.JobCodeID, pc.PayCodeGroupID, 0 as ProviderID, 0 as ProviderTypeID, 0 as ProviderSpecialtyID, 0 as ProviderLineItemID, 3 as SubsectionID, SUM(ISNULL(src.Value, 0)) as SampledBudgetTotal      		
			FROM [int].[FactStaffing] src        
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID   
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID      
			WHERE src.FiscalYearID = @StaffingFiscalYearID   
				AND src.TimeClassID = @StaffingTimeClassID   
				AND src.IsDeleted = 0   
				AND src.FiscalMonthID != 0   
				AND src.UnitTypeID = 51   
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))      
				AND pc.IsHoursIgnored = 0        
			GROUP BY src.DepartmentID, src.JobCodeID, pc.PayCodeGroupID
		) as total
			ON total.DepartmentID = fs.DepartmentID
				AND total.JobCodeID = fs.JobCodeID
				AND total.PayCodeGroupID = fs.PayCodeGroupID
				AND total.ProviderID = fs.ProviderID
				AND total.ProviderTypeID = fs.ProviderTypeID
				AND total.ProviderSpecialtyID = fs.ProviderSpecialtyID
				AND total.ProviderLineItemID = fs.ProviderLineItemID
				AND total.SubsectionID = fs.SubsectionID
		LEFT JOIN #staffingVariability fv 
			ON fv.DepartmentID = fs.DepartmentID 
			AND fv.JobCodeID = fs.JobCodeID
			AND fv.PayCodeGroupID = fs.PayCodeGroupID
			AND fv.EmployeeID = fs.EmployeeID
		WHERE 
			fs.EntityGroupConfigID = @EntityGroupConfigID		
			AND fs.VariabilityID = 2
			AND (@IsProviderPlanningEnabled = 0 OR fs.SubSectionID <> @ProviderSubsectionID)

		-- JAZZ-76040: Adjust Statistics and Hours for Leap Year
		IF (@AdjustStatisticsForLeapYear = 1)
		BEGIN

			-- per stackoverflow (per MY)
			DECLARE @BudgetFiscalYearID INT = @CurrentFiscalYearID + 1;
			DECLARE @IsBudgetLeapYear BIT = (CASE WHEN (@BudgetFiscalYearID % 4 = 0 AND @BudgetFiscalYearID % 100 <> 0) OR @BudgetFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)  
			DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12)
			DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsCurrentYearALeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)

			UPDATE #statsBudget
			SET	StatTotal = ((StatTotal / @DaysInMonthsLoaded) * @DaysBudgetYear)		

			UPDATE #variableHours
			SET	BudgetHourTotal = ((BudgetHourTotal / @DaysInMonthsLoaded) * @DaysBudgetYear)			

		END

		-- set the Dollars/UOS values on Staffing table
		UPDATE
			fs
		SET
			InitialBudgetRate01 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate02 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate03 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate04 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate05 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate06 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate07 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate08 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate09 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate10 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate11 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialBudgetRate12 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),


			-- Projection rates should match the budget rates and use the budget baseline to calculate
			InitialProjectionRate01 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate02 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate03 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate04 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate05 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate06 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate07 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate08 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate09 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate10 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate11 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0),
			InitialProjectionRate12 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0)

		FROM
			[fp].[Staffing] fs
			INNER JOIN #variableHours fsHours
				ON fs.StaffingID = fsHours.StaffingID /*fs.DepartmentID = fsHours.DepartmentID
				AND fs.JobCodeID = fsHours.JobCodeID
				AND fs.PayCodeGroupID = fsHours.PayCodeGroupID
				AND fs.EntityGroupConfigID = fsHours.EntityGroupConfigID */
			INNER JOIN #statsBudget stat
				ON stat.DepartmentID = fs.DepartmentID
				AND stat.JobCodeID = fs.JobCodeID
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID
			AND (

					fs.InitialBudgetRate01 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate02 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate03 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate04 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate05 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate06 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate07 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate08 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate09 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate10 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate11 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialBudgetRate12 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR

					fs.InitialProjectionRate01 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate02 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate03 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate04 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate05 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate06 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate07 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate08 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate09 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate10 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate11 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR 
					fs.InitialProjectionRate12 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0))


END
GO


---------------------------------------------

-- fp.procSampleStaffingInitialBudgetDollars
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1    2023-09-20  BK      JAZZ-60973	Update for data restructure
** 2    2024-01-31  NH      JAZZ-64064	Move Provider Planning FF as a setting in Plan Config
** 3    2024-03-20  MY      JAZZ-69388	Migration to resolve JAZZ-59251 was reverted by the next migration to the proc for new data structure.
*************************************************************/
CREATE   PROCEDURE [fp].[procSampleStaffingInitialBudgetDollars]
	@EntityGroupConfigID int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;
	DECLARE @ProviderSubsectionID INT;
	SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' 


	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	
	-- Spread Dollars-Only evenly
	UPDATE
		fs
	SET
		InitialBudgetDollars01 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars02 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars03 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars04 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars05 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars06 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars07 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars08 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars09 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars10 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars11 = SampledBudgetDollarsTotal/12,
		InitialBudgetDollars12 = SampledBudgetDollarsTotal - ((SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) +
															  (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) ) 
	FROM [fp].[Staffing] fs 
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID  AND (fs.ProductiveClassID = 4 OR (@IsProviderPlanningEnabled = 1 AND SubsectionID = @ProviderSubsectionID))
	

	-- Now do all non Dollars-Only   
   
	-- All other productive classes should be hours * wage rate
	-- Known issue to resolve, if no hours/wage rate, then all dollars will be put in month 12
	UPDATE
		fs
	SET
		fs.InitialBudgetDollars01 = fs.InitialBudgetHours01 * wr.InitialBudget01,
		fs.InitialBudgetDollars02 = fs.InitialBudgetHours02 * wr.InitialBudget02,
		fs.InitialBudgetDollars03 = fs.InitialBudgetHours03 * wr.InitialBudget03,
		fs.InitialBudgetDollars04 = fs.InitialBudgetHours04 * wr.InitialBudget04,
		fs.InitialBudgetDollars05 = fs.InitialBudgetHours05 * wr.InitialBudget05,
		fs.InitialBudgetDollars06 = fs.InitialBudgetHours06 * wr.InitialBudget06,
		fs.InitialBudgetDollars07 = fs.InitialBudgetHours07 * wr.InitialBudget07,
		fs.InitialBudgetDollars08 = fs.InitialBudgetHours08 * wr.InitialBudget08,
		fs.InitialBudgetDollars09 = fs.InitialBudgetHours09 * wr.InitialBudget09,
		fs.InitialBudgetDollars10 = fs.InitialBudgetHours10 * wr.InitialBudget10,
		fs.InitialBudgetDollars11 = fs.InitialBudgetHours11 * wr.InitialBudget11,
		fs.InitialBudgetDollars12 = fs.InitialBudgetHours12 * wr.InitialBudget12 
	FROM [fp].[Staffing] fs 
		INNER JOIN fp.StaffingWageRate wr on fs.StaffingWageRateID = wr.StaffingWageRateID
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.ProductiveClassID <> 4 AND (fs.SubsectionID <> @ProviderSubsectionID OR @IsProviderPlanningEnabled = 0)	
	
END
GO


---------------------------------------------

-- fp.procSampleStaffingInitialProjectionDollars
CREATE   PROCEDURE [fp].[procSampleStaffingInitialProjectionDollars]  
	@EntityGroupConfigID int,  
	@MonthsLoaded int,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE  
AS  
BEGIN  
/*************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI            Description
** 1    2023-03-20  BK      JAZZ-50830	  Fix issue with Provider not being updated for BudgetPhaseID = 2
** 2    2023-09-20  BK      JAZZ-60973    Update for data restructure
** 3    2024-01-31  NH      JAZZ-64064    Move Provider Planning FF as a setting in Plan Config
** 4    2024-03-20  MY      JAZZ-69388	  Migration to resolve JAZZ-59251 was reverted by the next migration to the proc for new data structure.
**************************************************************
*/
	DECLARE @IsProviderPlanningEnabled BIT, @StaffingTimeClassID INT, @StaffingFiscalYearID INT, @ProjectionFiscalYearID INT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;
	DECLARE @ProviderSubsectionID INT;
	SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' 
		
	SELECT @StaffingTimeClassID = PayrollTimeClassID, @StaffingFiscalYearID = PayrollFiscalYearID, @ProjectionFiscalYearID = FiscalYearID - 1 
	FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID


	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
  
  
  -- Update all Non Dollars-Only Productive Classes  
  UPDATE  
   fs  
  SET  
   InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1  THEN fs.SampledProjectionDollars01 ELSE fs.InitialProjectionHours01 * wr.InitialProjection01 END,  
   InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2  THEN fs.SampledProjectionDollars02 ELSE fs.InitialProjectionHours02 * wr.InitialProjection02 END,  
   InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3  THEN fs.SampledProjectionDollars03 ELSE fs.InitialProjectionHours03 * wr.InitialProjection03 END,  
   InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4  THEN fs.SampledProjectionDollars04 ELSE fs.InitialProjectionHours04 * wr.InitialProjection04 END,  
   InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5  THEN fs.SampledProjectionDollars05 ELSE fs.InitialProjectionHours05 * wr.InitialProjection05 END,  
   InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6  THEN fs.SampledProjectionDollars06 ELSE fs.InitialProjectionHours06 * wr.InitialProjection06 END,  
   InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7  THEN fs.SampledProjectionDollars07 ELSE fs.InitialProjectionHours07 * wr.InitialProjection07 END,  
   InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8  THEN fs.SampledProjectionDollars08 ELSE fs.InitialProjectionHours08 * wr.InitialProjection08 END,  
   InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9  THEN fs.SampledProjectionDollars09 ELSE fs.InitialProjectionHours09 * wr.InitialProjection09 END,  
   InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionDollars10 ELSE fs.InitialProjectionHours10 * wr.InitialProjection10 END,  
   InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionDollars11 ELSE fs.InitialProjectionHours11 * wr.InitialProjection11 END,  
   InitialProjectionDollars12 = CASE WHEN @MonthsLoaded  = 12 THEN fs.SampledProjectionDollars12 ELSE fs.InitialProjectionHours12 * wr.InitialProjection12 END  
  FROM [fp].[Staffing] fs    
  INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
  INNER JOIN [fp].[StaffingWageRate] wr on fs.StaffingWageRateID = wr.StaffingWageRateID
  WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.ProductiveClassID <> 4 -- not 'Dollars-Only'  
		AND (fs.SubsectionID <> @ProviderSubsectionID OR @IsProviderPlanningEnabled = 0) -- not provider data
  
    
  -- Dollars-Only Productive Class  
  -- Spread Dollars-Only evenly when not using Current Year Budget as baseline  
  
  IF @StaffingTimeClassID = 2 AND @StaffingFiscalYearID = @ProjectionFiscalYearID 
  BEGIN
		UPDATE
			fs
		SET
			InitialProjectionDollars01 = SampledProjectionDollars01,
			InitialProjectionDollars02 = SampledProjectionDollars02,
			InitialProjectionDollars03 = SampledProjectionDollars03,
			InitialProjectionDollars04 = SampledProjectionDollars04,
			InitialProjectionDollars05 = SampledProjectionDollars05,
			InitialProjectionDollars06 = SampledProjectionDollars06,
			InitialProjectionDollars07 = SampledProjectionDollars07,
			InitialProjectionDollars08 = SampledProjectionDollars08,
			InitialProjectionDollars09 = SampledProjectionDollars09,
			InitialProjectionDollars10 = SampledProjectionDollars10,
			InitialProjectionDollars11 = SampledProjectionDollars11,
			InitialProjectionDollars12 = SampledProjectionDollars12 
		FROM [fp].[Staffing] fs 
			INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND (fs.ProductiveClassID = 4 OR (@IsProviderPlanningEnabled = 1 AND SubsectionID = @ProviderSubsectionID))
		
	END ELSE 
	BEGIN 
		CREATE TABLE #DollarTotals (StaffingID INT, ProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8),  
	    INDEX ix_dol_1 NONCLUSTERED (StaffingID))   
	       
	       INSERT INTO #DollarTotals (StaffingID, ProjectionTotal)  
	       SELECT staff.StaffingID,   
	       CASE WHEN @MonthsLoaded = 11 THEN staff.SampledProjectionDollars12    
	       WHEN @MonthsLoaded = 10 THEN staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 9 THEN staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 8 THEN staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 7 THEN staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 6 THEN staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 5 THEN staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 4 THEN staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 3 THEN staff.SampledProjectionDollars04 + staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10  + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 2 THEN staff.SampledProjectionDollars03 + staff.SampledProjectionDollars04 + staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12  
	       WHEN @MonthsLoaded = 1 THEN staff.SampledProjectionDollars02 + staff.SampledProjectionDollars03 + staff.SampledProjectionDollars04 + staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12    
	        ELSE 0  
	     END  
	       FROM [fp].[Staffing] staff   
	       INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID	   
	     WHERE staff.EntityGroupConfigID = @EntityGroupConfigID AND (staff.ProductiveClassID = 4  OR (@IsProviderPlanningEnabled = 1 AND SubsectionID = @ProviderSubsectionID))
	            
	            
	    UPDATE a   
	        SET NewValue = ProjectionTotal / (12.0 - @MonthsLoaded)  
	    FROM #DollarTotals a  
	       
	       
	    -- update initial projection for dollars and hours  
	    UPDATE fs  
	    SET    
	      fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.SampledProjectionDollars01 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledProjectionDollars02 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledProjectionDollars03 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledProjectionDollars04 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledProjectionDollars05 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledProjectionDollars06 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledProjectionDollars07 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledProjectionDollars08 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledProjectionDollars09 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionDollars10 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionDollars11 ELSE t.NewValue END,  
	        fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjectionDollars12 ELSE t.NewValue END  
	    FROM   
	     [fp].[Staffing] fs INNER JOIN #DollarTotals t on fs.StaffingID = t.StaffingID  
       
   END
   
  
END
GO


---------------------------------------------

-- fp.procSampleStaffingOriginalBudgetDollars
CREATE   PROCEDURE [fp].[procSampleStaffingOriginalBudgetDollars]         
	@EntityGroupConfigGUID uniqueidentifier,          
	@EntityGroupConfigID int,          
	@CurrentFiscalYearID smallint,          
	@BudgetYearID smallint,          
	@SourceFiscalYearID smallint,          
	@SourceTimeClassID tinyint,          
	@MonthsLoaded int, 
	@IsEmployeeBudgeting bit,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY        
AS          
BEGIN   
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date       Author    WI   			Description
	 ** 4   2021-03-22  NT  	  JAZZ-15374    Use NPI instead of EmployeID for Provider Comp Sampling
	 ** 5   2021-06-30  BW  	  JAZZ-21627    Update selects and group by for EmployeID for variablity
	 ** 6   2021-12-01  OP		  JAZZ-29466    removed empty users check for prov comp data
 	 ** 7   2022-02-14  BK		  JAZZ-33248    respect department setting for employee budgeting
	 ** 8   2022-03-02  MZ		  JAZZ-30547    improved checks in order to sample valid Employees with valid NPI
	 ** 9   2022-05-27  OP		  JAZZ-30811    sample prov comp data
	 ** 10  2022-08-08  BK		  JAZZ-38357    Make sure IsFP records are correctly sampled depending on if true or false
	 ** 11  2022-10-07  AO		  JAZZ-42868    Non-provider department samples correct staffing values when provider sampling feature is turned on.
	 ** 12  2022-11-07  MZ		  JAZZ-35344    improved checks in order to sample valid Employees with valid NPI from FactProvider
	 ** 13  2022-11-07  MY		  JAZZ-35951    Add EmployeeID to FactStaffingVariabilityDetail
	 ** 14  2022-12-12  DM		  JAZZ-46455    Sampling of Provider Type and Provider Specialty is linked to Section Setup
	 ** 15  2023-09-26  BK		  JAZZ-61239    Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing
	 ** 16  2023-09-30  BK		  JAZZ-60973    Update for data restructure
	 ** 17  2024-01-31  NH		  JAZZ-64064    Move Provider Planning FF as a setting in Plan Config
	 ** 18  2024-03-25  MY        JAZZ-69661	Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
	 ** 19  2024-06-18  MZ        JAZZ-72231    Added Source Provider Sampling
	 ** 20  2024-08-12  MD			JAZZ-75302   Adjust dollars for leap year
	 *************************************************************/
          
	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable
	IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData 
	IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData 
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved 
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider   
	IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData  

	DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)    
	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	DECLARE @UseProviderSource BIT;
	DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT;
	DECLARE @AdjustWageRateByDaysInYear BIT = 0;
	DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID) 

	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

	SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID

	SELECT @AdjustWageRateByDaysInYear = ISNULL(Value,0) FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Adjust Wage Rate by Days in Year' AND BudgetConfigID = @BudgetConfigID

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END
	       
	CREATE TABLE #IntStaffingData (    
		DepartmentID int,    
		JobCodeID int,    
		PayCodeGroupID int,    
		EmployeeID int, 
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
		MonthColumnName varchar(50),    
		FixedPercentage decimal(19,8),    
		Value decimal (19,8)    
	)   

	CREATE TABLE #TempIntStaffingData (    
		DepartmentID int,    
		JobCodeID int,    
		PayCodeGroupID int,    
		EmployeeID int, 
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
		MonthColumnName varchar(50),    
		FixedPercentage decimal(19,8),    
		Value decimal (19,8)    
	)       

	CREATE TABLE #WorkingHoursRatioData (  
		DepartmentID int,  
		JobCodeID int,  
		PayCodeGroupID int,  
		MonthRatio01 decimal(19,8),  
		MonthRatio02 decimal (19,8),  
		MonthRatio03 decimal (19,8),  
		MonthRatio04 decimal (19,8),  
		MonthRatio05 decimal (19,8),  
		MonthRatio06 decimal (19,8),  
		MonthRatio07 decimal (19,8),  
		MonthRatio08 decimal (19,8),  
		MonthRatio09 decimal (19,8),  
		MonthRatio10 decimal (19,8),  
		MonthRatio11 decimal (19,8),  
		MonthRatio12 decimal (19,8)   
	) 
     
	IF @IsProviderPlanningEnabled = 0 
	BEGIN

		------------------------------------
		-- Provider disabled
		------------------------------------

		-- Resolve EmployeeID up front so we don't have to do it every time.
		SELECT
			src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeID,   
			CASE
			WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
			END as EmployeeID,
			0 AS ProviderID, 
			0 AS ProviderTypeID, 
			0 AS ProviderSpecialtyID, 
			0 AS ProviderLineItemID,
			src.FiscalYearID,
			src.TimeClassID,
			src.UnitTypeID,
			src.FiscalMonthID,
			src.IsDeleted,
			Value
		INTO #intFactStaffingWithEmployeeResolved
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- see Jazz-61239 for more details
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
		WHERE src.FiscalYearID = @SourceFiscalYearID 
			AND src.TimeClassID = @SourceTimeClassID 
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 34 

		INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
			ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value)    
		SELECT     
			src.DepartmentID,     
			src.JobCodeID,     
			pc.PayCodeGroupID,     
			src.EmployeeID,
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			0 as SubsectionID,
			fm.MonthColumnName,     
			ISNULL(fv.FixedPercentage,1) as FixedPercentage,
			SUM(ISNULL(src.Value, 0)) as Value
		FROM #intFactStaffingWithEmployeeResolved src           
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID          
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID          
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID           
				AND fv.PayCodeID = src.PayCodeID 				  
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved
						-- see Jazz-61239 for more details
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID            
		WHERE src.FiscalYearID = @SourceFiscalYearID 
			AND src.TimeClassID = @SourceTimeClassID 
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 34 
			AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
			AND pc.IsDollarsIgnored = 0        
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			pc.PayCodeGroupID,
			src.EmployeeID,
			fm.MonthColumnName,
			FixedPercentage

	END ELSE BEGIN
		
		------------------------------------
		-- Provider enabled
		------------------------------------

		IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
		IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept
		IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims
		CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT)
		CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)
		CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT)
		DECLARE @StaffingSubsectionID INT;
		DECLARE @ProviderSubsectionID INT;
		SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' 
		SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' 
		
		DECLARE @IsProviderTypeDisabled BIT;
		SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

	
		DECLARE @IsProviderSpecialtyDisabled BIT;
		SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

		-- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
		DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 
						   FROM fp.BudgetConfigSetting setting 
						      INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
						   WHERE def.Name = 'Enable Department Level Provider For Sampling'
						     AND setting.BudgetConfigID = @BudgetConfigID
			  				  AND setting.Value = 1), 0)

		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN

			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
			    staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT	
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
				emp.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
			    staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 				
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')
			UNION		
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
				phys.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')
				
			-- Provider from int.FactProvider
			INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
			SELECT
				DISTINCT
				fp.DepartmentID, 
				0 as JobCodeID,  
			    0 as PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fp.ProviderLineItemID,
				@ProviderSubsectionID, 
				fm.MonthColumnName,     
				1 as FixedPercentage,
				SUM(ISNULL(fp.Value, 0)) as Value
			FROM
				[int].[FactProvider] fp
				INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
			WHERE 
				fp.FiscalYearID = @SourceFiscalYearID 
				AND fp.TimeClassID = @SourceTimeClassID 
				AND fp.IsDeleted = 0 
				AND fp.FiscalMonthID != 0 
				AND fp.UnitTypeID = 34
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
				AND ps.Description = 'Staffing'
				AND emp.IsFP = 1
			GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID


			INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData

			-- Provider from int.FactStaffing
			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
				ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)   
			SELECT
				DISTINCT
				src.DepartmentID, 
				src.JobCodeID,  
			    pcg.PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				@ProviderSubsectionID, 
				fm.MonthColumnName,     
				ISNULL(fv.FixedPercentage,1) as FixedPercentage,
				SUM(ISNULL(src.Value, 0)) as Value
			FROM
				[int].[FactStaffing] src
				INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
				INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
					AND fv.JobCodeID = src.JobCodeID           
					AND fv.PayCodeID = src.PayCodeID 
					AND fv.EmployeeID = 0
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
				LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID
			WHERE 
				src.FiscalYearID = @SourceFiscalYearID 
				AND src.TimeClassID = @SourceTimeClassID 
				AND src.IsDeleted = 0 
				AND src.FiscalMonthID != 0 
				AND src.UnitTypeID = 34
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
				AND pc.IsDollarsIgnored = 0 
				AND ps.Description = 'Staffing'
				AND pd.DepartmentID IS NULL
				AND emp.IsFP = 1
			GROUP BY src.DepartmentID,   
				src.JobCodeID,   
				pcg.PayCodeGroupID,
				emp.EmployeeID,
				fm.MonthColumnName,
				FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

			

		END ELSE BEGIN

			IF @UseProviderSource = 0
				BEGIN

					-------------------------------------------------------
					-- BudgetConfig UseProviderSource is disabled
					-------------------------------------------------------

					-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
					INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
					SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
						INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE 			 
					    staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 				
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1

					-- 2. Employees from staffing
					INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
					SELECT DISTINCT	
						CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
						emp.EmployeeID, 
						phys.PhysicianID, 
						CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
						CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
						phys.IsFP
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
						INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
						INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
						INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
						INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE
					    staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 				
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1
						AND ps.Description = 'Staffing'
						AND staff.EmployeeID > 0
						AND emp.NPI NOT IN ('Not Specified', '0', '')
						
					-- Provider from int.FactStaffing
					INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
						ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)   
					SELECT
						DISTINCT
						src.DepartmentID, 
						src.JobCodeID,  
					    pcg.PayCodeGroupID,  
						0 as EmployeeID,
						emp.ProviderID,
						emp.ProviderTypeID,
						emp.ProviderSpecialtyID,
						pc.ProviderLineItemID,
						@ProviderSubsectionID, 
						fm.MonthColumnName,     
						ISNULL(fv.FixedPercentage,1) as FixedPercentage,
						SUM(ISNULL(src.Value, 0)) as Value
					FROM
						[int].[FactStaffing] src
						INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
						INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
						INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
						INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
						LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
							AND fv.JobCodeID = src.JobCodeID           
							AND fv.PayCodeID = src.PayCodeID 
							AND fv.EmployeeID = 0
							AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
					WHERE 
						src.FiscalYearID = @SourceFiscalYearID 
						AND src.TimeClassID = @SourceTimeClassID 
						AND src.IsDeleted = 0 
						AND src.FiscalMonthID != 0 
						AND src.UnitTypeID = 34
						AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
						AND pc.IsDollarsIgnored = 0 
						AND ps.Description = 'Staffing'
						AND emp.IsFP = 1
					GROUP BY src.DepartmentID,   
						src.JobCodeID,   
						pcg.PayCodeGroupID,
						emp.EmployeeID,
						fm.MonthColumnName,
						FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID



				END ELSE BEGIN

					-------------------------------------------------------
					-- BudgetConfig UseProviderSource is enabled
					-------------------------------------------------------

					-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
					INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
					SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
						INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE 			 
						prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1

					-- 2. all employees that are providers
					INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)		
					SELECT DISTINCT 
						CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
						phys.EmployeeID, 
						phys.PhysicianID, 
						CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
						CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
						phys.IsFP
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
						INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
						INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE
						prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1
						AND ps.Description = 'Staffing'
						AND phys.NPI NOT IN ('Not Specified', '0', '')
						
					-- Provider from int.FactProvider
					INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)    		  
					SELECT
						DISTINCT
						fp.DepartmentID, 
						0 as JobCodeID,  
					    0 as PayCodeGroupID,  
						0 as EmployeeID,
						emp.ProviderID,
						emp.ProviderTypeID,
						emp.ProviderSpecialtyID,
						fp.ProviderLineItemID,
						@ProviderSubsectionID, 
						fm.MonthColumnName,     
						1 as FixedPercentage,
						SUM(ISNULL(fp.Value, 0)) as Value
					FROM
						[int].[FactProvider] fp
						INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
						INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
					WHERE 
						fp.FiscalYearID = @SourceFiscalYearID 
						AND fp.TimeClassID = @SourceTimeClassID 
						AND fp.IsDeleted = 0 
						AND fp.FiscalMonthID != 0 
						AND fp.UnitTypeID = 34
						AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
						AND ps.Description = 'Staffing'
						AND emp.IsFP = 1
					GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
						emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

				END

		END

		-- regular staffing
			-- Populate into a temp table before summing up to deal with issues with the dynamic employee join
			SELECT   
				 src.DepartmentID,   
				 src.JobCodeID,  
				 pc.PayCodeID,
				 pc.PayCodeGroupID,   
				 CASE
					WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
					ELSE CASE
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE src.EmployeeID
					END
				 END as EmployeeID,
				 0 AS ProviderID, 
				 0 AS ProviderTypeID, 
				 0 AS ProviderSpecialtyID,
				 0 AS ProviderLineItemID,
				 fm.FiscalMonthID,
				 fm.MonthColumnName,  
				 ISNULL(fv.FixedPercentage, 1) as FixedPercentage,  
				 ISNULL(src.Value, 0) as Value 
			INTO #intFactStaffingWithEmployeeResolvedForProvider  
			FROM [int].[FactStaffing] src     
				INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID      
				INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID   
				LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID
				LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID
				LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID   
				LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
					AND fv.JobCodeID = src.JobCodeID       
					AND fv.PayCodeID = src.PayCodeID 
					AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
							-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
							-- see Jazz-61239 for more details
							WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0
							ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
						END = fv.EmployeeID
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID      
			WHERE src.FiscalYearID = @SourceFiscalYearID 
				AND src.TimeClassID = @SourceTimeClassID 
				AND src.IsDeleted = 0 
				AND src.FiscalMonthID != 0 
				AND src.UnitTypeID = 34 
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
				AND pc.IsDollarsIgnored = 0 
				AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) 

			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
				ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value)    
			SELECT     
				src.DepartmentID,     
				src.JobCodeID,     
				src.PayCodeGroupID,     
				src.EmployeeID,
				0 as ProviderID,
				0 as ProviderTypeID,
				0 as ProviderSpecialtyID,
				0 as ProviderLineItemID,
				@StaffingSubsectionID as SubsectionID,
				src.MonthColumnName,     
				ISNULL(fv.FixedPercentage,1) as FixedPercentage,
				SUM(ISNULL(src.Value, 0)) as Value
			FROM #intFactStaffingWithEmployeeResolvedForProvider src           
				INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID    
				LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID  
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
					AND fv.JobCodeID = src.JobCodeID           
					AND fv.PayCodeID = src.PayCodeID				 				  
					AND fv.EmployeeID = src.EmployeeID
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID                 
			GROUP BY src.DepartmentID,   
				src.JobCodeID,   
				src.PayCodeGroupID,
				src.EmployeeID,
				src.MonthColumnName,
				fv.FixedPercentage
		
	END

	INSERT INTO #IntStaffingData    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value    
	FROM #TempIntStaffingData    
	WHERE FixedPercentage = 1     
     
	INSERT INTO #IntStaffingData    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, 
	CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, 
	ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0))    
	FROM #TempIntStaffingData    
	WHERE FixedPercentage <> 1    
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END   
          
	--JAZZ-75302 - Adjusted dollars for leap year like we already do with hours
	-- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget
	-- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months
	INSERT INTO #WorkingHoursRatioData  
	SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID
	, (wh.Month01 / whSourceYear.Month01)  
	, (wh.Month02 / whSourceYear.Month02)  
	, (wh.Month03 / whSourceYear.Month03)  
	, (wh.Month04 / whSourceYear.Month04)  
	, (wh.Month05 / whSourceYear.Month05)  
	, (wh.Month06 / whSourceYear.Month06)  
	, (wh.Month07 / whSourceYear.Month07)  
	, (wh.Month08 / whSourceYear.Month08)  
	, (wh.Month09 / whSourceYear.Month09)  
	, (wh.Month10 / whSourceYear.Month10)  
	, (wh.Month11 / whSourceYear.Month11)  
	, (wh.Month12 / whSourceYear.Month12)  
	FROM #IntStaffingData fs 
	 	INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID      
	    INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID      
	    INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        
	    INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @SourceFiscalYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)

	UPDATE          
	  fs          
	 SET          
	  SampledBudgetDollars01 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)      
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)        
		  END,      
	  SampledBudgetDollars02 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)       
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)
		  END,          
	  SampledBudgetDollars03 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)       
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)      
		  END,          
	  SampledBudgetDollars04 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)       
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)       
		  END,          
	  SampledBudgetDollars05 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)      
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) 
		  END,          
	  SampledBudgetDollars06 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)       
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)    
		  END,          
	  SampledBudgetDollars07 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)      
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)        
		  END,          
	  SampledBudgetDollars08 = CASE         
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)       
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)       
		  END,          
	  SampledBudgetDollars09 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)       
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)       
		  END,          
	  SampledBudgetDollars10 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)       
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)         
		  END,          
	  SampledBudgetDollars11 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)   
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)
		  END,          
	  SampledBudgetDollars12 = CASE          
	   WHEN VariabilityID = 1          
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)        
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)
		  END          
	 FROM [fp].[Staffing] fs    
	INNER JOIN           
	   (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data          
	  PIVOT          
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv          
	   ON fs.DepartmentID = pv.DepartmentID          
	   AND fs.JobCodeID = pv.JobCodeID          
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID          
	   AND fs.EmployeeID = pv.EmployeeID        
	   AND fs.ProviderID = pv.ProviderID        
	   AND fs.ProviderTypeID = pv.ProviderTypeID        
	   AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID        
	   AND fs.ProviderLineItemID = pv.ProviderLineItemID        
	 WHERE          
	  fs.EntityGroupConfigID = @EntityGroupConfigID      
	  
	IF(@AdjustWageRateByDaysInYear = 1)
	BEGIN
		UPDATE fs
		SET
			SampledBudgetDollars01 = SampledBudgetDollars01 * wh.MonthRatio01,
			SampledBudgetDollars02 = SampledBudgetDollars02 * wh.MonthRatio02,
			SampledBudgetDollars03 = SampledBudgetDollars03 * wh.MonthRatio03,
			SampledBudgetDollars04 = SampledBudgetDollars04 * wh.MonthRatio04,
			SampledBudgetDollars05 = SampledBudgetDollars05 * wh.MonthRatio05,
			SampledBudgetDollars06 = SampledBudgetDollars06 * wh.MonthRatio06,
			SampledBudgetDollars07 = SampledBudgetDollars07 * wh.MonthRatio07,
			SampledBudgetDollars08 = SampledBudgetDollars08 * wh.MonthRatio08,
			SampledBudgetDollars09 = SampledBudgetDollars09 * wh.MonthRatio09,
			SampledBudgetDollars10 = SampledBudgetDollars10 * wh.MonthRatio10,
			SampledBudgetDollars11 = SampledBudgetDollars11 * wh.MonthRatio11,
			SampledBudgetDollars12 = SampledBudgetDollars12 * wh.MonthRatio12
		FROM [fp].[Staffing] fs    
		INNER JOIN #WorkingHoursRatioData wh on wh.DepartmentID = fs.DepartmentID AND wh.JobCodeID = fs.JobCodeID AND wh.PayCodeGroupID = fs.PayCodeGroupID
		INNER JOIN           
		(SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data          
		PIVOT          
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv          
		ON fs.DepartmentID = pv.DepartmentID          
			AND fs.JobCodeID = pv.JobCodeID          
			AND fs.PayCodeGroupID = pv.PayCodeGroupID          
			AND fs.EmployeeID = pv.EmployeeID        
			AND fs.ProviderID = pv.ProviderID        
			AND fs.ProviderTypeID = pv.ProviderTypeID        
			AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID        
			AND fs.ProviderLineItemID = pv.ProviderLineItemID        
		WHERE          
			fs.EntityGroupConfigID = @EntityGroupConfigID
	END
            
	 -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data          
	 IF(@IsAnnualized = 1)           
	 BEGIN          
           
	   SELECT fs.StaffingID,        
		CASE           
		 WHEN @MonthsLoaded = 12 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09 + SampledBudgetDollars10 + SampledBudgetDollars11 + SampledBudgetDollars12       
		 WHEN @MonthsLoaded >= 11 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09 + SampledBudgetDollars10 + SampledBudgetDollars11          
		 WHEN @MonthsLoaded >= 10 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09 + SampledBudgetDollars10          
		 WHEN @MonthsLoaded >= 9 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09           
		 WHEN @MonthsLoaded >= 8 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08          
		 WHEN @MonthsLoaded >= 7 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07          
		 WHEN @MonthsLoaded >= 6 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06          
		 WHEN @MonthsLoaded >= 5 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05           
		 WHEN @MonthsLoaded >= 4 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04          
		 WHEN @MonthsLoaded >= 3 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03          
		 WHEN @MonthsLoaded >= 2 THEN SampledBudgetDollars01 + SampledBudgetDollars02           
		ELSE SampledBudgetDollars01              
		END AS SampledBudgetDollarsTotal          
	   INTO #MonthsLoadedTotal          
			FROM [fp].[Staffing] fs       
				INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID		
		  WHERE fs.EntityGroupConfigID = @EntityGroupConfigID       
       
		-- Staffing section

	   SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.EntityGroupConfigID, h.VariabilityID,          
			mnlt.SampledBudgetDollarsTotal / ytd.YTDHours AS AverageDollars          
		  INTO #dolTemp           
		  FROM [fp].[Staffing] h               
		 INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID          
			  INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID          
			  INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID          
			  INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @BudgetYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)           
			  INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID          
		  WHERE h.EntityGroupConfigID  = @EntityGroupConfigID 
			AND h.SubsectionID = 3 -- Staffing
          
	   UPDATE          
		fs          
	   SET          
		SampledBudgetDollars02 = CASE WHEN @MonthsLoaded >= 2  THEN fs.SampledBudgetDollars02 ELSE AverageDollars * wh.Month02 END,          
		SampledBudgetDollars03 = CASE WHEN @MonthsLoaded >= 3  THEN fs.SampledBudgetDollars03 ELSE AverageDollars * wh.Month03 END,          
		SampledBudgetDollars04 = CASE WHEN @MonthsLoaded >= 4  THEN fs.SampledBudgetDollars04 ELSE AverageDollars * wh.Month04 END,          
		SampledBudgetDollars05 = CASE WHEN @MonthsLoaded >= 5  THEN fs.SampledBudgetDollars05 ELSE AverageDollars * wh.Month05 END,          
		SampledBudgetDollars06 = CASE WHEN @MonthsLoaded >= 6  THEN fs.SampledBudgetDollars06 ELSE AverageDollars * wh.Month06 END,          
		SampledBudgetDollars07 = CASE WHEN @MonthsLoaded >= 7  THEN fs.SampledBudgetDollars07 ELSE AverageDollars * wh.Month07 END,          
		SampledBudgetDollars08 = CASE WHEN @MonthsLoaded >= 8  THEN fs.SampledBudgetDollars08 ELSE AverageDollars * wh.Month08 END,          
		SampledBudgetDollars09 = CASE WHEN @MonthsLoaded >= 9  THEN fs.SampledBudgetDollars09 ELSE AverageDollars * wh.Month09 END,          
		SampledBudgetDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledBudgetDollars10 ELSE AverageDollars * wh.Month10 END,          
		SampledBudgetDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledBudgetDollars11 ELSE AverageDollars * wh.Month11 END,          
		SampledBudgetDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledBudgetDollars12 ELSE AverageDollars * wh.Month12 END          
	   FROM [fp].[Staffing] fs           
		INNER JOIN #dolTemp fte ON fs.DepartmentID = fte.DepartmentID and fs.JobCodeID = fte.JobCodeID and fs.PayCodeGroupID = fte.PayCodeGroupID and fs.EmployeeID = fte.EmployeeID and fs.EntityGroupConfigID = fte.EntityGroupConfigID AND fs.VariabilityID = fte.VariabilityID          
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID          
		   INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID          
		   INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)            
	   WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID        
			AND fs.SubsectionID = 3 -- Staffing
         
		-- Provider Compensation section

		-- per stackoverflow (per MY)
		DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
		DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
		DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded)
        	
		UPDATE fs
		SET
			-- not doing month 1 because it wouldn't really make sense to annualize without at least 1 month of actual data
			SampledBudgetDollars02 = CASE WHEN @MonthsLoaded < 2 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars02 END,
			SampledBudgetDollars03 = CASE WHEN @MonthsLoaded < 3 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars03 END,
			SampledBudgetDollars04 = CASE WHEN @MonthsLoaded < 4 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars04 END,
			SampledBudgetDollars05 = CASE WHEN @MonthsLoaded < 5 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars05 END,
			SampledBudgetDollars06 = CASE WHEN @MonthsLoaded < 6 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars06 END,
			SampledBudgetDollars07 = CASE WHEN @MonthsLoaded < 7 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars07 END,
			SampledBudgetDollars08 = CASE WHEN @MonthsLoaded < 8 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars08 END,
			SampledBudgetDollars09 = CASE WHEN @MonthsLoaded < 9 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars09 END,
			SampledBudgetDollars10 = CASE WHEN @MonthsLoaded < 10 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars10 END,
			SampledBudgetDollars11 = CASE WHEN @MonthsLoaded < 11 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars11 END,
			SampledBudgetDollars12 = CASE WHEN @MonthsLoaded < 12 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars12 END
		FROM [fp].[Staffing] fs
			INNER JOIN #MonthsLoadedTotal dt ON dt.StaffingID = fs.StaffingID
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			AND fs.SubsectionID = 4 -- Provider Compensation

	 END          
           
           
END
GO


---------------------------------------------

-- fp.procSampleStaffingOriginalBudgetHours
CREATE     PROCEDURE [fp].[procSampleStaffingOriginalBudgetHours]      	
	@EntityGroupConfigGUID uniqueidentifier,      
	@EntityGroupConfigID int,      
	@CurrentFiscalYearID smallint,    
	@BudgetYearID smallint,      
	@SourceFiscalYearID smallint,      
	@SourceTimeClassID tinyint,      
	@MonthsLoaded int, 
	@IsEmployeeBudgeting bit,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS     
BEGIN
/**************************************************************
** Change History
**************************************************************
** CID Date       Author   WI   	      Description
** 4 	2021-03-22 NT	       JAZZ-15374  Use NPI instead of EmployeID for Provider Comp Sampling
** 5 	2021-06-30 BW	       JAZZ-21627  Update selects and group by for EmployeID for variablity
** 6 	2021-12-01 OP	       JAZZ-29466  removed empty users check for prov comp data
** 7	2022-01-11 OP	       JAZZ-30834  sampling provider data 
** 8 	2022-02-14 BK	       JAZZ-33248  respect department setting for employee budgeting
** 9 	2022-03-02 MZ	       JAZZ-30547  improved checks in order to sample valid Employees with valid NPI
** 10	2022-03-18 AO	       JAZZ-33623  hours always sample fixed
** 11	2022-08-08 BK	       JAZZ-38357  Make sure IsFP records are correctly sampled depending on if true or false
** 12	2022-10-07 AO	       JAZZ-42868  Non-provider department samples correct staffing values when provider sampling feature is turned on.
** 13	2022-11-07 MZ	       JAZZ-35951  Add EmployeeID to FactStaffingVariabilityDetail
** 15	2022-12-12 DM	       JAZZ-46455  Samplimg of Provider Type and Provider Specialty is linked to Section Setup

** 16  2023-08-22 JB       JAZZ-59251  Use ProductiveClassID = 4 instead of Dollars-Only string to accommodate internationalization
** 17  2023-09-26 BK       JAZZ-61239  Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing
** 18  2023-09-27 BK       JAZZ-61239  Fix incorrect ProductiveClass = 4
** 19  2023-09-30 BK       JAZZ-60973  Update for new data structure
** 20  2023-12-26 NH/NT    JAZZ-64324  Remove 'Use Hours and FTE on Provider Compensation (doing this in restructure branch on behalf of Softserve)
** 21  2024-01-31 NH       JAZZ-64064  Move Provider Planning FF as a setting in Plan Config
** 22  2024-03-25 MY       JAZZ-69661  Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
** 23  2024-06-18 MZ       JAZZ-72231  Added Source Provider Sampling
*************************************************************/

/***********************************************************************************************

NOTE----Any change to this proc likely will need to be changed in procApplyVariabilityToStaffing 

************************************************************************************************/
      
	DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)      
	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;
	
	DECLARE @UseProviderSource BIT;
	DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT;
	DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID) 

	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

	SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID

	DECLARE @ProviderSubsectionID INT;
	SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' 
  
	IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE   #TempIntStaffingData
	IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp
	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable
	IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData  
	IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData  
	IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData  
	IF OBJECT_ID('tempdb..#MonthsLoadedTotal') IS NOT NULL DROP TABLE #MonthsLoadedTotal  
	IF OBJECT_ID('tempdb..#fteTemp') IS NOT NULL DROP TABLE #fteTemp  
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved  
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider  

	CREATE TABLE #TempIntStaffingData (  
		DepartmentID int,  
		JobCodeID int,  
		PayCodeGroupID int,  
		EmployeeID int, 
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int,  
		MonthColumnName varchar(50),  
		FixedPercentage decimal(19,4),  
		Value decimal (19,4)  
	) 

	CREATE TABLE #IntStaffingData (  
		DepartmentID int,  
		JobCodeID int,  
		PayCodeGroupID int,  
		EmployeeID int, 
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int,  -- we'll need this eventually, plus we should make sure we're joining on it
		MonthColumnName varchar(50),  
		FixedPercentage decimal(19,4),  
		Value decimal (19,4)  
	)

	CREATE TABLE #WorkingHoursRatioData (  
		DepartmentID int,  
		JobCodeID int,  
		PayCodeGroupID int,  
		MonthRatio01 decimal(19,8),  
		MonthRatio02 decimal (19,8),  
		MonthRatio03 decimal (19,8),  
		MonthRatio04 decimal (19,8),  
		MonthRatio05 decimal (19,8),  
		MonthRatio06 decimal (19,8),  
		MonthRatio07 decimal (19,8),  
		MonthRatio08 decimal (19,8),  
		MonthRatio09 decimal (19,8),  
		MonthRatio10 decimal (19,8),  
		MonthRatio11 decimal (19,8),  
		MonthRatio12 decimal (19,8)   
	) 
	  
	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END

	IF @IsProviderPlanningEnabled = 0 
	BEGIN

		--------------------------------------
		-- Provider Disabled
		--------------------------------------
		-- Resolve EmployeeID up front so we don't have to do it every time.
		SELECT
			src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeID,   
			CASE
			WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
			END as EmployeeID,
			0 AS ProviderID, 
			0 AS ProviderTypeID, 
			0 AS ProviderSpecialtyID, 
			0 AS ProviderLineItemID,
			src.FiscalYearID,
			src.TimeClassID,
			src.UnitTypeID,
			src.FiscalMonthID,
			src.IsDeleted,
			Value
		INTO #intFactStaffingWithEmployeeResolved
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0.
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID 
		WHERE src.FiscalYearID = @SourceFiscalYearID   
			AND src.TimeClassID = @SourceTimeClassID   
			AND src.IsDeleted = 0   
			AND src.FiscalMonthID != 0   
			AND src.UnitTypeID = 51 

		INSERT INTO #TempIntStaffingData  
	 	SELECT   
			 src.DepartmentID,   
			 src.JobCodeID,   
			 pc.PayCodeGroupID,   
			 src.EmployeeID,
			 0 AS ProviderID, 
			 0 AS ProviderTypeID, 
			 0 AS ProviderSpecialtyID, 
			 0 AS ProviderLineItemID,
			 fm.MonthColumnName,  
			 ISNULL(fv.FixedPercentage, 1) as FixedPercentage,  
			 SUM(ISNULL(src.Value, 0)) as Value      
		FROM #intFactStaffingWithEmployeeResolved src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID      
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID      
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved
						-- see Jazz-61239 for more details
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID     
		WHERE src.FiscalYearID = @SourceFiscalYearID   
			AND src.TimeClassID = @SourceTimeClassID   
			AND src.IsDeleted = 0   
			AND src.FiscalMonthID != 0   
			AND src.UnitTypeID = 51   
			AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))      
			AND pc.IsHoursIgnored = 0 
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			pc.PayCodeGroupID,
			src.EmployeeID,
			fm.MonthColumnName,
			FixedPercentage

	END ELSE BEGIN

		--------------------------------------
		-- Provider Enabled
		--------------------------------------

		IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
		IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept
		IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims
		CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT)
		CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)
		CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT)   
		
		DECLARE @IsProviderTypeDisabled BIT;
		SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

	
		DECLARE @IsProviderSpecialtyDisabled BIT;
		SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

		-- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
		DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 
						   FROM fp.BudgetConfigSetting setting 
						      INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
						   WHERE def.Name = 'Enable Department Level Provider For Sampling'
						     AND setting.BudgetConfigID = @BudgetConfigID
			  				  AND setting.Value = 1), 0)

		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN
			-- Get all departments that use Provider Staffing
			-- Get all employees that are providers
			-- (not doing this step for anything other than dollars yet) Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling
			-- Sample regular data for non provider employees and departments that are not configured to use provider sampling
			
			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 
				staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
				emp.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
			    INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
				INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID
			WHERE 
				staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0			
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = bc.BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')
			UNION		
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
				phys.EmployeeID, 
				phys.PhysicianID,
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')
			    
			-- Provider from int.FactProvider
			INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)    		  
			SELECT
				DISTINCT
				fp.DepartmentID, 
				0 as JobCodeID,  
				0 as PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fp.ProviderLineItemID,
				fm.MonthColumnName,     
				1 as FixedPercentage,
				SUM(ISNULL(fp.Value, 0)) as Value
			FROM
				[int].[FactProvider] fp
				INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
			WHERE 
				fp.FiscalYearID = @SourceFiscalYearID 
				AND fp.TimeClassID = @SourceTimeClassID 
				AND fp.IsDeleted = 0 
				AND fp.FiscalMonthID != 0 
				AND fp.UnitTypeID = 51
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
				AND ps.Description = 'Staffing'
				AND emp.IsFP = 1
			GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID


			INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData

			-- Provider from int.FactStaffing
			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
				ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)   
			SELECT
				DISTINCT
				src.DepartmentID, 
				src.JobCodeID,  
				pcg.PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				fm.MonthColumnName,     
				1 as FixedPercentage,
				SUM(ISNULL(src.Value, 0)) as Value
			FROM
				[int].[FactStaffing] src
				INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
				INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
					AND fv.JobCodeID = src.JobCodeID           
					AND fv.PayCodeID = src.PayCodeID            
					AND fv.EmployeeID = 0
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
				LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID
			WHERE 
				src.FiscalYearID = @SourceFiscalYearID 
				AND src.TimeClassID = @SourceTimeClassID 
				AND src.IsDeleted = 0 
				AND src.FiscalMonthID != 0 
				AND src.UnitTypeID = 51
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
				AND pc.IsHoursIgnored = 0 
				AND ps.Description = 'Staffing'
				AND pd.DepartmentID IS NULL
				AND emp.IsFP = 1
			GROUP BY src.DepartmentID,   
				src.JobCodeID,   
				pcg.PayCodeGroupID,
				emp.EmployeeID,
				fm.MonthColumnName,
				FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

		END ELSE BEGIN

			-------------------------------------------------------
			-- BudgetConfigSetting is enabled
			-------------------------------------------------------

			IF @UseProviderSource = 0
			BEGIN
				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is disabled
				-------------------------------------------------------

				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 
					staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID 
					AND staff.IsDeleted = 0
					AND staff.FiscalMonthID != 0
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

				-- 2. Employees from staffing
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
					emp.EmployeeID, 
					phys.PhysicianID, 
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				    INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
					INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
					INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID
				WHERE 
					staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID 
					AND staff.IsDeleted = 0
					AND staff.FiscalMonthID != 0			
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = bc.BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND staff.EmployeeID > 0
					AND emp.NPI NOT IN ('Not Specified', '0', '')

				-- Provider from int.FactStaffing
				INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
					ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)   
				SELECT
					DISTINCT
					src.DepartmentID, 
					src.JobCodeID,  
					pcg.PayCodeGroupID,  
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					pc.ProviderLineItemID,
					fm.MonthColumnName,     
					1 as FixedPercentage,
					SUM(ISNULL(src.Value, 0)) as Value
				FROM
					[int].[FactStaffing] src
					INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
					INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
					INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
					LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
						AND fv.JobCodeID = src.JobCodeID           
						AND fv.PayCodeID = src.PayCodeID            
						AND fv.EmployeeID = 0
						AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
				WHERE 
					src.FiscalYearID = @SourceFiscalYearID 
					AND src.TimeClassID = @SourceTimeClassID 
					AND src.IsDeleted = 0 
					AND src.FiscalMonthID != 0 
					AND src.UnitTypeID = 51
					AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
					AND pc.IsHoursIgnored = 0 
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
				GROUP BY src.DepartmentID,   
					src.JobCodeID,   
					pcg.PayCodeGroupID,
					emp.EmployeeID,
					fm.MonthColumnName,
					FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

			END ELSE BEGIN
				
				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is enabled
				-------------------------------------------------------

				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

				-- 2. all employees that are providers
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
					phys.EmployeeID, 
					phys.PhysicianID,
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
					INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND phys.NPI NOT IN ('Not Specified', '0', '')
				    

				-- Provider from int.FactProvider
				INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)    		  
				SELECT
					DISTINCT
					fp.DepartmentID, 
					0 as JobCodeID,  
					0 as PayCodeGroupID,  
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					fp.ProviderLineItemID,
					fm.MonthColumnName,     
					1 as FixedPercentage,
					SUM(ISNULL(fp.Value, 0)) as Value
				FROM
					[int].[FactProvider] fp
					INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID   			
				WHERE 
					fp.FiscalYearID = @SourceFiscalYearID 
					AND fp.TimeClassID = @SourceTimeClassID 
					AND fp.IsDeleted = 0 
					AND fp.FiscalMonthID != 0 
					AND fp.UnitTypeID = 51
					AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))          
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
				GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
					emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

			END

		END
		

		

		-- Populate into a temp table before summing up to deal with issues with the dynamic employee join
		SELECT   
			 src.DepartmentID,   
			 src.JobCodeID,  
			 pc.PayCodeID,
			 pc.PayCodeGroupID,   
			 CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
			 END as EmployeeID,
			 0 AS ProviderID, 
			 0 AS ProviderTypeID, 
			 0 AS ProviderSpecialtyID,
			 0 AS ProviderLineItemID,
			 fm.FiscalMonthID,
			 fm.MonthColumnName,  
			 ISNULL(fv.FixedPercentage, 1) as FixedPercentage,  
			 ISNULL(src.Value, 0) as Value 
		INTO #intFactStaffingWithEmployeeResolvedForProvider  
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID      
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID   
			LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID   
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID      
		WHERE src.FiscalYearID = @SourceFiscalYearID   
			AND src.TimeClassID = @SourceTimeClassID   
			AND src.IsDeleted = 0   
			AND src.FiscalMonthID != 0   
			AND src.UnitTypeID = 51   
			AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))      
			AND pc.IsHoursIgnored = 0 
			AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0)))

		-- any other staffing data that doesn't meet previous requirements comes from int.FactStaffing
		INSERT INTO #TempIntStaffingData  
		SELECT   
			 src.DepartmentID,   
			 src.JobCodeID,   
			 src.PayCodeGroupID,   
			 src.EmployeeID,
			 0 AS ProviderID, 
			 0 AS ProviderTypeID, 
			 0 AS ProviderSpecialtyID, 
			 0 AS ProviderLineItemID,
			 src.MonthColumnName,  
			 ISNULL(fv.FixedPercentage, 1) as FixedPercentage,  
			 SUM(ISNULL(src.Value, 0)) as Value      
		FROM #intFactStaffingWithEmployeeResolvedForProvider src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID   
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND fv.EmployeeID = src.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID  
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeGroupID,
			src.EmployeeID,
			src.MonthColumnName,
			fv.FixedPercentage

	END
	
	INSERT INTO #IntStaffingData  
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value  
	FROM #TempIntStaffingData  
	WHERE FixedPercentage = 1   
   
	INSERT INTO #IntStaffingData  
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, 
		CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, 
		ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0))  
	FROM #TempIntStaffingData  
	WHERE FixedPercentage <> 1  
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END
	
	-- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget
	-- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months
	INSERT INTO #WorkingHoursRatioData  
	SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID
	, (wh.Month01 / whSourceYear.Month01)  
	, (wh.Month02 / whSourceYear.Month02)  
	, (wh.Month03 / whSourceYear.Month03)  
	, (wh.Month04 / whSourceYear.Month04)  
	, (wh.Month05 / whSourceYear.Month05)  
	, (wh.Month06 / whSourceYear.Month06)  
	, (wh.Month07 / whSourceYear.Month07)  
	, (wh.Month08 / whSourceYear.Month08)  
	, (wh.Month09 / whSourceYear.Month09)  
	, (wh.Month10 / whSourceYear.Month10)  
	, (wh.Month11 / whSourceYear.Month11)  
	, (wh.Month12 / whSourceYear.Month12)  
	FROM #IntStaffingData fs 
	 	INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID      
	    INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID      
	    INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        
	    INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @SourceFiscalYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        
           
  -- Make sure to multiply by the ratio of working hours for the target year / working hours for the source year to ensure that hours are adjusted properly for leap year
  -- Only February should ever have a difference (unless the client defines the working hours for another month as varying between years)
  UPDATE fs      
  SET      
  SampledBudgetHours01 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month01, 0)  * wh.MonthRatio01
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month01, 0) * wh.MonthRatio01     
      END,      
  SampledBudgetHours02 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month02, 0)  * wh.MonthRatio02
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month02, 0) * wh.MonthRatio02    
      END,      
  SampledBudgetHours03 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month03, 0) * wh.MonthRatio03
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month03, 0) * wh.MonthRatio03  
      END,      
  SampledBudgetHours04 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month04, 0) * wh.MonthRatio04
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month04, 0) * wh.MonthRatio04
      END,      
  SampledBudgetHours05 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month05, 0) * wh.MonthRatio05
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month05, 0) * wh.MonthRatio05
      END,      
  SampledBudgetHours06 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month06, 0) * wh.MonthRatio06
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month06, 0) * wh.MonthRatio06  
      END,      
  SampledBudgetHours07 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month07, 0) * wh.MonthRatio07
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month07, 0) * wh.MonthRatio07  
      END,      
  SampledBudgetHours08 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month08, 0) * wh.MonthRatio08
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month08, 0) * wh.MonthRatio08 
      END,      
  SampledBudgetHours09 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month09, 0) * wh.MonthRatio09
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month09, 0) * wh.MonthRatio09
      END,      
  SampledBudgetHours10 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month10, 0) * wh.MonthRatio10
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month10, 0) * wh.MonthRatio10
      END,      
  SampledBudgetHours11 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month11, 0) * wh.MonthRatio11
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month11, 0) * wh.MonthRatio11
      END,      
  SampledBudgetHours12 = CASE      
   WHEN VariabilityID = 1      
    THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month12, 0) * wh.MonthRatio12
             ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month12, 0) * wh.MonthRatio12
      END    
 FROM      
  [fp].[Staffing] fs      
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID     
        INNER JOIN #WorkingHoursRatioData wh on wh.DepartmentID = fs.DepartmentID AND wh.JobCodeID = fs.JobCodeID AND wh.PayCodeGroupID = fs.PayCodeGroupID
        INNER JOIN       
  (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data      
  PIVOT      
  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv      
   ON fs.DepartmentID = pv.DepartmentID      
   AND fs.JobCodeID = pv.JobCodeID      
   AND fs.PayCodeGroupID = pv.PayCodeGroupID     
   AND fs.EmployeeID = pv.EmployeeID   
   AND fs.ProviderID = pv.ProviderID   
   AND fs.ProviderTypeID = pv.ProviderTypeID   
   AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID   
   AND fs.ProviderLineItemID = pv.ProviderLineItemID   
 WHERE      
  fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.ProductiveClassID <> 4
      
 -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data      
 IF(@IsAnnualized = 1)       
 BEGIN      
        
      
   SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.VariabilityID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID,      
    CASE       
     WHEN @MonthsLoaded = 12 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09 + SampledBudgetHours10 + SampledBudgetHours11 + SampledBudgetHours12      
     WHEN @MonthsLoaded >= 11 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09 + SampledBudgetHours10 + SampledBudgetHours11      
     WHEN @MonthsLoaded >= 10 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09 + SampledBudgetHours10      
     WHEN @MonthsLoaded >= 9 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09       
     WHEN @MonthsLoaded >= 8 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08      
     WHEN @MonthsLoaded >= 7 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07      
     WHEN @MonthsLoaded >= 6 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06      
     WHEN @MonthsLoaded >= 5 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05       
     WHEN @MonthsLoaded >= 4 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04      
     WHEN @MonthsLoaded >= 3 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03      
     WHEN @MonthsLoaded >= 2 THEN SampledBudgetHours01 + SampledBudgetHours02       
    ELSE SampledBudgetHours01          
    END AS SampledBudgetTotal      
   INTO #MonthsLoadedTotal      
        FROM [fp].[Staffing] fs      
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
     WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
            
   -- figure out ftes...      
   SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.EntityGroupConfigID, h.VariabilityID,      
        mnlt.SampledBudgetTotal / ytd.YTDHours AS AverageFTE      
      INTO #fteTemp       
      FROM [fp].[Staffing] h          
		  INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID      -- don't need to join #filterTable here because #MonthsLoadedTotal already has that filtered
          INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID    
          INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID      
          INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @BudgetYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)       
          INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID      
      WHERE h.EntityGroupConfigID  = @EntityGroupConfigID       
      
 UPDATE      
    fs      
   SET      
    SampledBudgetHours02 = CASE WHEN @MonthsLoaded >= 2  THEN fs.SampledBudgetHours02 ELSE AverageFTE * wh.Month02 END,      
    SampledBudgetHours03 = CASE WHEN @MonthsLoaded >= 3  THEN fs.SampledBudgetHours03 ELSE AverageFTE * wh.Month03 END,      
    SampledBudgetHours04 = CASE WHEN @MonthsLoaded >= 4  THEN fs.SampledBudgetHours04 ELSE AverageFTE * wh.Month04 END,      
    SampledBudgetHours05 = CASE WHEN @MonthsLoaded >= 5  THEN fs.SampledBudgetHours05 ELSE AverageFTE * wh.Month05 END,      
    SampledBudgetHours06 = CASE WHEN @MonthsLoaded >= 6  THEN fs.SampledBudgetHours06 ELSE AverageFTE * wh.Month06 END,      
    SampledBudgetHours07 = CASE WHEN @MonthsLoaded >= 7  THEN fs.SampledBudgetHours07 ELSE AverageFTE * wh.Month07 END,      
    SampledBudgetHours08 = CASE WHEN @MonthsLoaded >= 8  THEN fs.SampledBudgetHours08 ELSE AverageFTE * wh.Month08 END,      
    SampledBudgetHours09 = CASE WHEN @MonthsLoaded >= 9  THEN fs.SampledBudgetHours09 ELSE AverageFTE * wh.Month09 END,      
    SampledBudgetHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledBudgetHours10 ELSE AverageFTE * wh.Month10 END,      
    SampledBudgetHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledBudgetHours11 ELSE AverageFTE * wh.Month11 END,      
    SampledBudgetHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledBudgetHours12 ELSE AverageFTE * wh.Month12 END      
   FROM [fp].[Staffing] fs       
    INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID	
    INNER JOIN #fteTemp fte ON fs.DepartmentID = fte.DepartmentID and fs.JobCodeID = fte.JobCodeID and fs.PayCodeGroupID = fte.PayCodeGroupID and fs.EmployeeID = fte.EmployeeID 
		AND fs.EntityGroupConfigID = fte.EntityGroupConfigID AND fs.VariabilityID = fte.VariabilityID AND fs.ProviderID = fte.ProviderID   
	    AND fs.ProviderTypeID = fte.ProviderTypeID   
	    AND fs.ProviderSpecialtyID = fte.ProviderSpecialtyID   
	    AND fs.ProviderLineItemID = fte.ProviderLineItemID    
    INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID      
       INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID      
       INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        
   WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID
                  
 END      
       
 -- spread hours so that FTEs remain flat for fixed job codes      
 -- figure out ftes...      
 SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.EntityGroupConfigID, h.VariabilityID, --h.SampledBudgetTotal / wh.MonthYearly AS AverageFTE      
        ((h.SampledBudgetHours01 / wh.MonthYearly) +      
         (h.SampledBudgetHours02 / wh.MonthYearly) +      
         (h.SampledBudgetHours03 / wh.MonthYearly) +      
         (h.SampledBudgetHours04 / wh.MonthYearly) +      
         (h.SampledBudgetHours05 / wh.MonthYearly) +      
         (h.SampledBudgetHours06 / wh.MonthYearly) +      
         (h.SampledBudgetHours07 / wh.MonthYearly) +      
         (h.SampledBudgetHours08 / wh.MonthYearly) +      
         (h.SampledBudgetHours09 / wh.MonthYearly) +      
         (h.SampledBudgetHours10 / wh.MonthYearly) +      
         (h.SampledBudgetHours11 / wh.MonthYearly) +      
         (h.SampledBudgetHours12 / wh.MonthYearly)) AS AverageFTE      
    INTO #flatFteTemp       
        FROM [fp].[Staffing] h      
		  INNER JOIN #filterTable tmp on h.DepartmentID = tmp.DepartmentID
          LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID       
          INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID      
          INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID      
          INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)      
        WHERE h.EntityGroupConfigID = @EntityGroupConfigID AND (h.VariabilityID = 1 OR exc.PayCodeGroupID IS NOT NULL)
       
 -- now back into hours      
 UPDATE      
  fs      
 SET      
  InitialBudgetHours01 = AverageFTE * wh.Month01,      
  InitialBudgetHours02 = AverageFTE * wh.Month02,      
  InitialBudgetHours03 = AverageFTE * wh.Month03,      
  InitialBudgetHours04 = AverageFTE * wh.Month04,      
  InitialBudgetHours05 = AverageFTE * wh.Month05,      
  InitialBudgetHours06 = AverageFTE * wh.Month06,      
  InitialBudgetHours07 = AverageFTE * wh.Month07,      
  InitialBudgetHours08 = AverageFTE * wh.Month08,      
  InitialBudgetHours09 = AverageFTE * wh.Month09,      
  InitialBudgetHours10 = AverageFTE * wh.Month10,      
  InitialBudgetHours11 = AverageFTE * wh.Month11,      
  InitialBudgetHours12 = AverageFTE * wh.Month12       
   FROM [fp].[Staffing] fs       
     INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
     LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID                 
	 INNER JOIN #flatFteTemp fte ON fs.DepartmentID = fte.DepartmentID and fs.JobCodeID = fte.JobCodeID and fs.PayCodeGroupID = fte.PayCodeGroupID and fs.EmployeeID = fte.EmployeeID 
		and fs.VariabilityID = fte.VariabilityID and fs.EntityGroupConfigID = fte.EntityGroupConfigID        
		AND fs.ProviderID = fte.ProviderID   
		AND fs.ProviderTypeID = fte.ProviderTypeID   
		AND fs.ProviderSpecialtyID = fte.ProviderSpecialtyID   
		AND fs.ProviderLineItemID = fte.ProviderLineItemID   
   INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID      
     INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID      
     INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)             
 WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.VariabilityID = 1 OR exc.PayCodeGroupID IS NOT NULL)
      
       
 -- update the initial values to be equal to the sampled values for variable job codes      
 UPDATE      
  fs      
 SET      
  InitialBudgetHours01 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours02 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours03 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours04 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours05 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours06 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours07 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours08 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours09 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours10 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours11 = SampledBudgetHoursTotal/12,      
  InitialBudgetHours12 = SampledBudgetHoursTotal - (SampledBudgetHoursTotal/12 * 11)      
 FROM [fp].[Staffing] fs      
     INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
     LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID              
 WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.VariabilityID = 2 AND exc.PayCodeGroupID IS NULL
             
       
END
GO


---------------------------------------------

-- fp.procSampleStaffingOriginalProjectionDollars
CREATE   PROCEDURE [fp].[procSampleStaffingOriginalProjectionDollars]    
	@EntityGroupConfigGUID uniqueidentifier,    
	@EntityGroupConfigID int,    
	@CurrentFiscalYearID smallint,    
	@MonthsLoaded int,
	@IsEmployeeBudgeting bit,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE    
AS    
BEGIN  
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author   WI   		 Description
** 4 	2021-03-22 NT  	    JAZZ-15374	 Use NPI instead of EmployeID for Provider Comp Sampling
** 5 	2021-06-30 BW  	    JAZZ-21627	 Update selects and group by for EmployeID for variablity
** 6    2021-12-01 OP       JAZZ-29466	 removed empty users check for prov comp data
** 7    2022-02-14 BK       JAZZ-33248	 respect department setting for employee budgeting
** 8 	2022-03-02 MZ		JAZZ-30547	 improved checks in order to sample valid Employees with valid NPI
** 9    2022-08-08 BK       JAZZ-38357	 Make sure IsFP records are correctly sampled depending on if true or false
** 10   2022-10-07 AO       JAZZ-42868	 Non-provider department samples correct staffing values when provider sampling feature is turned on.
** 11   2022-11-07 MZ		JAZZ-35344   improved checks in order to sample valid Employees with valid NPI from FactProvider
** 12	11-7-2022  MY       JAZZ-35951	 Add EmployeeID to FactStaffingVariabilityDetail
** 13	2022-12-12 DM		JAZZ-46455   Samplimg of Provider Type and Provider Specialty is linked to Section Setup
** 14	2023-09-26 BK		JAZZ-61239   Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing
** 15	2023-09-30 BK		JAZZ-60973   Update for new data structure
** 16	2024-01-31 NH		JAZZ-64064   Move Provider Planning FF as a setting in Plan Config
** 17   2024-03-25 MY       JAZZ-69661	 Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
** 18   2024-06-18 MZ       JAZZ-72231   Added Source Provider Sampling
** 19  2024-08-12  MD			JAZZ-75302   Adjust dollars for leap year
*************************************************************/

	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable	
	IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData
	IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved  
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider  
	IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END

	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;
	
	DECLARE @UseProviderSource BIT;
	DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT;
	DECLARE @AdjustWageRateByDaysInYear BIT = 0;
	DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID)    

	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

	SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID

	SELECT @AdjustWageRateByDaysInYear = ISNULL(Value,0) FROM fp.BudgetConfigSetting bcs
	INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
	WHERE Name = 'Adjust Wage Rate by Days in Year' AND BudgetConfigID = @BudgetConfigID

	CREATE TABLE #IntStaffingData (
		DepartmentID int,
		JobCodeID int,
		PayCodeGroupID int,
		EmployeeID int,
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
		MonthColumnName varchar(50),
		FixedPercentage decimal(19,4),
		Value decimal (19,4)
	)
	CREATE TABLE #TempIntStaffingData (    
		DepartmentID int,    
		JobCodeID int,    
		PayCodeGroupID int,    
		EmployeeID int, 
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int,  
		MonthColumnName varchar(50),    
		FixedPercentage decimal(19,4),    
		Value decimal (19,4)    
	)

	CREATE TABLE #WorkingHoursRatioData (  
		DepartmentID int,  
		JobCodeID int,  
		PayCodeGroupID int,  
		MonthRatio01 decimal(19,8),  
		MonthRatio02 decimal (19,8),  
		MonthRatio03 decimal (19,8),  
		MonthRatio04 decimal (19,8),  
		MonthRatio05 decimal (19,8),  
		MonthRatio06 decimal (19,8),  
		MonthRatio07 decimal (19,8),  
		MonthRatio08 decimal (19,8),  
		MonthRatio09 decimal (19,8),  
		MonthRatio10 decimal (19,8),  
		MonthRatio11 decimal (19,8),  
		MonthRatio12 decimal (19,8)   
	) 

	IF @IsProviderPlanningEnabled = 0 
	BEGIN

		-----------------------------------
		-- Provider Disabled
		-----------------------------------
		-- Resolve EmployeeID up front so we don't have to do it every time.
		SELECT
			src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeID,   
			CASE
			WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
			END as EmployeeID,
			0 AS ProviderID, 
			0 AS ProviderTypeID, 
			0 AS ProviderSpecialtyID, 
			0 AS ProviderLineItemID,
			src.FiscalYearID,
			src.TimeClassID,
			src.UnitTypeID,
			src.FiscalMonthID,
			src.IsDeleted,
			Value
		INTO #intFactStaffingWithEmployeeResolved
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- see Jazz-61239 for more details
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID  
		WHERE src.FiscalYearID = @CurrentFiscalYearID 
			AND src.TimeClassID = 1 
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 34 

		INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
			ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value) 
		SELECT 
			src.DepartmentID, 
			src.JobCodeID, 
			pc.PayCodeGroupID, 
			src.EmployeeID, 
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			0 as SubsectionID,
			fm.MonthColumnName, 
			ISNULL(fv.FixedPercentage, 1) as FixedPercentage,
			SUM(ISNULL(src.Value, 0)) as Value
		FROM #intFactStaffingWithEmployeeResolved src   
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID 
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID    
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID    
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID     
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved
						-- see Jazz-61239 for more details
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID       
		WHERE src.FiscalYearID = @CurrentFiscalYearID 
			AND src.TimeClassID = 1 
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 34 
			AND fm.SortOrder <= @MonthsLoaded    
			AND pc.IsDollarsIgnored = 0    
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			pc.PayCodeGroupID,
			src.EmployeeID, 
			fm.MonthColumnName,
			FixedPercentage

	END ELSE BEGIN

		-----------------------------------
		-- Provider Enabled
		-----------------------------------

		IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
		IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept
		IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims
		
		CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT)
		CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)
		CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT)
		DECLARE @StaffingSubsectionID INT;
		DECLARE @ProviderSubsectionID INT;
		SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' 
		SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider'
		
		DECLARE @IsProviderTypeDisabled BIT;
		SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

	
		DECLARE @IsProviderSpecialtyDisabled BIT;
		SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

		-- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
		DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 
						   FROM fp.BudgetConfigSetting setting 
						      INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
						   WHERE def.Name = 'Enable Department Level Provider For Sampling'
						     AND setting.BudgetConfigID = @BudgetConfigID
			  				  AND setting.Value = 1), 0)

		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN
			
			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
				emp.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID		
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE  
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0			
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')
			UNION		
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
				phys.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')
				
			-- Provider from int.FactProvider
			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
				ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)   
			SELECT
				DISTINCT
				fp.DepartmentID, 
				0 as JobCodeID,  
			    0 as PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				fp.ProviderLineItemID,
				@ProviderSubsectionID, 
				fm.MonthColumnName,     
				1 as FixedPercentage,
				SUM(ISNULL(fp.Value, 0)) as Value
			FROM
				[int].[FactProvider] fp
				INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID        	
			WHERE 
				fp.FiscalYearID = @CurrentFiscalYearID 
				AND fp.TimeClassID = 1 
				AND fp.IsDeleted = 0 
				AND fp.FiscalMonthID != 0 
				AND fp.UnitTypeID = 34
				AND fm.SortOrder <= @MonthsLoaded      
				AND ps.Description = 'Staffing'
				AND emp.IsFP = 1
			GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
				emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

			INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData
			
			-- Provider from int.FactStaffing
			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
				ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)   
			SELECT
				DISTINCT
				src.DepartmentID, 
				src.JobCodeID,  
			    pcg.PayCodeGroupID,  
				0 as EmployeeID,
				emp.ProviderID,
				emp.ProviderTypeID,
				emp.ProviderSpecialtyID,
				pc.ProviderLineItemID,
				@ProviderSubsectionID, 
				fm.MonthColumnName,     
				ISNULL(fv.FixedPercentage,1) as FixedPercentage,
				SUM(ISNULL(src.Value, 0)) as Value
			FROM
				[int].[FactStaffing] src
				INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
				INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
				INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
					AND fv.JobCodeID = src.JobCodeID           
					AND fv.PayCodeID = src.PayCodeID            
					AND fv.EmployeeID = 0
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
				LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID
			WHERE 
				src.FiscalYearID = @CurrentFiscalYearID 
				AND src.TimeClassID = 1 
				AND src.IsDeleted = 0 
				AND src.FiscalMonthID != 0 
				AND src.UnitTypeID = 34
				AND fm.SortOrder <= @MonthsLoaded           
				AND pc.IsDollarsIgnored = 0 
				AND ps.Description = 'Staffing'
				AND pd.DepartmentID IS NULL
				AND emp.IsFP = 1
			GROUP BY src.DepartmentID,   
				src.JobCodeID,   
				pcg.PayCodeGroupID,
				emp.EmployeeID,
				fm.MonthColumnName,
				FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

		END ELSE BEGIN

			IF @UseProviderSource = 0
				BEGIN

					-------------------------------------------------------
					-- BudgetConfig UseProviderSource is disabled
					-------------------------------------------------------

					-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
					INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
					SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
						INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE 
						staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
						AND staff.IsDeleted = 0
						AND staff.FiscalMonthID != 0
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1

					-- 2. Employees from staffing
					INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
					SELECT DISTINCT 
						CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
						emp.EmployeeID, 
						phys.PhysicianID, 
						CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
						CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
						phys.IsFP
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID		
						INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
						INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
						INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
						INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE  
						staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
						AND staff.IsDeleted = 0
						AND staff.FiscalMonthID != 0			
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1
						AND ps.Description = 'Staffing'
						AND staff.EmployeeID > 0
						AND emp.NPI NOT IN ('Not Specified', '0', '')
						
		
					-- Provider from int.FactStaffing
					INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
						ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)   
					SELECT
						DISTINCT
						src.DepartmentID, 
						src.JobCodeID,  
					    pcg.PayCodeGroupID,  
						0 as EmployeeID,
						emp.ProviderID,
						emp.ProviderTypeID,
						emp.ProviderSpecialtyID,
						pc.ProviderLineItemID,
						@ProviderSubsectionID, 
						fm.MonthColumnName,     
						ISNULL(fv.FixedPercentage,1) as FixedPercentage,
						SUM(ISNULL(src.Value, 0)) as Value
					FROM
						[int].[FactStaffing] src
						INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
						INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
						INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
						INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
						LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
							AND fv.JobCodeID = src.JobCodeID           
							AND fv.PayCodeID = src.PayCodeID            
							AND fv.EmployeeID = 0
							AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
					WHERE 
						src.FiscalYearID = @CurrentFiscalYearID 
						AND src.TimeClassID = 1 
						AND src.IsDeleted = 0 
						AND src.FiscalMonthID != 0 
						AND src.UnitTypeID = 34
						AND fm.SortOrder <= @MonthsLoaded           
						AND pc.IsDollarsIgnored = 0 
						AND ps.Description = 'Staffing'
						AND emp.IsFP = 1
					GROUP BY src.DepartmentID,   
						src.JobCodeID,   
						pcg.PayCodeGroupID,
						emp.EmployeeID,
						fm.MonthColumnName,
						FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID


				END ELSE BEGIN

					-------------------------------------------------------
					-- BudgetConfig UseProviderSource is enabled
					-------------------------------------------------------

					-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
					INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
					SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
						INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE 			 
						prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1

					-- 2. all employees that are providers
					INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)		
					SELECT DISTINCT 
						CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
						phys.EmployeeID, 
						phys.PhysicianID, 
						CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
						CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,  
						phys.IsFP
					FROM [fp].[DepartmentLevelConfiguration] config  
						INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
						INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
						INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
						INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
						INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
						INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					WHERE
						prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
						AND egc.EntityGroupConfigID = @EntityGroupConfigID
						AND config.BudgetConfigID = @BudgetConfigID
						AND config.IsUsingProviderStaffing = 1
						AND ps.Description = 'Staffing'
						AND phys.NPI NOT IN ('Not Specified', '0', '')
						
					-- Provider from int.FactProvider
					INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
						ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value)   
					SELECT
						DISTINCT
						fp.DepartmentID, 
						0 as JobCodeID,  
					    0 as PayCodeGroupID,  
						0 as EmployeeID,
						emp.ProviderID,
						emp.ProviderTypeID,
						emp.ProviderSpecialtyID,
						fp.ProviderLineItemID,
						@ProviderSubsectionID, 
						fm.MonthColumnName,     
						1 as FixedPercentage,
						SUM(ISNULL(fp.Value, 0)) as Value
					FROM
						[int].[FactProvider] fp
						INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
						INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
						INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID        	
					WHERE 
						fp.FiscalYearID = @CurrentFiscalYearID 
						AND fp.TimeClassID = 1 
						AND fp.IsDeleted = 0 
						AND fp.FiscalMonthID != 0 
						AND fp.UnitTypeID = 34
						AND fm.SortOrder <= @MonthsLoaded      
						AND ps.Description = 'Staffing'
						AND emp.IsFP = 1
					GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
						emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

				END

		END

		

		-- Populate into a temp table before summing up to deal with issues with the dynamic employee join
		SELECT   
			 src.DepartmentID,   
			 src.JobCodeID,  
			 pc.PayCodeID,
			 pc.PayCodeGroupID,   
			 CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
			 END as EmployeeID,
			 0 AS ProviderID, 
			 0 AS ProviderTypeID, 
			 0 AS ProviderSpecialtyID,
			 0 AS ProviderLineItemID,
			 fm.FiscalMonthID,
			 fm.MonthColumnName,  
			 ISNULL(fv.FixedPercentage, 1) as FixedPercentage,  
			 ISNULL(src.Value, 0) as Value 
		INTO #intFactStaffingWithEmployeeResolvedForProvider  
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID          
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID          
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID  
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID           
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- see Jazz-61239 for more details
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID       
		WHERE src.FiscalYearID = @CurrentFiscalYearID 
			AND src.TimeClassID = 1
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 34 
			AND fm.SortOrder <= @MonthsLoaded      
			AND pc.IsDollarsIgnored = 0 
			AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0)))  

		INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
			ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value)    
		SELECT     
			src.DepartmentID,     
			src.JobCodeID,     
			src.PayCodeGroupID,     
			src.EmployeeID, 
			0 as ProviderID,
			0 as ProviderTypeID,
			0 as ProviderSpecialtyID,
			0 as ProviderLineItemID,
			@StaffingSubsectionID as SubsectionID,
			src.MonthColumnName,     
			ISNULL(fv.FixedPercentage,1) as FixedPercentage,
			SUM(ISNULL(src.Value, 0)) as Value
		FROM #intFactStaffingWithEmployeeResolvedForProvider src           
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID  
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID  
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID           
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved
						-- see Jazz-61239 for more details
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeGroupID,
			src.EmployeeID,
			src.MonthColumnName,
			fv.FixedPercentage
	END
	
	INSERT INTO #IntStaffingData    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value    
	FROM #TempIntStaffingData    
	WHERE FixedPercentage = 1     
     
	INSERT INTO #IntStaffingData    
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, 
	CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID,
	ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0))    
	FROM #TempIntStaffingData    
	WHERE FixedPercentage <> 1    
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END      

	-- Get Budget Year, since that is what we will need to check against for the ratio
	-- in the main Original Hours proc, Sampled values were adjusted to reflect any difference in leap year/not leap year hours, so we need to adjust again
	DECLARE @BudgetYearID INT
	SELECT TOP 1 @BudgetYearID = FiscalYearID FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID
    
	-- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget
	-- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months
	INSERT INTO #WorkingHoursRatioData  
	   SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID
	   , (wh.Month01 / whSourceYear.Month01)  
	   , (wh.Month02 / whSourceYear.Month02)  
	   , (wh.Month03 / whSourceYear.Month03)  
	   , (wh.Month04 / whSourceYear.Month04)  
	   , (wh.Month05 / whSourceYear.Month05)  
	   , (wh.Month06 / whSourceYear.Month06)  
	   , (wh.Month07 / whSourceYear.Month07)  
	   , (wh.Month08 / whSourceYear.Month08)  
	   , (wh.Month09 / whSourceYear.Month09)  
	   , (wh.Month10 / whSourceYear.Month10)  
	   , (wh.Month11 / whSourceYear.Month11)  
	   , (wh.Month12 / whSourceYear.Month12)  
	FROM 
	 (SELECT DISTINCT f.DepartmentID, JobCodeID, PayCodeGroupID FROM fp.Staffing f
			INNER JOIN #filterTable tmp on f.DepartmentID = tmp.DepartmentID
	        WHERE f.EntityGroupConfigID = @EntityGroupConfigID
	 ) fs 
 		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID      
		INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID      
    	INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @CurrentFiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        
		INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @BudgetYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        


	 -- set all of the values from the source fy/tc    
	UPDATE    
	  fs    
	 SET    
	  SampledProjectionDollars01 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)    
		  END,    
	  SampledProjectionDollars02 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)    
		  END,    
	  SampledProjectionDollars03 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)    
		  END,    
	  SampledProjectionDollars04 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)    
		  END,    
	  SampledProjectionDollars05 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)    
		  END,    
	  SampledProjectionDollars06 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)    
		  END,    
	  SampledProjectionDollars07 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)    
		  END,    
	  SampledProjectionDollars08 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)    
		  END,    
	  SampledProjectionDollars09 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)    
		  END,    
	  SampledProjectionDollars10 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)    
		  END,    
	  SampledProjectionDollars11 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)    
		  END,    
	  SampledProjectionDollars12 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)    
		  END    
	 FROM    
	  [fp].[Staffing] fs    
			INNER JOIN     
	   (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data    
	  PIVOT    
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv    
	   ON fs.DepartmentID = pv.DepartmentID    
	   AND fs.JobCodeID = pv.JobCodeID    
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID    
	   AND fs.EmployeeID = pv.EmployeeID  
	   AND fs.ProviderID = pv.ProviderID        
	   AND fs.ProviderTypeID = pv.ProviderTypeID        
	   AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID        
	   AND fs.ProviderLineItemID = pv.ProviderLineItemID   
	 WHERE    
	  fs.EntityGroupConfigID = @EntityGroupConfigID    

	IF(@AdjustWageRateByDaysInYear = 1)
	BEGIN
		UPDATE    
		  fs    
		 SET    
		  SampledProjectionDollars02 = CASE WHEN @MonthsLoaded < 2  THEN SampledBudgetDollars02 * wh.MonthRatio02  ELSE SampledProjectionDollars02 END,    
		  SampledProjectionDollars03 = CASE WHEN @MonthsLoaded < 3  THEN SampledBudgetDollars03 * wh.MonthRatio03  ELSE SampledProjectionDollars03 END,    
		  SampledProjectionDollars04 = CASE WHEN @MonthsLoaded < 4  THEN SampledBudgetDollars04 * wh.MonthRatio04  ELSE SampledProjectionDollars04 END,    
		  SampledProjectionDollars05 = CASE WHEN @MonthsLoaded < 5  THEN SampledBudgetDollars05 * wh.MonthRatio05  ELSE SampledProjectionDollars05 END,    
		  SampledProjectionDollars06 = CASE WHEN @MonthsLoaded < 6  THEN SampledBudgetDollars06 * wh.MonthRatio06  ELSE SampledProjectionDollars06 END,    
		  SampledProjectionDollars07 = CASE WHEN @MonthsLoaded < 7  THEN SampledBudgetDollars07 * wh.MonthRatio07  ELSE SampledProjectionDollars07 END,    
		  SampledProjectionDollars08 = CASE WHEN @MonthsLoaded < 8  THEN SampledBudgetDollars08 * wh.MonthRatio08  ELSE SampledProjectionDollars08 END,    
		  SampledProjectionDollars09 = CASE WHEN @MonthsLoaded < 9  THEN SampledBudgetDollars09 * wh.MonthRatio09  ELSE SampledProjectionDollars09 END,    
		  SampledProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudgetDollars10 * wh.MonthRatio10  ELSE SampledProjectionDollars10 END,    
		  SampledProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudgetDollars11 * wh.MonthRatio11  ELSE SampledProjectionDollars11 END,    
		  SampledProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudgetDollars12 * wh.MonthRatio12  ELSE SampledProjectionDollars12 END    
		 FROM [fp].[Staffing] fs
			INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
			INNER JOIN #WorkingHoursRatioData wh ON fs.DepartmentID = wh.DepartmentID AND fs.JobCodeID = wh.JobCodeID AND fs.PayCodeGroupID = wh.PayCodeGroupID
			WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
	END 
	ELSE
	BEGIN
		   -- copy the baseline data over for months without data (month sort order > @MonthsLoaded)    
			UPDATE    
			  fs    
			 SET    
			  SampledProjectionDollars02 = CASE WHEN @MonthsLoaded < 2  THEN SampledBudgetDollars02 ELSE SampledProjectionDollars02 END,    
			  SampledProjectionDollars03 = CASE WHEN @MonthsLoaded < 3  THEN SampledBudgetDollars03 ELSE SampledProjectionDollars03 END,    
			  SampledProjectionDollars04 = CASE WHEN @MonthsLoaded < 4  THEN SampledBudgetDollars04 ELSE SampledProjectionDollars04 END,    
			  SampledProjectionDollars05 = CASE WHEN @MonthsLoaded < 5  THEN SampledBudgetDollars05 ELSE SampledProjectionDollars05 END,    
			  SampledProjectionDollars06 = CASE WHEN @MonthsLoaded < 6  THEN SampledBudgetDollars06 ELSE SampledProjectionDollars06 END,    
			  SampledProjectionDollars07 = CASE WHEN @MonthsLoaded < 7  THEN SampledBudgetDollars07 ELSE SampledProjectionDollars07 END,    
			  SampledProjectionDollars08 = CASE WHEN @MonthsLoaded < 8  THEN SampledBudgetDollars08 ELSE SampledProjectionDollars08 END,    
			  SampledProjectionDollars09 = CASE WHEN @MonthsLoaded < 9  THEN SampledBudgetDollars09 ELSE SampledProjectionDollars09 END,    
			  SampledProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudgetDollars10 ELSE SampledProjectionDollars10 END,    
			  SampledProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudgetDollars11 ELSE SampledProjectionDollars11 END,    
			  SampledProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudgetDollars12 ELSE SampledProjectionDollars12 END    
			 FROM [fp].[Staffing] fs
				INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
				WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
	END
        																		  
END
GO


---------------------------------------------

-- fp.procSampleStaffingOriginalProjectionHours
CREATE   PROCEDURE [fp].[procSampleStaffingOriginalProjectionHours]    
 @EntityGroupConfigGUID uniqueidentifier,    
 @EntityGroupConfigID int,    
 @CurrentFiscalYearID smallint,    
 @MonthsLoaded int,
 @IsEmployeeBudgeting bit,
 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS    
BEGIN 
	/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI				Description
	 ** 4 	 2021-03-22  NT  	 JAZZ-15374		Use NPI instead of EmployeID for Provider Comp Sampling
	 ** 5 	 2021-06-30  BW  	 JAZZ-21627		Update selects and group by for EmployeID for variablity
	 ** 6 	 2021-12-01  OP		 JAZZ-29466		removed empty users check for prov comp data
	 ** 7	 2022-01-11  OP		 JAZZ-30834		sampled provider data for hours
	 ** 8    2022-02-14  BK      JAZZ-33248		respect department setting for employee budgeting
	 ** 9 	 2022-03-02  MZ		 JAZZ-30547		improved checks in order to sample valid Employees with valid NPI
	 ** 10   2022-03-18  AO      JAZZ-33623		hours always sample fixed
	 ** 11	 2022-08-08  BK		 JAZZ-38357		Make sure IsFP records are correctly sampled depending on if true or false
	 ** 12   2022-10-07  AO      JAZZ-42868		Non-provider department samples correct staffing values when provider sampling feature is turned on.
	 ** 13   2022-11-07  MZ		 JAZZ-35344		improved checks in order to sample valid Employees with valid NPI from FactProvider
	 ** 14	 11-7-2022   MY      JAZZ-35951		Add EmployeeID to FactStaffingVariabilityDetail
	 ** 15	 2022-12-12  DM		 JAZZ-46455     Samplimg of Provider Type and Provider Specialty is linked to Section Setup
	 ** 16	 2023-02-16  BK		 JAZZ-50052     Fix for if no Current Year Actuals exist for dimensionality that was sampled from another baseline
	 **                                         the working hour ratio was missing when copying SampledBudget to Proj for Months Not Loaded
	 **                                         We are also not flattening the SampledProjection Months Not Loaded data when updating InitialProjecton
	 ** 17	 2023-08-22  BK		 JAZZ-59251     Use ProductiveClassID = 4 instead of Dollars-Only string to accommodate internationalization
	 ** 18	 2023-09-26  BK		 JAZZ-61239     Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing
	 ** 19	 2023-09-30  BK		 JAZZ-60973     Update for data restructure
	 ** 20	 2023-12-26 NH/NT    JAZZ-64324     Remove 'Use Hours and FTE on Provider Compensation (doing this in restructure branch on behalf of Softserve)
	 ** 21	 2024-01-31  NH		 JAZZ-64064     Move Provider Planning FF as a setting in Plan Config
	 ** 22   2024-03-25  MY      JAZZ-69661		Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
	 ** 23	 2024-06-19  AO		 JAZZ-72231		Added Source Provider Sampling
	 *************************************************************/

	DECLARE @IsProviderPlanningEnabled BIT, @BaselineTimeClassID INT, @BaselineFiscalYearID INT;
	DECLARE @UseProviderSource BIT;
	DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT;

	SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs
		INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID
		INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = bcs.BudgetConfigID
		INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID
	WHERE bcds.Name = 'Sample Provider either from Staffing or Provider int tables' AND egc.EntityGroupConfigID = @EntityGroupConfigID

	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	SELECT @BaselineTimeClassID = PayrollTimeClassID, @BaselineFiscalYearID = PayrollFiscalYearID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID;
	
	DECLARE @StaffingSubsectionID INT;
	DECLARE @ProviderSubsectionID INT;
	SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' 
	SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider'

	IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE   #TempIntStaffingData
	IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp
	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable
	IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData
	IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData
	IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved  
	IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider  

    CREATE TABLE #TempIntStaffingData (  
		DepartmentID int,  
		JobCodeID int,  
		PayCodeGroupID int,  
		EmployeeID int, 
		ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int,  -- we'll need this eventually, plus we should make sure we're joining on it
		MonthColumnName varchar(50),  
		FixedPercentage decimal(19,4),  
		Value decimal (19,4)  
    ) 

	CREATE TABLE #IntStaffingData (
		DepartmentID int,
		JobCodeID int,
		PayCodeGroupID int,
		EmployeeID int,
	    ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int,
		MonthColumnName varchar(50),
		FixedPercentage decimal(19,4),
		Value decimal (19,4)
	)

	CREATE TABLE #WorkingHoursRatioData (  
		DepartmentID int,  
		JobCodeID int,  
		PayCodeGroupID int,  
		MonthRatio01 decimal(19,8),  
		MonthRatio02 decimal (19,8),  
		MonthRatio03 decimal (19,8),  
		MonthRatio04 decimal (19,8),  
		MonthRatio05 decimal (19,8),  
		MonthRatio06 decimal (19,8),  
		MonthRatio07 decimal (19,8),  
		MonthRatio08 decimal (19,8),  
		MonthRatio09 decimal (19,8),  
		MonthRatio10 decimal (19,8),  
		MonthRatio11 decimal (19,8),  
		MonthRatio12 decimal (19,8)   
	) 

	CREATE TABLE #filterTable (DepartmentID int)
	INSERT INTO #filterTable (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #filterTable (DepartmentID)
		SELECT DISTINCT DepartmentID
		FROM fp.Staffing 
		WHERE EntityGroupConfigID = @EntityGroupConfigID
	END

	IF @IsProviderPlanningEnabled = 0 
	BEGIN

		-----------------------------------------
		-- Provider Disabled
		-----------------------------------------
		-- Resolve EmployeeID up front so we don't have to do it every time.
		SELECT
			src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeID,   
			CASE
			WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
			END as EmployeeID,
			0 AS ProviderID, 
			0 AS ProviderTypeID, 
			0 AS ProviderSpecialtyID, 
			0 AS ProviderLineItemID,
			src.FiscalYearID,
			src.TimeClassID,
			src.UnitTypeID,
			src.FiscalMonthID,
			src.IsDeleted,
			Value
		INTO #intFactStaffingWithEmployeeResolved
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0.
						-- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data
						-- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved
						-- see Jazz-61239 for more details						
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID 
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID 

		INSERT INTO #TempIntStaffingData  
		SELECT 
			src.DepartmentID, 
			src.JobCodeID, 
			pc.PayCodeGroupID, 
			src.EmployeeID, 
			0 AS ProviderID, 0 AS ProviderTypeID, 0 AS ProviderSpecialtyID, 0 AS ProviderLineItemID,
			fm.MonthColumnName, 
			ISNULL(fv.FixedPercentage, 1) as FixedPercentage,
			SUM(ISNULL(src.Value, 0)) as Value  
		FROM #intFactStaffingWithEmployeeResolved src    
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID    
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID       
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID     
				AND fv.PayCodeID = src.PayCodeID 
				AND src.EmployeeID = fv.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID 
		WHERE src.FiscalYearID = @CurrentFiscalYearID 
			AND src.TimeClassID = 1 
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 51 
			AND fm.SortOrder <= @MonthsLoaded    
			AND pc.IsHoursIgnored = 0  
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			pc.PayCodeGroupID,
			src.EmployeeID,
			fm.MonthColumnName,
			FixedPercentage

	END ELSE BEGIN

		-----------------------------------------
		-- Provider Enabled
		-----------------------------------------

		IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims
		IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
		IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept

		CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT)
		CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)
		CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT)

		DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID)    

		DECLARE @IsProviderTypeDisabled BIT;
		SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;


		DECLARE @IsProviderSpecialtyDisabled BIT;
		SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
								SELECT *
								FROM fp.SectionSetup ss
													INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
													WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
								 )
								THEN CAST(1 AS BIT)
								ELSE CAST(0 AS BIT) END;

		-- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning
		DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 
						   FROM fp.BudgetConfigSetting setting 
						      INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
						   WHERE def.Name = 'Enable Department Level Provider For Sampling'
						     AND setting.BudgetConfigID = @BudgetConfigID
			  				  AND setting.Value = 1), 0)

		-- Get all departments that use Provider Staffing
		-- Get all employees that are providers
		-- This step is only for dollars for now - Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling
		-- Sample regular data for non provider employees and departments that are not configured to use provider sampling

		IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0
		BEGIN
			
			-------------------------------------------------------
			-- BudgetConfigSetting is disabled
			-------------------------------------------------------
			-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing
			INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
			SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID
			WHERE 
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = bc.BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
			UNION
			SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE 			 
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1

			-- 2. all employees that are providers
			INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
				emp.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, 
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
				INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
				INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
				INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID
			WHERE 
				staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
				AND staff.IsDeleted = 0
				AND staff.FiscalMonthID != 0			
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = bc.BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND staff.EmployeeID > 0
				AND emp.NPI NOT IN ('Not Specified', '0', '')	
			UNION		
			SELECT DISTINCT 
				CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
				phys.EmployeeID, 
				phys.PhysicianID, 
				CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
				CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,
				phys.IsFP
			FROM [fp].[DepartmentLevelConfiguration] config  
				INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
				INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
				INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
				INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
				INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
				INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			WHERE
				prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
				AND egc.EntityGroupConfigID = @EntityGroupConfigID
				AND config.BudgetConfigID = @BudgetConfigID
				AND config.IsUsingProviderStaffing = 1
				AND ps.Description = 'Staffing'
				AND phys.NPI NOT IN ('Not Specified', '0', '')

			INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
					ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)   
				SELECT
					DISTINCT
					fp.DepartmentID, 
					0 as JobCodeID,  
					0 as PayCodeGroupID,  
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					fp.ProviderLineItemID,
					fm.MonthColumnName,     
					1 as FixedPercentage,
					SUM(ISNULL(fp.Value, 0)) as Value
				FROM
					[int].[FactProvider] fp
					INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID        	
				WHERE 
					fp.FiscalYearID = @CurrentFiscalYearID 
					AND fp.TimeClassID = 1 
					AND fp.IsDeleted = 0 
					AND fp.FiscalMonthID != 0 
					AND fp.UnitTypeID = 51
					AND fm.SortOrder <= @MonthsLoaded      
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
				GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
					emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

				INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData

				INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
					ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)   
				SELECT
					DISTINCT
					src.DepartmentID, 
					src.JobCodeID,  
					pcg.PayCodeGroupID,  
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					pc.ProviderLineItemID,
					fm.MonthColumnName,     
					1 as FixedPercentage,
					SUM(ISNULL(src.Value, 0)) as Value
				FROM
					[int].[FactStaffing] src
					INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
					INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
					INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
					LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
						AND fv.JobCodeID = src.JobCodeID           
						AND fv.PayCodeID = src.PayCodeID           
						AND fv.EmployeeID = 0 
						AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
					LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID
				WHERE 
					src.FiscalYearID = @CurrentFiscalYearID 
					AND src.TimeClassID = 1 
					AND src.IsDeleted = 0 
					AND src.FiscalMonthID != 0 
					AND src.UnitTypeID = 51
					AND fm.SortOrder <= @MonthsLoaded           
					AND pc.IsHoursIgnored = 0 
					AND ps.Description = 'Staffing'
					AND pd.DepartmentID IS NULL
					AND emp.IsFP = 1
				GROUP BY src.DepartmentID,   
					src.JobCodeID,   
					pcg.PayCodeGroupID,
					emp.EmployeeID,
					fm.MonthColumnName,
					FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID
		END ELSE BEGIN

			-------------------------------------------------------
			-- BudgetConfigSetting is enabled
			-------------------------------------------------------
			IF @UseProviderSource = 0
			BEGIN

				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is disabled
				-------------------------------------------------------
				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID
				WHERE 
					staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
					AND staff.IsDeleted = 0
					AND staff.FiscalMonthID != 0
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = bc.BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

				-- 2. all employees that are providers
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END,
					emp.EmployeeID, 
					phys.PhysicianID, 
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, 
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID	
					INNER JOIN [dss].[DimPhysician]	phys ON phys.NPI = emp.NPI
					INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
					INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID
				WHERE 
					staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 
					AND staff.IsDeleted = 0
					AND staff.FiscalMonthID != 0			
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = bc.BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND staff.EmployeeID > 0
					AND emp.NPI NOT IN ('Not Specified', '0', '')	

				INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
					ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)   
				SELECT
					DISTINCT
					src.DepartmentID, 
					src.JobCodeID,  
					pcg.PayCodeGroupID,  
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					pc.ProviderLineItemID,
					fm.MonthColumnName,     
					1 as FixedPercentage,
					SUM(ISNULL(src.Value, 0)) as Value
				FROM
					[int].[FactStaffing] src
					INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID  
					INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID  
					INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID  
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID		
					LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
						AND fv.JobCodeID = src.JobCodeID           
						AND fv.PayCodeID = src.PayCodeID           
						AND fv.EmployeeID = 0 
						AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID          	
				WHERE 
					src.FiscalYearID = @CurrentFiscalYearID 
					AND src.TimeClassID = 1 
					AND src.IsDeleted = 0 
					AND src.FiscalMonthID != 0 
					AND src.UnitTypeID = 51
					AND fm.SortOrder <= @MonthsLoaded           
					AND pc.IsHoursIgnored = 0 
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
				GROUP BY src.DepartmentID,   
					src.JobCodeID,   
					pcg.PayCodeGroupID,
					emp.EmployeeID,
					fm.MonthColumnName,
					FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID

			END ELSE BEGIN
				
				-------------------------------------------------------
				-- BudgetConfig UseProviderSource is enabled
				-------------------------------------------------------
				-- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider 
				INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
				SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE 			 
					prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1

				-- 2. all employees from staffing
				INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP)
				SELECT DISTINCT 
					CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, 
					phys.EmployeeID, 
					phys.PhysicianID, 
					CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID,
					CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID,
					phys.IsFP
				FROM [fp].[DepartmentLevelConfiguration] config  
					INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID
					INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID	
					INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID
					INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
				WHERE
					prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 					
					AND egc.EntityGroupConfigID = @EntityGroupConfigID
					AND config.BudgetConfigID = @BudgetConfigID
					AND config.IsUsingProviderStaffing = 1
					AND ps.Description = 'Staffing'
					AND phys.NPI NOT IN ('Not Specified', '0', '')

				INSERT INTO #TempIntStaffingData  (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, 
					ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value)   
				SELECT
					DISTINCT
					fp.DepartmentID, 
					0 as JobCodeID,  
					0 as PayCodeGroupID,  
					0 as EmployeeID,
					emp.ProviderID,
					emp.ProviderTypeID,
					emp.ProviderSpecialtyID,
					fp.ProviderLineItemID,
					fm.MonthColumnName,     
					1 as FixedPercentage,
					SUM(ISNULL(fp.Value, 0)) as Value
				FROM
					[int].[FactProvider] fp
					INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID
					INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID)
					INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID   
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID        	
				WHERE 
					fp.FiscalYearID = @CurrentFiscalYearID 
					AND fp.TimeClassID = 1 
					AND fp.IsDeleted = 0 
					AND fp.FiscalMonthID != 0 
					AND fp.UnitTypeID = 51
					AND fm.SortOrder <= @MonthsLoaded      
					AND ps.Description = 'Staffing'
					AND emp.IsFP = 1
				GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName,
					emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID

			END
		END

		-- Regular staffing
		-- Populate into a temp table before summing up to deal with issues with the dynamic employee join
		SELECT   
				src.DepartmentID,   
				src.JobCodeID,  
				pc.PayCodeID,
				pc.PayCodeGroupID,   
				CASE
				WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0
				ELSE CASE
					WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
					ELSE src.EmployeeID
				END
				END as EmployeeID,
				0 AS ProviderID, 
				0 AS ProviderTypeID, 
				0 AS ProviderSpecialtyID,
				0 AS ProviderLineItemID,
				fm.FiscalMonthID,
				fm.MonthColumnName,  
				ISNULL(fv.FixedPercentage, 1) as FixedPercentage,  
				ISNULL(src.Value, 0) as Value 
		INTO #intFactStaffingWithEmployeeResolvedForProvider  
		FROM [int].[FactStaffing] src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID      
			INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID   
			LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID
			LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID   
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0.
						WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed
						ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not.
					END = fv.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID      
		WHERE src.FiscalYearID = @CurrentFiscalYearID 
			AND src.TimeClassID = 1 
			AND src.IsDeleted = 0 
			AND src.FiscalMonthID != 0 
			AND src.UnitTypeID = 51 
			AND fm.SortOrder <= @MonthsLoaded    
			AND pc.IsHoursIgnored = 0  
			AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0)))
					   
		INSERT INTO #TempIntStaffingData  
			SELECT   
				src.DepartmentID,   
				src.JobCodeID,   
				src.PayCodeGroupID,   
				src.EmployeeID,
				0 AS ProviderID, 
				0 AS ProviderTypeID, 
				0 AS ProviderSpecialtyID, 
				0 AS ProviderLineItemID,
				src.MonthColumnName,  
				ISNULL(fv.FixedPercentage, 1) as FixedPercentage,  
				SUM(ISNULL(src.Value, 0)) as Value      
		FROM #intFactStaffingWithEmployeeResolvedForProvider src     
			INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID
			LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID 
			LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID 
				AND fv.JobCodeID = src.JobCodeID       
				AND fv.PayCodeID = src.PayCodeID 
				AND fv.EmployeeID = src.EmployeeID
				AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID     		
		GROUP BY src.DepartmentID,   
			src.JobCodeID,   
			src.PayCodeGroupID,
			src.EmployeeID,
			src.MonthColumnName,
			fv.FixedPercentage
	END

	INSERT INTO #IntStaffingData
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value
	FROM #TempIntStaffingData
	WHERE FixedPercentage = 1 

	INSERT INTO #IntStaffingData
	SELECT DepartmentID, JobCodeID, PayCodeGroupID, 
		CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, 
		ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0))
	FROM #TempIntStaffingData
	WHERE FixedPercentage <> 1
	GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END   

	-- Get Budget Year, since that is what we will need to check against for the ratio
	-- in the main Original Hours proc, Sampled values were adjusted to reflect any difference in leap year/not leap year hours, so we need to adjust again
	DECLARE @BudgetYearID INT
	SELECT TOP 1 @BudgetYearID = FiscalYearID FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
	WHERE egc.EntityGroupConfigID = @EntityGroupConfigID

	-- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget
	-- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months
	INSERT INTO #WorkingHoursRatioData  
	   SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID
	   , (wh.Month01 / whSourceYear.Month01)  
	   , (wh.Month02 / whSourceYear.Month02)  
	   , (wh.Month03 / whSourceYear.Month03)  
	   , (wh.Month04 / whSourceYear.Month04)  
	   , (wh.Month05 / whSourceYear.Month05)  
	   , (wh.Month06 / whSourceYear.Month06)  
	   , (wh.Month07 / whSourceYear.Month07)  
	   , (wh.Month08 / whSourceYear.Month08)  
	   , (wh.Month09 / whSourceYear.Month09)  
	   , (wh.Month10 / whSourceYear.Month10)  
	   , (wh.Month11 / whSourceYear.Month11)  
	   , (wh.Month12 / whSourceYear.Month12)  
	FROM 
	 (SELECT DISTINCT f.DepartmentID, JobCodeID, PayCodeGroupID FROM fp.Staffing f
			INNER JOIN #filterTable tmp on f.DepartmentID = tmp.DepartmentID
	        WHERE f.EntityGroupConfigID = @EntityGroupConfigID
	 ) fs 
 		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID      
		INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID      
    	INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @CurrentFiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        
		INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @BudgetYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        


	-- set all of the values from the source fy/tc    
	UPDATE    
	  fs    
	 SET    
	  SampledProjectionHours01 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0)    
		  END,    
	  SampledProjectionHours02 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0)    
		  END,    
	  SampledProjectionHours03 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0)    
		  END,    
	  SampledProjectionHours04 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0)    
		  END,    
	  SampledProjectionHours05 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0)    
		  END,    
	  SampledProjectionHours06 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0)    
		  END,    
	  SampledProjectionHours07 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0)    
		  END,    
	  SampledProjectionHours08 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0)    
		  END,    
	  SampledProjectionHours09 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0)    
		  END,    
	  SampledProjectionHours10 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0)    
		  END,    
	  SampledProjectionHours11 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0)    
		  END,    
	  SampledProjectionHours12 = CASE    
	   WHEN VariabilityID = 1    
		THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0)    
				 ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0)    
		  END    
	 FROM    
	  [fp].[Staffing] fs       
			INNER JOIN     
	   (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data    
	  PIVOT    
	  (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv    
	   ON fs.DepartmentID = pv.DepartmentID    
	   AND fs.JobCodeID = pv.JobCodeID    
	   AND fs.PayCodeGroupID = pv.PayCodeGroupID    
	   AND fs.EmployeeID = pv.EmployeeID 
	   AND fs.ProviderID = pv.ProviderID   
	   AND fs.ProviderTypeID = pv.ProviderTypeID   
	   AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID   
	   AND fs.ProviderLineItemID = pv.ProviderLineItemID    
	 WHERE    
	  fs.EntityGroupConfigID = @EntityGroupConfigID    
	  AND fs.ProductiveClassID <> 4

	-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)  
	-- make sure we apply the ratio of projection year / source year to get the correct valu
	UPDATE    
	  fs    
	 SET    
	  SampledProjectionHours02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudgetHours02 * wh.MonthRatio02 ELSE SampledProjectionHours02 END,    
	  SampledProjectionHours03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudgetHours03 * wh.MonthRatio03 ELSE SampledProjectionHours03 END,    
	  SampledProjectionHours04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudgetHours04 * wh.MonthRatio04 ELSE SampledProjectionHours04 END,    
	  SampledProjectionHours05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudgetHours05 * wh.MonthRatio05 ELSE SampledProjectionHours05 END,    
	  SampledProjectionHours06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudgetHours06 * wh.MonthRatio06 ELSE SampledProjectionHours06 END,    
	  SampledProjectionHours07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudgetHours07 * wh.MonthRatio07 ELSE SampledProjectionHours07 END,    
	  SampledProjectionHours08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudgetHours08 * wh.MonthRatio08 ELSE SampledProjectionHours08 END,    
	  SampledProjectionHours09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudgetHours09 * wh.MonthRatio09 ELSE SampledProjectionHours09 END,    
	  SampledProjectionHours10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudgetHours10 * wh.MonthRatio10 ELSE SampledProjectionHours10 END,    
	  SampledProjectionHours11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudgetHours11 * wh.MonthRatio11 ELSE SampledProjectionHours11 END,    
	  SampledProjectionHours12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudgetHours12 * wh.MonthRatio12 ELSE SampledProjectionHours12 END    
	 FROM    
	  [fp].[Staffing] fs 
	  INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID 
	  INNER JOIN #WorkingHoursRatioData wh ON fs.DepartmentID = wh.DepartmentID AND fs.JobCodeID = wh.JobCodeID AND fs.PayCodeGroupID = wh.PayCodeGroupID
	 WHERE    
	  fs.EntityGroupConfigID = @EntityGroupConfigID


	IF @BaselineTimeClassID = 2 AND @BaselineFiscalYearID = @CurrentFiscalYearID BEGIN
		-- We are leaving Months Not Loaded Projection values what the Current Year Budget values are and not flattening the data
	 -- But we do have to potentially readjust for hours if Budget Year is leap year or current year is a leap year
	 IF EXISTS (SELECT 1 FROM #WorkingHoursRatioData WHERE MonthRatio01 <> 1.0 OR MonthRatio02 <> 1.0 OR MonthRatio03 <> 1.0 OR MonthRatio04 <> 1.0 OR MonthRatio05 <> 1.0 OR MonthRatio06<> 1.0 OR 
		                                                   MonthRatio07 <> 1.0 OR MonthRatio08 <> 1.0 OR MonthRatio09 <> 1.0 OR MonthRatio10 <> 1.0 OR MonthRatio11 <> 1.0 OR MonthRatio12 <> 1.0)
			 BEGIN
				 TRUNCATE TABLE #WorkingHoursRatioData

				 INSERT INTO #WorkingHoursRatioData  
				   SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID
				   , (wh.Month01 / whSourceYear.Month01)  
				   , (wh.Month02 / whSourceYear.Month02)  
				   , (wh.Month03 / whSourceYear.Month03)  
				   , (wh.Month04 / whSourceYear.Month04)  
				   , (wh.Month05 / whSourceYear.Month05)  
				   , (wh.Month06 / whSourceYear.Month06)  
				   , (wh.Month07 / whSourceYear.Month07)  
				   , (wh.Month08 / whSourceYear.Month08)  
				   , (wh.Month09 / whSourceYear.Month09)  
				   , (wh.Month10 / whSourceYear.Month10)  
				   , (wh.Month11 / whSourceYear.Month11)  
				   , (wh.Month12 / whSourceYear.Month12)  
				FROM 
				 (SELECT DISTINCT f.DepartmentID, JobCodeID, PayCodeGroupID FROM fp.Staffing f
						INNER JOIN #filterTable tmp on f.DepartmentID = tmp.DepartmentID
						WHERE f.EntityGroupConfigID = @EntityGroupConfigID
				 ) fs 
		 			INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID      
					INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID    
					-- We switch the budget and source here because if the hours were adjusted for leap year when updating SampledBudget then they would need to be set back to the
					-- values for the current year - see example below this statement
		    		INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        
					INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @CurrentFiscalYearID  and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)        

					/* 
		
					Budget Year is 2017, Current Year is 2016 (leap year) 
					Baseline is Current Year Budget 
					February is in MonthsNotLoaded
					Sampled February data for TimeClassID = 2/FiscalYearID = 2016 is 90 for hours
					When we sample, February data for SampledBudget is adjusted to 86.8965 to account for difference in hours between years (so that FTE value is same for both)
					Now we copy Feb's SampledBudget to SampledProjection since we're using CYB
					If we didn't account for leap year, we'd copy 86.8965, but it should be 90
					So we need to apply the ratio back to February's value when copying SampledBudget to SampledProjection for MonthsNotLoaded
					-- Extra note that this will only matter if February is in Months NOT Loaded
		
					*/

		    END

 	  UPDATE    
		fs    
	   SET    
		InitialProjectionHours01 = fs.SampledProjectionHours01,    
		InitialProjectionHours02 = fs.SampledProjectionHours02,
		InitialProjectionHours03 = fs.SampledProjectionHours03,
		InitialProjectionHours04 = fs.SampledProjectionHours04,
		InitialProjectionHours05 = fs.SampledProjectionHours05,
		InitialProjectionHours06 = fs.SampledProjectionHours06,
		InitialProjectionHours07 = fs.SampledProjectionHours07,
		InitialProjectionHours08 = fs.SampledProjectionHours08,
		InitialProjectionHours09 = fs.SampledProjectionHours09,
		InitialProjectionHours10 = fs.SampledProjectionHours10,
		InitialProjectionHours11 = fs.SampledProjectionHours11,
		InitialProjectionHours12 = fs.SampledProjectionHours12
	   FROM [fp].[Staffing] fs 
			-- filter is implicit in #WorkingHoursRatioData so don't need to join on #filterTable
			INNER JOIN #WorkingHoursRatioData wh on fs.DepartmentID = wh.DepartmentID AND wh.JobCodeID = fs.JobCodeID AND wh.PayCodeGroupID = fs.PayCodeGroupID
		WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID

	END ELSE BEGIN
		SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.VariabilityID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID,    
		CASE     
		 WHEN @MonthsLoaded = 12 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09 + SampledProjectionHours10 +  
			   SampledProjectionHours11 + SampledProjectionHours12    
		 WHEN @MonthsLoaded >= 11 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09 + SampledProjectionHours10 + 
			   SampledProjectionHours11    
		 WHEN @MonthsLoaded >= 10 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09 + SampledProjectionHours10   
		  WHEN @MonthsLoaded >= 9 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09     
		 WHEN @MonthsLoaded >= 8 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08    
		 WHEN @MonthsLoaded >= 7 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07    
		 WHEN @MonthsLoaded >= 6 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06    
		 WHEN @MonthsLoaded >= 5 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05     
		 WHEN @MonthsLoaded >= 4 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04    
		 WHEN @MonthsLoaded >= 3 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03    
		 WHEN @MonthsLoaded >= 2 THEN SampledProjectionHours01 + SampledProjectionHours02     
		ELSE SampledProjectionHours01        
		END AS SampledProjectionHoursTotal    
	   INTO #MonthsLoadedTotal    
			FROM [fp].[Staffing] fs   
				INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID 
		  WHERE fs.EntityGroupConfigID = @EntityGroupConfigID

		  -- spread hours so that FTEs remain flat for fixed job codes    
	   -- figure out ftes...    
	   SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.EntityGroupConfigID, h.VariabilityID,    
			mnlt.SampledProjectionHoursTotal / ytd.YTDHours AS AverageFTE    
		  INTO #fteTemp     
		  FROM [fp].[Staffing] h   
			LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID          
			INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID    -- don't need to join #filterTable here because #MonthsLoadedTotal already has that filtered
			  INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID    
			  INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID    
			  INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @CurrentFiscalYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)     
			  INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID    
		  WHERE h.EntityGroupConfigID  = @EntityGroupConfigID AND (exc.PayCodeGroupID IS NOT NULL OR h.VariabilityID = 1) 

	   -- Projected hours should vary by working hours for fixed JobCodes     
	   UPDATE    
		fs    
	   SET    
		InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1  THEN fs.SampledProjectionHours01 ELSE AverageFTE * wh.Month01 END,    
		InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2  THEN fs.SampledProjectionHours02 ELSE AverageFTE * wh.Month02 END,    
		InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3  THEN fs.SampledProjectionHours03 ELSE AverageFTE * wh.Month03 END,    
		InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4  THEN fs.SampledProjectionHours04 ELSE AverageFTE * wh.Month04 END,    
		InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5  THEN fs.SampledProjectionHours05 ELSE AverageFTE * wh.Month05 END,    
		InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6  THEN fs.SampledProjectionHours06 ELSE AverageFTE * wh.Month06 END,    
		InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7  THEN fs.SampledProjectionHours07 ELSE AverageFTE * wh.Month07 END,    
		InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8  THEN fs.SampledProjectionHours08 ELSE AverageFTE * wh.Month08 END,    
		InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9  THEN fs.SampledProjectionHours09 ELSE AverageFTE * wh.Month09 END,    
		InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionHours10 ELSE AverageFTE * wh.Month10 END,    
		InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionHours11 ELSE AverageFTE * wh.Month11 END,    
		InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjectionHours12 ELSE AverageFTE * wh.Month12 END    
	   FROM [fp].[Staffing] fs    
		INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID 
		 LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID      
		INNER JOIN #fteTemp fte ON fs.DepartmentID = fte.DepartmentID AND fs.JobCodeID = fte.JobCodeID AND fs.PayCodeGroupID = fte.PayCodeGroupID AND fs.EmployeeID = fte.EmployeeID 
			AND fs.EntityGroupConfigID = fte.EntityGroupConfigID AND fs.VariabilityID = fte.VariabilityID AND fs.ProviderID = fte.ProviderID   
			AND fs.ProviderTypeID = fte.ProviderTypeID   
			AND fs.ProviderSpecialtyID = fte.ProviderSpecialtyID   
			AND fs.ProviderLineItemID = fte.ProviderLineItemID        
		INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID    
		   INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID    
		   INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @CurrentFiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end)      
	   WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID AND (exc.PayCodeGroupID IS NOT NULL OR fs.VariabilityID = 1)

	   -- Projected hours should be flat for variable Job Codes or PayCodeGroups that have ProductiveClass that is excluded from FTE calcs    
	   UPDATE    
		fs    
	   SET    
		InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1  THEN fs.SampledProjectionHours01 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2  THEN fs.SampledProjectionHours02 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3  THEN fs.SampledProjectionHours03 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4  THEN fs.SampledProjectionHours04 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5  THEN fs.SampledProjectionHours05 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6  THEN fs.SampledProjectionHours06 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7  THEN fs.SampledProjectionHours07 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8  THEN fs.SampledProjectionHours08 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9  THEN fs.SampledProjectionHours09 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionHours10 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionHours11 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END,    
		InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjectionHours12 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END    
	   FROM [fp].[Staffing] fs INNER JOIN #MonthsLoadedTotal t on fs.StaffingID = t.StaffingID    
			INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID 
		  LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID               
	   WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID AND fs.VariabilityID = 2 AND exc.PayCodeGroupID IS NULL
   END
END
GO


---------------------------------------------

-- fp.procSampleStaffingWageRate
CREATE PROCEDURE [fp].[procSampleStaffingWageRate]
  @EntityGroupConfigID int,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
  WITH RECOMPILE
AS
BEGIN
    /**************************************************************
    ** Change History
    **************************************************************
    ** CID  Date        Author  WI			Description
    ** 1	2021-08-25	BW		JAZZ-13122	Performance update per DBA re-write
    ** 2    2022-01-20  OP      JAZZ-31481  Restricted Prov Comp Wage Rate sampling
    ** 3    2023-02-16  BK      JAZZ-50052  Update to copy SampledProjecton to InitialProjection for MonthsNotLoaded when baseline is Current Year Budget
    **                                      instead of getting average of MonthsNotLoaded dollars and hours and flattening the wage rate
    ** 4    2023-09-20  BK      JAZZ-60973  Update for data restructure
    *************************************************************/ 

    CREATE TABLE #filterTable (DepartmentID int)
    INSERT INTO #filterTable (DepartmentID)
    SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
    
    IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL)
    BEGIN
        INSERT INTO #filterTable (DepartmentID)
        SELECT DISTINCT DepartmentID
        FROM fp.Staffing 
        WHERE EntityGroupConfigID = @EntityGroupConfigID
        
    END
    
	DECLARE @MonthsLoaded INT, @StaffingTimeClassID INT, @StaffingFiscalYearID INT, @CurrentFiscalYearID INT
    
    SELECT @MonthsLoaded = MonthsLoaded, @StaffingTimeClassID = PayrollTimeClassID, @StaffingFiscalYearID = PayrollFiscalYearID, @CurrentFiscalYearID = bc.FiscalYearID - 1 FROM fp.EntityGroupConfig egc
    INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID
    WHERE EntityGroupConfigID = @EntityGroupConfigID
     
 
	UPDATE wr SET 
	  wr.SampledBudget01 = COALESCE(NULLIF(fs.SampledBudgetDollars01, 0) / NULLIF(fs.SampledBudgetHours01, 0), 0)
	, wr.SampledBudget02 = COALESCE(NULLIF(fs.SampledBudgetDollars02, 0) / NULLIF(fs.SampledBudgetHours02, 0), 0)
	, wr.SampledBudget03 = COALESCE(NULLIF(fs.SampledBudgetDollars03, 0) / NULLIF(fs.SampledBudgetHours03, 0), 0)
	, wr.SampledBudget04 = COALESCE(NULLIF(fs.SampledBudgetDollars04, 0) / NULLIF(fs.SampledBudgetHours04, 0), 0)
	, wr.SampledBudget05 = COALESCE(NULLIF(fs.SampledBudgetDollars05, 0) / NULLIF(fs.SampledBudgetHours05, 0), 0)
	, wr.SampledBudget06 = COALESCE(NULLIF(fs.SampledBudgetDollars06, 0) / NULLIF(fs.SampledBudgetHours06, 0), 0)
	, wr.SampledBudget07 = COALESCE(NULLIF(fs.SampledBudgetDollars07, 0) / NULLIF(fs.SampledBudgetHours07, 0), 0)
	, wr.SampledBudget08 = COALESCE(NULLIF(fs.SampledBudgetDollars08, 0) / NULLIF(fs.SampledBudgetHours08, 0), 0)
	, wr.SampledBudget09 = COALESCE(NULLIF(fs.SampledBudgetDollars09, 0) / NULLIF(fs.SampledBudgetHours09, 0), 0)
	, wr.SampledBudget10 = COALESCE(NULLIF(fs.SampledBudgetDollars10, 0) / NULLIF(fs.SampledBudgetHours10, 0), 0)
	, wr.SampledBudget11 = COALESCE(NULLIF(fs.SampledBudgetDollars11, 0) / NULLIF(fs.SampledBudgetHours11, 0), 0)
	, wr.SampledBudget12 = COALESCE(NULLIF(fs.SampledBudgetDollars12, 0) / NULLIF(fs.SampledBudgetHours12, 0), 0)
	---
	, wr.SampledProjection01 = COALESCE(NULLIF(fs.SampledProjectionDollars01, 0) / NULLIF(fs.SampledProjectionHours01, 0), 0)
	, wr.SampledProjection02 = COALESCE(NULLIF(fs.SampledProjectionDollars02, 0) / NULLIF(fs.SampledProjectionHours02, 0), 0)
	, wr.SampledProjection03 = COALESCE(NULLIF(fs.SampledProjectionDollars03, 0) / NULLIF(fs.SampledProjectionHours03, 0), 0)
	, wr.SampledProjection04 = COALESCE(NULLIF(fs.SampledProjectionDollars04, 0) / NULLIF(fs.SampledProjectionHours04, 0), 0)
	, wr.SampledProjection05 = COALESCE(NULLIF(fs.SampledProjectionDollars05, 0) / NULLIF(fs.SampledProjectionHours05, 0), 0)
	, wr.SampledProjection06 = COALESCE(NULLIF(fs.SampledProjectionDollars06, 0) / NULLIF(fs.SampledProjectionHours06, 0), 0)
	, wr.SampledProjection07 = COALESCE(NULLIF(fs.SampledProjectionDollars07, 0) / NULLIF(fs.SampledProjectionHours07, 0), 0)
	, wr.SampledProjection08 = COALESCE(NULLIF(fs.SampledProjectionDollars08, 0) / NULLIF(fs.SampledProjectionHours08, 0), 0)
	, wr.SampledProjection09 = COALESCE(NULLIF(fs.SampledProjectionDollars09, 0) / NULLIF(fs.SampledProjectionHours09, 0), 0)
	, wr.SampledProjection10 = COALESCE(NULLIF(fs.SampledProjectionDollars10, 0) / NULLIF(fs.SampledProjectionHours10, 0), 0)
	, wr.SampledProjection11 = COALESCE(NULLIF(fs.SampledProjectionDollars11, 0) / NULLIF(fs.SampledProjectionHours11, 0), 0)
	, wr.SampledProjection12 = COALESCE(NULLIF(fs.SampledProjectionDollars12, 0) / NULLIF(fs.SampledProjectionHours12, 0), 0)
        --
	, wr.InitialBudget01 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget02 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget03 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget04 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget05 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget06 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget07 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget08 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget09 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget10 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget11 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	, wr.InitialBudget12 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0)
	FROM [fp].[StaffingWageRate] wr 
	INNER JOIN (SELECT StaffingWageRateID, 
	SUM(SampledBudgetDollars01) as SampledBudgetDollars01, SUM(SampledBudgetDollars02) as SampledBudgetDollars02, SUM(SampledBudgetDollars03) as SampledBudgetDollars03, SUM(SampledBudgetDollars04) as SampledBudgetDollars04,
	SUM(SampledBudgetDollars05) as SampledBudgetDollars05, SUM(SampledBudgetDollars06) as SampledBudgetDollars06, SUM(SampledBudgetDollars07) as SampledBudgetDollars07, SUM(SampledBudgetDollars08) as SampledBudgetDollars08,
	SUM(SampledBudgetDollars09) as SampledBudgetDollars09, SUM(SampledBudgetDollars10) as SampledBudgetDollars10, SUM(SampledBudgetDollars11) as SampledBudgetDollars11, SUM(SampledBudgetDollars12) as SampledBudgetDollars12,
	SUM(SampledBudgetDollarsTotal) as SampledBudgetDollarsTotal, 
	SUM(SampledBudgetHours01) as SampledBudgetHours01, SUM(SampledBudgetHours02) as SampledBudgetHours02, SUM(SampledBudgetHours03) as SampledBudgetHours03, SUM(SampledBudgetHours04) as SampledBudgetHours04,
	SUM(SampledBudgetHours05) as SampledBudgetHours05, SUM(SampledBudgetHours06) as SampledBudgetHours06, SUM(SampledBudgetHours07) as SampledBudgetHours07, SUM(SampledBudgetHours08) as SampledBudgetHours08,
	SUM(SampledBudgetHours09) as SampledBudgetHours09, SUM(SampledBudgetHours10) as SampledBudgetHours10, SUM(SampledBudgetHours11) as SampledBudgetHours11, SUM(SampledBudgetHours12) as SampledBudgetHours12,
	SUM(SampledBudgetHoursTotal) as SampledBudgetHoursTotal , 
	SUM(SampledProjectionDollars01) as SampledProjectionDollars01, SUM(SampledProjectionDollars02) as SampledProjectionDollars02, SUM(SampledProjectionDollars03) as SampledProjectionDollars03, SUM(SampledProjectionDollars04) as SampledProjectionDollars04,
	SUM(SampledProjectionDollars05) as SampledProjectionDollars05, SUM(SampledProjectionDollars06) as SampledProjectionDollars06, SUM(SampledProjectionDollars07) as SampledProjectionDollars07, SUM(SampledProjectionDollars08) as SampledProjectionDollars08,
	SUM(SampledProjectionDollars09) as SampledProjectionDollars09, SUM(SampledProjectionDollars10) as SampledProjectionDollars10, SUM(SampledProjectionDollars11) as SampledProjectionDollars11, SUM(SampledProjectionDollars12) as SampledProjectionDollars12,
	SUM(SampledProjectionDollarsTotal) as SampledProjectionDollarsTotal, 
	SUM(SampledProjectionHours01) as SampledProjectionHours01, SUM(SampledProjectionHours02) as SampledProjectionHours02, SUM(SampledProjectionHours03) as SampledProjectionHours03, SUM(SampledProjectionHours04) as SampledProjectionHours04,
	SUM(SampledProjectionHours05) as SampledProjectionHours05, SUM(SampledProjectionHours06) as SampledProjectionHours06, SUM(SampledProjectionHours07) as SampledProjectionHours07, SUM(SampledProjectionHours08) as SampledProjectionHours08,
	SUM(SampledProjectionHours09) as SampledProjectionHours09, SUM(SampledProjectionHours10) as SampledProjectionHours10, SUM(SampledProjectionHours11) as SampledProjectionHours11, SUM(SampledProjectionHours12) as SampledProjectionHours12,
	SUM(SampledProjectionHoursTotal) as SampledProjectionHoursTotal
	FROM fp.Staffing fs
	INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID 
	  AND fs.SubsectionID = 3 -- Staffing
	GROUP BY StaffingWageRateID) fs ON fs.StaffingWageRateID = wr.StaffingWageRateID
	
	 

	IF @StaffingTimeClassID = 2 AND @StaffingFiscalYearID = @CurrentFiscalYearID BEGIN
		-- Current Year Budget only
		UPDATE wr    
		SET    
			InitialProjection01 = wr.SampledProjection01,    
			InitialProjection02 = wr.SampledProjection02,
			InitialProjection03 = wr.SampledProjection03,
			InitialProjection04 = wr.SampledProjection04,
			InitialProjection05 = wr.SampledProjection05,
			InitialProjection06 = wr.SampledProjection06,
			InitialProjection07 = wr.SampledProjection07,
			InitialProjection08 = wr.SampledProjection08,
			InitialProjection09 = wr.SampledProjection09,
			InitialProjection10 = wr.SampledProjection10,
			InitialProjection11 = wr.SampledProjection11,
			InitialProjection12 = wr.SampledProjection12
	   FROM [fp].[StaffingWageRate] wr 
	        INNER JOIN fp.Staffing fs ON fs.StaffingWageRateID = wr.StaffingWageRateID
			INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID 
		WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID
		
	END ELSE BEGIN

		CREATE TABLE #Totals (StaffingWageRateID INT, SampledProjectionDollarsTotal DECIMAL(19,8), SampledProjectionHoursTotal DECIMAL(19,8), NewDollars DECIMAL(19,8), NewHours DECIMAL(19,8))
		INSERT INTO #Totals (StaffingWageRateID, SampledProjectionDollarsTotal, SampledProjectionHoursTotal)
		SELECT fs.StaffingWageRateID,
		CASE 
			WHEN @MonthsLoaded = 11 THEN SUM(fs.SampledProjectionDollars12)  
			WHEN @MonthsLoaded = 10 THEN SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 9 THEN SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 8 THEN SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 7 THEN SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 6 THEN SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 5 THEN SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 4 THEN SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 3 THEN SUM(fs.SampledProjectionDollars04) + SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10 ) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 2 THEN SUM(fs.SampledProjectionDollars03) + SUM(fs.SampledProjectionDollars04) + SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12)
			WHEN @MonthsLoaded = 1 THEN SUM(fs.SampledProjectionDollars02) + SUM(fs.SampledProjectionDollars03) + SUM(fs.SampledProjectionDollars04) + SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) 
			ELSE 0 
		END,
		CASE 
			WHEN @MonthsLoaded = 11 THEN SUM(fs.SampledProjectionHours12)  
			WHEN @MonthsLoaded = 10 THEN SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 9 THEN SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 8 THEN SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 7 THEN SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 6 THEN SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 5 THEN SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 4 THEN SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 3 THEN SUM(fs.SampledProjectionHours04) + SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10 ) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 2 THEN SUM(fs.SampledProjectionHours03) + SUM(fs.SampledProjectionHours04) + SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12)
			WHEN @MonthsLoaded = 1 THEN SUM(fs.SampledProjectionHours02) + SUM(fs.SampledProjectionHours03) + SUM(fs.SampledProjectionHours04) + SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) 
			ELSE 0 
		END              

		FROM [fp].[Staffing] fs 
		  INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID 
		WHERE fs.EntityGroupConfigID = @EntityGroupConfigID  AND fs.SubsectionID = 3 -- Staffing Subsection
		GROUP BY StaffingWageRateID

		UPDATE a SET 
		NewHours = SampledProjectionHoursTotal / (12.0 - @MonthsLoaded),
		NewDollars = SampledProjectionDollarsTotal / (12.0 - @MonthsLoaded)
		FROM #Totals a

		UPDATE wr
		SET 
		  InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN wr.SampledProjection01 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN wr.SampledProjection02 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN wr.SampledProjection03 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN wr.SampledProjection04 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN wr.SampledProjection05 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN wr.SampledProjection06 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN wr.SampledProjection07 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN wr.SampledProjection08 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN wr.SampledProjection09 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN wr.SampledProjection10 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN wr.SampledProjection11 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		, InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN wr.SampledProjection12 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END
		FROM [fp].[StaffingWageRate] wr 
	        INNER JOIN #Totals fs ON fs.StaffingWageRateID = wr.StaffingWageRateID
	END 
	
	-- Update all target, budget, and projection adjusted
	UPDATE wr
		SET 
		  TargetAdjusted01 = InitialBudget01
		, TargetAdjusted02 = InitialBudget02
		, TargetAdjusted03 = InitialBudget03
		, TargetAdjusted04 = InitialBudget04
		, TargetAdjusted05 = InitialBudget05
		, TargetAdjusted06 = InitialBudget06
		, TargetAdjusted07 = InitialBudget07
		, TargetAdjusted08 = InitialBudget08
		, TargetAdjusted09 = InitialBudget09
		, TargetAdjusted10 = InitialBudget10
		, TargetAdjusted11 = InitialBudget11
		, TargetAdjusted12 = InitialBudget12
		, BudgetAdjusted01 = InitialBudget01
		, BudgetAdjusted02 = InitialBudget02
		, BudgetAdjusted03 = InitialBudget03
		, BudgetAdjusted04 = InitialBudget04
		, BudgetAdjusted05 = InitialBudget05
		, BudgetAdjusted06 = InitialBudget06
		, BudgetAdjusted07 = InitialBudget07
		, BudgetAdjusted08 = InitialBudget08
		, BudgetAdjusted09 = InitialBudget09
		, BudgetAdjusted10 = InitialBudget10
		, BudgetAdjusted11 = InitialBudget11
		, BudgetAdjusted12 = InitialBudget12
		, ProjectionAdjusted01 = InitialProjection01
		, ProjectionAdjusted02 = InitialProjection02
		, ProjectionAdjusted03 = InitialProjection03
		, ProjectionAdjusted04 = InitialProjection04
		, ProjectionAdjusted05 = InitialProjection05
		, ProjectionAdjusted06 = InitialProjection06
		, ProjectionAdjusted07 = InitialProjection07
		, ProjectionAdjusted08 = InitialProjection08
		, ProjectionAdjusted09 = InitialProjection09
		, ProjectionAdjusted10 = InitialProjection10
		, ProjectionAdjusted11 = InitialProjection11
		, ProjectionAdjusted12 = InitialProjection12
		FROM [fp].[StaffingWageRate] wr 
		INNER JOIN (SELECT StaffingWageRateID 
        FROM fp.Staffing s
		INNER JOIN #filterTable ft on s.DepartmentID = ft.DepartmentID
		WHERE VariabilityID = 1 AND IsNew = 0) fs on wr.StaffingWageRateID = fs.StaffingWageRateID
END
GO


---------------------------------------------

-- fp.procSampleStatsBudgetData
CREATE PROCEDURE [fp].[procSampleStatsBudgetData]
	@EntityGroupConfigID int
AS
BEGIN
/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1 	2022-09-30	JB		JAZZ-43489	Remove FlexedValue references
	*************************************************************/
	-- update the budget data
	INSERT INTO [fp].[FactStatisticsBudget]([StatisticsID], [BudgetPhaseID], 
											[AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12])
	SELECT [StatisticsID], [BudgetPhaseID],
		   [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12]
	FROM [fp].[FactStatistics] fs
		 CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID)
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0

END
GO


---------------------------------------------

-- fp.procSampleStatsClearData
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author			WI			Description
** 1		2021-02-25		lrenadesouza	JAZZ-12907	Added rolling deletes
** 2		2021-06-09		NThomas			JAZZ-20639	Add new table StatisticsAdjustmentRate
** 3		2023-04-19		mdeboer			JAZZ-53496	Remove adjustment delete logic
** 4		2023-07-05		mdeboer			JAZZ-55672	Add remove config logic
***************************************************************/

CREATE     PROCEDURE [fp].[procSampleStatsClearData]
	@BudgetConfigGUID uniqueidentifier,
	@EntityGroupConfigID int,
	@IsRemoveConfig BIT = 0
AS
BEGIN

	DECLARE @ChunkCount INT;	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END;
	DECLARE @r INT;

	CREATE TABLE #StatsToDelete (StatisticsID INT)

	IF @IsRemoveConfig = 1
	BEGIN
		INSERT #StatsToDelete with (tablock) (StatisticsID)
		SELECT StatisticsID FROM fp.FactStatistics
		WHERE EntityGroupConfigID = @EntityGroupConfigID 
	END
	ELSE
	BEGIN
		INSERT #StatsToDelete with (tablock) (StatisticsID)
		SELECT StatisticsID FROM fp.FactStatistics
		WHERE EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0
	END
		
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
			DELETE TOP (@ChunkCount) fsch 
			FROM [fp].[StatisticsChangeHistory] fsch 
			INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsch.StatisticsID 
			INNER JOIN #StatsToDelete std on fsch.StatisticsID = std.StatisticsID;
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
	
	-- delete existing data (have to do value tables first so that we still have EntityGroupConfigID)
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
			DELETE TOP (@ChunkCount) fsb 
			FROM [fp].[FactStatisticsBudget] fsb 
			INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsb.StatisticsID 
			INNER JOIN #StatsToDelete std on fsb.StatisticsID = std.StatisticsID;
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
			DELETE TOP (@ChunkCount) fsb 
			FROM [fp].[FactStatisticsProjection] fsb 
			INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsb.StatisticsID 
			INNER JOIN #StatsToDelete std on fsb.StatisticsID = std.StatisticsID;
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
			DELETE TOP (@ChunkCount) fsb 
			FROM [fp].[FactStatisticsHistory] fsb 
			INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsb.StatisticsID 
			INNER JOIN #StatsToDelete std on fsb.StatisticsID = std.StatisticsID;
			SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
	SET @r = 1;	 
	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
			DELETE TOP (@ChunkCount) fs
			FROM [fp].[FactStatistics] fs
			INNER JOIN #StatsToDelete std on fs.StatisticsID = std.StatisticsID;
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END

END;
GO


---------------------------------------------

-- fp.procSampleStatsDimensionality
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			Description
** 1		2018-06-05								Created
** 2		2018-11-01		OV			B-20952		Add new budget config sampling sources (Statistics only)
** 3		2018-11-05		OV          B-20952		Filtered by ParentBudgetConfigID
** 4		2018-11-30		BK          D-07892		Limit prior year dimensionality to TimeClassID = 1
** 5		2018-12-13		GF          B-20952		Revert MR changes
** 6		2019-08-12		CB			B-23990		Filter accounts to stat accounts only
** 7		2020-10-27		BK          JAZZ-2905	Add support for provider sampling
** 8		2021-02-01		MY          JAZZ-14416	Update driver subsection = 1
** 9		2022-01-18		BK          JAZZ-32267	Add support for charge based stats
** 9		2022-04-04		BK          JAZZ-35385  Add Patient Type to join for Charge-Based stats sampling
** 10		2022-04-07		BW          JAZZ-35906  Add entity group config filter for Charge-Based stats sampling
** 11		2022-12-12		DM		    JAZZ-46455	Sampling of Provider Type and Provider Specialty is linked to Section Setup
** 12		2023-02-17		MY		    JAZZ-49985	Provider Statistics will NOT sample if there is no YTD data for a dept/provider
** 13		2023-03-30		MZ			JAZZ-51398  Extended left join by ProviderID for departments configured to use provider stats data
** 14		2024-01-31		NH			JAZZ-64064  Move Provider Planning FF as a setting in Plan Config
***************************************************************/
CREATE     PROCEDURE [fp].[procSampleStatsDimensionality] 
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@CurrentFiscalYearID SMALLINT,
	@SourceFiscalYearID SMALLINT,
	@SourceTimeClassID TINYINT
AS
BEGIN

	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc WHERE BudgetConfigID = @BudgetConfigID;

	DECLARE @IsUsingSystemGeneratedStats BIT;
	SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;
	
	DECLARE @IsProviderTypeDisabled BIT;
	SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	
	DECLARE @IsProviderSpecialtyDisabled BIT;
	SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS (
							SELECT *
							FROM fp.SectionSetup ss
												INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID
												WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1
							 )
							THEN CAST(1 AS BIT)
							ELSE CAST(0 AS BIT) END;

	IF @IsProviderPlanningEnabled = 0 BEGIN
		INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], 
			[FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], [SubsectionID])
		SELECT
			DISTINCT
			@BudgetConfigID,
			@EntityGroupConfigID,
			dept.EntityID,
			stat.DepartmentID, 
			stat.AccountID,
			acc.OBUnitsFinancialReportingID,
			acc.OBPayorID,
			acc.PatientClassID,
			acc.OBStatUnitTypeID,
			1
		FROM
			[int].[FactStatistic] stat
			INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID
			INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID 
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			LEFT JOIN (
					SELECT DISTINCT DepartmentID, AccountID
					FROM [fp].[FactStatistics]
					WHERE EntityGroupConfigID = @EntityGroupConfigID
					AND IsNew = 1
				) fs
				ON stat.DepartmentID = fs.DepartmentID
				AND stat.AccountID = fs.AccountID 
		WHERE 
			((stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID)  -- baseline
			 OR (stat.FiscalYearID = @CurrentFiscalYearID)  		                                 -- projection (current year actuals)
			 OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1))  			-- prior year, actual & budget
			AND stat.IsDeleted = 0
			AND stat.FiscalMonthID != 0
			AND acc.IsStat = 1	-- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config
			AND acc.OBStatUnitTypeID = 140
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND fs.DepartmentID IS NULL
	END ELSE BEGIN
		IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept
		CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT)

		-- Three steps to make sure we get all departments to sample
		-- 1. Departments in DepartmentLevelConfiguration and do not use Provider Stats
		-- 2. Departments in DepartmentLevelConfiguration and do use Provider Stats
		-- 3. Departments not in DepartmentLevelConfiguration
		
		-- 1. Depts that are in fp.DepartmentLevelConfiguration table
		INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
		SELECT DISTINCT stat.DepartmentID, dept.EntityID, IsUsingProviderStats
		FROM [fp].[DepartmentLevelConfiguration] config  
			INNER JOIN [int].[FactStatistic] stat ON stat.DepartmentID = config.DepartmentID
			INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID
			INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID 
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE 
			(
				   (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID)	-- baseline
				OR (stat.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
				OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1)				-- prior year, actual & budget
			)
			AND stat.IsDeleted = 0
			AND stat.FiscalMonthID != 0
			AND acc.IsStat = 1	-- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config
			AND acc.OBStatUnitTypeID = 140
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND config.BudgetConfigID = @BudgetConfigID
			AND config.IsUsingProviderStats = 0 

		-- 2. depts in DepartmentLevelConfiguration that use provider stats
		INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
		SELECT DISTINCT stat.DepartmentID, dept.EntityID, IsUsingProviderStats
		FROM [fp].[DepartmentLevelConfiguration] config  
			INNER JOIN [int].[FactProvider] stat ON stat.DepartmentID = config.DepartmentID			
			INNER JOIN [fw].[DimDepartment] dept ON dept.DepartmentID = config.DepartmentID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE 
			(
				   (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID)	-- baseline
				OR (stat.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
				OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1)				-- prior year, actual & budget
			)
			AND stat.IsDeleted = 0
			AND stat.FiscalMonthID != 0			
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND config.BudgetConfigID = @BudgetConfigID
			AND config.IsUsingProviderStats = 1

		-- 3. get any departments that aren't in the fp.DepartmentLevelConfiguration table for the Budget 
		INSERT INTO #dept (DepartmentID, EntityID, UseProvider)
		SELECT DISTINCT stat.DepartmentID, dept.EntityID, ISNULL(IsUsingProviderStats, 0)
		FROM [int].[FactStatistic] stat
			INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID 
			INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID
			INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
			INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
			LEFT JOIN (SELECT DepartmentID, IsUsingProviderStats FROM [fp].[DepartmentLevelConfiguration] WHERE BudgetConfigID = @BudgetConfigID) config ON stat.DepartmentID = config.DepartmentID
			LEFT JOIN #dept d on stat.DepartmentID = d.DepartmentID
		WHERE 
			(
				   (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID)	-- baseline
				OR (stat.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
				OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1)				-- prior year, actual & budget
			)
			AND stat.IsDeleted = 0
			AND stat.FiscalMonthID != 0
			AND acc.IsStat = 1	-- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config
			AND acc.OBStatUnitTypeID = 140
			AND egc.EntityGroupConfigID = @EntityGroupConfigID
			AND config.IsUsingProviderStats IS NULL
			AND d.DepartmentID IS NULL

		-- sample actual dimensionality
		INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], 
												ProviderID, ProviderLineItemID, ProviderSpecialtyID, ProviderTypeID, SubsectionID)
		SELECT
			DISTINCT
			@BudgetConfigID,
			@EntityGroupConfigID,
			dept.EntityID,
			stat.DepartmentID, 
			stat.AccountID,
			acc.OBUnitsFinancialReportingID,
			acc.OBPayorID,
			acc.PatientClassID,
			acc.OBStatUnitTypeID, 0, 0, 0, 0, 1
		FROM
			[int].[FactStatistic] stat
			INNER JOIN #dept dept ON stat.DepartmentID = dept.DepartmentID
			INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID 
			LEFT JOIN (
					SELECT DISTINCT DepartmentID, AccountID
					FROM [fp].[FactStatistics]
					WHERE EntityGroupConfigID = @EntityGroupConfigID
					AND IsNew = 1
				) fs
				ON stat.DepartmentID = fs.DepartmentID
				AND stat.AccountID = fs.AccountID 
		WHERE 
			(
				   (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID)	-- baseline
				OR (stat.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
				OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1)				-- prior year, actual & budget
			)
			AND stat.IsDeleted = 0
			AND stat.FiscalMonthID != 0
			AND acc.IsStat = 1	-- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config
			AND acc.OBStatUnitTypeID = 140
			AND fs.DepartmentID IS NULL
			AND dept.UseProvider = 0

		-- departments configured to use provider stats data
		INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], 
												 ProviderID, ProviderLineItemID, ProviderSpecialtyID, ProviderTypeID, SubsectionID)
		SELECT
			DISTINCT
			@BudgetConfigID,
			@EntityGroupConfigID,
			dept.EntityID,
			prov.DepartmentID, 
			acc.AccountID,
			acc.OBUnitsFinancialReportingID,
			acc.OBPayorID,
			acc.PatientClassID,
			acc.OBStatUnitTypeID,
			prov.PhysicianID,
			prov.ProviderLineItemID,
			CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE phys.PhysicianSpecialtyID END AS ProviderSpecialtyID,
			CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE phys.ProviderTypeID END AS ProviderTypeID,
			1
		FROM
			[int].[FactProvider] prov
			INNER JOIN #dept dept ON prov.DepartmentID = dept.DepartmentID
			INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID
			INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
			INNER JOIN fp.ProviderStatisticsConfig config on prov.ProviderLineItemID = config.ProviderLineItemID
			INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
			INNER JOIN dss.DimPhysician phys on prov.PhysicianID = phys.PhysicianID
			LEFT JOIN (
					SELECT DISTINCT DepartmentID, AccountID, ProviderID
					FROM [fp].[FactStatistics]
					WHERE EntityGroupConfigID = @EntityGroupConfigID
					AND IsNew = 1
				) fs
				ON prov.DepartmentID = fs.DepartmentID
				AND acc.AccountID = fs.AccountID 
				AND phys.PhysicianID = fs.ProviderID
		WHERE 
			(
				   (prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID)	-- baseline
				OR (prov.FiscalYearID = @CurrentFiscalYearID)  											-- projection (current year actuals)
				OR (prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeClassID = 1)				-- prior year, actual & budget
			)
			AND prov.FiscalMonthID != 0
			AND acc.IsStat = 1	-- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config
			AND acc.OBStatUnitTypeID = 140
			AND fs.DepartmentID IS NULL
			AND dept.UseProvider = 1
			AND ps.Description = 'Statistics'
			AND config.BudgetConfigID = @BudgetConfigID

	END

	--If flag is true, for dimensionality (DeptID, AcctID, FiscalYearID, TimeClassID) that exists in fw.FactChargeBasedStatisticsMonthly,
	--attempt to set historical stats from fw.FactChargeBasedStatisticsMonthly

	IF(@IsUsingSystemGeneratedStats = 1)
	BEGIN
 		IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats
		CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT) 
	
		--Pull existing stats data so we know what not to touch			
		INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID ) 
		SELECT stat.DepartmentID, stat.AccountID, stat.PatientClassID
		FROM fp.FactStatistics stat WHERE EntityGroupConfigID = @EntityGroupConfigID


		-- sample dimensionality that does not exist in int.FactStatistic
		INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], 
												 ProviderID, ProviderLineItemID, ProviderSpecialtyID, ProviderTypeID, SubsectionID)
		SELECT @BudgetConfigID,
			@EntityGroupConfigID,
			dept.EntityID,
			cbs.DepartmentID, 
			cbs.AccountID,
			cbs.OBUnitsFinancialReportingID,
			cbs.OBPayorID,
			cbs.PatientClassID,
			cbs.OBStatUnitTypeID, 0, 0, 0, 0, 1
		FROM (SELECT DISTINCT stat.DepartmentID, stat.AccountID, acc.OBUnitsFinancialReportingID, acc.OBPayorID, acc.PatientClassID, acc.OBStatUnitTypeID
				FROM fw.FactChargeBasedStatisticsMonthly stat 
					INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID		
					INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID
					INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID
					INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID							
				WHERE stat.FiscalYearID IN (@CurrentFiscalYearID, @CurrentFiscalYearID - 1) 
				  AND stat.IsDeleted = 0 
				  AND stat.FiscalMonthID != 0
				  AND egc.EntityGroupConfigID = @EntityGroupConfigID -- Filter for the targeted config
				) as cbs   -- Charge Based Stats
		  INNER JOIN fw.DimDepartment dept ON cbs.DepartmentID = dept.DepartmentID
		  LEFT JOIN #existingStats intData ON cbs.DepartmentID = intData.DepartmentID 
			AND cbs.AccountID = intData.AccountID 
			AND cbs.PatientClassID = intData.PatientClassID			
		WHERE intData.DepartmentID is null 
	END

END
GO


---------------------------------------------

-- fp.procSampleStatsHistoricalData
CREATE PROCEDURE [fp].[procSampleStatsHistoricalData]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
AS
BEGIN
	/**************************************************************
    ** Change History
    **************************************************************
    ** CID  Date        Author  WI          Description
    ** 1 	 2021-12-08   MD      JAZZ-67     Update AP Stat sampling to leverage charge based stats
    ** 2   2022-03-07   NT      JAZZ-34087  Add FiscalMonthID in the JOIN when generating system generated stats 		
    ** 3   2022-06-09   AO      JAZZ-32943  Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics
    ** 4   2022-07-18   NT      JAZZ-40469  Fix the filter on FiscalYearID when calculating CurrentYear values
    ** 5   2023-07-14   BK      JAZZ-56315  If using provider do not use overwrite with System Generate Stats
    ** 6   2024-01-31   NH      JAZZ-64064  Move Provider Planning FF as a setting in Plan Config
    *************************************************************/

	-- pad all of the data
	INSERT INTO [fp].[FactStatisticsHistory]([StatisticsID])
	SELECT [StatisticsID]
	FROM [fp].[FactStatistics] fs
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0

	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	DECLARE @BudgetConfigID INT 
	SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID

	DECLARE @IsUsingSystemGeneratedStats BIT;
	SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;
	IF @IsUsingSystemGeneratedStats = NULL BEGIN SET @IsUsingSystemGeneratedStats = 0 END

	-- set all of the values for prior year actual
	UPDATE
		fsh
	SET
		PriorYearActualValue01 = ISNULL(Month01, 0),
		PriorYearActualValue02 = ISNULL(Month02, 0),
		PriorYearActualValue03 = ISNULL(Month03, 0),
		PriorYearActualValue04 = ISNULL(Month04, 0),
		PriorYearActualValue05 = ISNULL(Month05, 0),
		PriorYearActualValue06 = ISNULL(Month06, 0),
		PriorYearActualValue07 = ISNULL(Month07, 0),
		PriorYearActualValue08 = ISNULL(Month08, 0),
		PriorYearActualValue09 = ISNULL(Month09, 0),
		PriorYearActualValue10 = ISNULL(Month10, 0),
		PriorYearActualValue11 = ISNULL(Month11, 0),
		PriorYearActualValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactStatisticsHistory] fsh
		INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
		INNER JOIN 
		(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value
		 FROM [int].[FactStatistic] stat
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
		 WHERE stat.FiscalYearID = (@CurrentFiscalYearID - 1) AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0
		 GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID = 1)


	-- set all of the values for current year actual/annualized
	UPDATE
		fsh
	SET
		ActualYTDValue01 = ISNULL(Month01, 0),
		ActualYTDValue02 = ISNULL(Month02, 0),
		ActualYTDValue03 = ISNULL(Month03, 0),
		ActualYTDValue04 = ISNULL(Month04, 0),
		ActualYTDValue05 = ISNULL(Month05, 0),
		ActualYTDValue06 = ISNULL(Month06, 0),
		ActualYTDValue07 = ISNULL(Month07, 0),
		ActualYTDValue08 = ISNULL(Month08, 0),
		ActualYTDValue09 = ISNULL(Month09, 0),
		ActualYTDValue10 = ISNULL(Month10, 0),
		ActualYTDValue11 = ISNULL(Month11, 0),
		ActualYTDValue12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactStatisticsHistory] fsh
		INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
		INNER JOIN 
		(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value
		 FROM [int].[FactStatistic] stat 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
		 WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded
		 GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID = 1)

	
	-- set all of the values for current year budget
	UPDATE
		fsh
	SET
		CurrentYearBudget01 = ISNULL(Month01, 0),
		CurrentYearBudget02 = ISNULL(Month02, 0),
		CurrentYearBudget03 = ISNULL(Month03, 0),
		CurrentYearBudget04 = ISNULL(Month04, 0),
		CurrentYearBudget05 = ISNULL(Month05, 0),
		CurrentYearBudget06 = ISNULL(Month06, 0),
		CurrentYearBudget07 = ISNULL(Month07, 0),
		CurrentYearBudget08 = ISNULL(Month08, 0),
		CurrentYearBudget09 = ISNULL(Month09, 0),
		CurrentYearBudget10 = ISNULL(Month10, 0),
		CurrentYearBudget11 = ISNULL(Month11, 0),
		CurrentYearBudget12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactStatisticsHistory] fsh
		INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
		INNER JOIN 
		(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value
		 FROM [int].[FactStatistic] stat 
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
		 WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 2 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0
		 GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID = 1)

	 -----------------------------------------------------------------------------------------------------------------------------------------------
	 -----------------------------------------------------------------------------------------------------------------------------------------------
	 -----------------------------------------------------------------------------------------------------------------------------------------------

	--If flag is true, for dimensionality (DeptID, AcctID, FiscalYearID, TimeClassID) that doesn't exist in int.FactStatistic,
	--attempt to set historical stats from fw.FactChargeBasedStatisticsMonthly

	IF(@IsUsingSystemGeneratedStats = 1)
	BEGIN
		IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats
		CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, TimeClassID INT, FiscalYearID INT, FiscalMonthID INT)
		
		--Pull existing stats data so we know what not to touch
		INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, TimeClassID, FiscalYearID, FiscalMonthID) 
		SELECT DISTINCT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.TimeClassID, stat.FiscalYearID, stat.FiscalMonthID
		FROM int.FactStatistic stat
		INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
		WHERE 1=1
		AND stat.TimeClassID in (1,2)
		AND stat.FiscalYearID in (@CurrentFiscalYearID, @CurrentFiscalYearID - 1)
		AND stat.IsDeleted = 0 
		AND stat.FiscalMonthID != 0

		-- set all of the values for prior year actual that do not exist in int.FactStatistic
		UPDATE
			fsh
		SET
			PriorYearActualValue01 = ISNULL(Month01, PriorYearActualValue01),
			PriorYearActualValue02 = ISNULL(Month02, PriorYearActualValue02),
			PriorYearActualValue03 = ISNULL(Month03, PriorYearActualValue03),
			PriorYearActualValue04 = ISNULL(Month04, PriorYearActualValue04),
			PriorYearActualValue05 = ISNULL(Month05, PriorYearActualValue05),
			PriorYearActualValue06 = ISNULL(Month06, PriorYearActualValue06),
			PriorYearActualValue07 = ISNULL(Month07, PriorYearActualValue07),
			PriorYearActualValue08 = ISNULL(Month08, PriorYearActualValue08),
			PriorYearActualValue09 = ISNULL(Month09, PriorYearActualValue09),
			PriorYearActualValue10 = ISNULL(Month10, PriorYearActualValue10),
			PriorYearActualValue11 = ISNULL(Month11, PriorYearActualValue11),
			PriorYearActualValue12 = ISNULL(Month12, PriorYearActualValue12)
		FROM
			[fp].[FactStatisticsHistory] fsh
			INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
			INNER JOIN 
				(SELECT stat.DepartmentID, 
						 stat.AccountID, 
						 acc.PatientClassID,
						 fm.MonthColumnName, 
						 SUM(Value) AS Value
				FROM fw.FactChargeBasedStatisticsMonthly stat 
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID	
			    INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID
				LEFT JOIN (SELECT exStats.DepartmentID, exStats.AccountID, exStats.PatientClassID, exStats.TimeClassID, exStats.FiscalYearID, exStats.FiscalMonthID 
						    FROM #existingStats exStats 
						    WHERE exStats.FiscalYearID = (@CurrentFiscalYearID - 1) 
							 AND exStats.TimeclassID = 1
						  ) intData 
			  	 ON stat.DepartmentID = intData.DepartmentID 
				AND stat.AccountID = intData.AccountID
				AND stat.FiscalMonthID = intdata.FiscalMonthID
				AND acc.PatientClassID = intData.PatientClassID
			 WHERE stat.FiscalYearID = (@CurrentFiscalYearID - 1) 
			   AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0
			   AND intData.DepartmentID IS NULL
			GROUP BY stat.DepartmentID, stat.AccountID, acc.PatientClassID, fm.MonthColumnName) data	
			PIVOT
			(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
			AND fs.PatientClassID = pv.PatientClassID			
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID  AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0
		
		-- set all of the values for current year actual/annualized that do not exist in int.FactStatistic
		UPDATE
			fsh
		SET
			ActualYTDValue01 = ISNULL(Month01, ActualYTDValue01),
			ActualYTDValue02 = ISNULL(Month02, ActualYTDValue02),
			ActualYTDValue03 = ISNULL(Month03, ActualYTDValue03),
			ActualYTDValue04 = ISNULL(Month04, ActualYTDValue04),
			ActualYTDValue05 = ISNULL(Month05, ActualYTDValue05),
			ActualYTDValue06 = ISNULL(Month06, ActualYTDValue06),
			ActualYTDValue07 = ISNULL(Month07, ActualYTDValue07),
			ActualYTDValue08 = ISNULL(Month08, ActualYTDValue08),
			ActualYTDValue09 = ISNULL(Month09, ActualYTDValue09),
			ActualYTDValue10 = ISNULL(Month10, ActualYTDValue10),
			ActualYTDValue11 = ISNULL(Month11, ActualYTDValue11),
			ActualYTDValue12 = ISNULL(Month12, ActualYTDValue12)
		FROM
			[fp].[FactStatisticsHistory] fsh
			INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
			INNER JOIN 
			(SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, fm.MonthColumnName, SUM(Value) as Value
			 FROM fw.FactChargeBasedStatisticsMonthly stat 
			 INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
			    INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID
			  LEFT JOIN (SELECT exStats.DepartmentID, exStats.AccountID, exStats.PatientClassID, exStats.TimeClassID, exStats.FiscalYearID, exStats.FiscalMonthID 
						    FROM #existingStats exStats 
						    WHERE exStats.FiscalYearID = (@CurrentFiscalYearID) 
							 AND exStats.TimeclassID = 1
						  ) intData 
			    ON stat.DepartmentID = intData.DepartmentID 
			  AND stat.AccountID = intData.AccountID
			  AND stat.FiscalMonthID = intdata.FiscalMonthID
			  AND acc.PatientClassID = intData.PatientClassID
		WHERE stat.FiscalYearID = @CurrentFiscalYearID 
		  AND stat.IsDeleted = 0 
		  AND stat.FiscalMonthID != 0 
		  AND fm.SortOrder <= @MonthsLoaded
		  AND intData.DepartmentID IS NULL
		GROUP BY stat.DepartmentID, stat.AccountID, acc.PatientClassID, fm.MonthColumnName) data	
			PIVOT
			(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv
				ON fs.DepartmentID = pv.DepartmentID
				AND fs.AccountID = pv.AccountID
				AND fs.PatientClassID = pv.PatientClassID
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0

		-- We do not populate Current Year Budget with this process
		
	END
 
 -----------------------------------------------------------------------------------------------------------------------------------------------
 -----------------------------------------------------------------------------------------------------------------------------------------------
 -----------------------------------------------------------------------------------------------------------------------------------------------
 -- sample provider historicals 

	IF @IsProviderPlanningEnabled = 1 BEGIN
		

		-- set all of the values for prior year actual
		UPDATE
			fsh
		SET
			PriorYearActualValue01 = ISNULL(Month01, 0),
			PriorYearActualValue02 = ISNULL(Month02, 0),
			PriorYearActualValue03 = ISNULL(Month03, 0),
			PriorYearActualValue04 = ISNULL(Month04, 0),
			PriorYearActualValue05 = ISNULL(Month05, 0),
			PriorYearActualValue06 = ISNULL(Month06, 0),
			PriorYearActualValue07 = ISNULL(Month07, 0),
			PriorYearActualValue08 = ISNULL(Month08, 0),
			PriorYearActualValue09 = ISNULL(Month09, 0),
			PriorYearActualValue10 = ISNULL(Month10, 0),
			PriorYearActualValue11 = ISNULL(Month11, 0),
			PriorYearActualValue12 = ISNULL(Month12, 0)
		FROM
			[fp].[FactStatisticsHistory] fsh
			INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
			LEFT JOIN 
			(SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID
					FROM [int].[FactProvider] stat
		 				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID
					INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
					WHERE stat.FiscalYearID = (@CurrentFiscalYearID - 1) AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID
					GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) pv
				PIVOT
				(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
					ON fs.DepartmentID = pv.DepartmentID
					AND fs.AccountID = pv.AccountID
					AND fs.ProviderID = pv.ProviderID
					AND fs.ProviderLineItemID = pv.ProviderLineItemID
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0


		-- set all of the values for current year actual/annualized
		UPDATE
			fsh
		SET
			ActualYTDValue01 = ISNULL(Month01, 0),
			ActualYTDValue02 = ISNULL(Month02, 0),
			ActualYTDValue03 = ISNULL(Month03, 0),
			ActualYTDValue04 = ISNULL(Month04, 0),
			ActualYTDValue05 = ISNULL(Month05, 0),
			ActualYTDValue06 = ISNULL(Month06, 0),
			ActualYTDValue07 = ISNULL(Month07, 0),
			ActualYTDValue08 = ISNULL(Month08, 0),
			ActualYTDValue09 = ISNULL(Month09, 0),
			ActualYTDValue10 = ISNULL(Month10, 0),
			ActualYTDValue11 = ISNULL(Month11, 0),
			ActualYTDValue12 = ISNULL(Month12, 0)
		FROM
			[fp].[FactStatisticsHistory] fsh
			INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
			LEFT JOIN 
			(SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID
					FROM [int].[FactProvider] stat
		 				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID
					INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
					WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID
					GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) pv
				PIVOT
				(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
					ON fs.DepartmentID = pv.DepartmentID
					AND fs.AccountID = pv.AccountID
					AND fs.ProviderID = pv.ProviderID
					AND fs.ProviderLineItemID = pv.ProviderLineItemID			
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0

	
		-- set all of the values for current year budget
		UPDATE
			fsh
		SET
			CurrentYearBudget01 = ISNULL(Month01, 0),
			CurrentYearBudget02 = ISNULL(Month02, 0),
			CurrentYearBudget03 = ISNULL(Month03, 0),
			CurrentYearBudget04 = ISNULL(Month04, 0),
			CurrentYearBudget05 = ISNULL(Month05, 0),
			CurrentYearBudget06 = ISNULL(Month06, 0),
			CurrentYearBudget07 = ISNULL(Month07, 0),
			CurrentYearBudget08 = ISNULL(Month08, 0),
			CurrentYearBudget09 = ISNULL(Month09, 0),
			CurrentYearBudget10 = ISNULL(Month10, 0),
			CurrentYearBudget11 = ISNULL(Month11, 0),
			CurrentYearBudget12 = ISNULL(Month12, 0)
		FROM
			[fp].[FactStatisticsHistory] fsh
			INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID
			LEFT JOIN 
			(SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID
					FROM [int].[FactProvider] stat
		 				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID
					INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
					WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 2 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID 
					GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) pv
				PIVOT
				(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
					ON fs.DepartmentID = pv.DepartmentID
					AND fs.AccountID = pv.AccountID	
					AND fs.ProviderID = pv.ProviderID
					AND fs.ProviderLineItemID = pv.ProviderLineItemID				
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0
 
	END
END
GO


---------------------------------------------

-- fp.procSampleStatsOriginalBudgetVolume
CREATE PROCEDURE [fp].[procSampleStatsOriginalBudgetVolume]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN

/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			 Description
** 1      2018-05-06                               Created
** 2		2018-11-05       OV	       B-20952       Add new budget config sampling sources (Statistics only)
** 3		2018-11-07       BK	       B-21035       Spread InitialValue evenly across months
** 4		2020-10-27       BK	       JAZZ-2905     Add provider data
** 5		2021-04-21       BK	       JAZZ-18500    Fix subsection
** 6		2022-02-17       MD	       JAZZ-33345    Add code to handle projection of system generated stats
** 7      2022-03-08       NT	       JAZZ-34087   Add FiscalMonthID in the JOIN when generating charge based stats 		
** 8      2022-04-04       BK	       JAZZ-35385   Add Patient Type to join for Charge-Based stats sampling
** 9      2022-06-09       AO	       JAZZ-32943	Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics
** 10     2023-07-15       BK	       JAZZ-35385   Add Patient Type to join for Charge-Based stats sampling
** 11     2023-07-14       BK        JAZZ-56315   If using provider do not use overwrite with System Generate Stats
** 12     2024-01-31       NH        JAZZ-64064   Move Provider Planning FF as a setting in Plan Config
***************************************************************/

DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END)


declare @ParentEntityConfigID int = (
select EntityGroupConfigID 
from fp.EntityGroupConfig
where EntityGroupConfigGUID = (
select ParentEntityGroupConfigGuid
from fp.EntityGroupConfig ecg
inner join fp.BudgetConfig bc on bc.BudgetConfigGUID = ecg.BudgetConfigGUID and bc.IsMRTracking = 1
where ecg.EntityGroupConfigID = @EntityGroupConfigID)
)

IF @ParentEntityConfigID > 0

		UPDATE
		fs
	SET
		SampledBudget01 = fsb.AdjustedValue01,
		SampledBudget02 = fsb.AdjustedValue02,
		SampledBudget03 = fsb.AdjustedValue03,
		SampledBudget04 = fsb.AdjustedValue04,
		SampledBudget05 = fsb.AdjustedValue05,
		SampledBudget06 = fsb.AdjustedValue06,
		SampledBudget07 = fsb.AdjustedValue07,
		SampledBudget08 = fsb.AdjustedValue08,
		SampledBudget09 = fsb.AdjustedValue09,
		SampledBudget10 = fsb.AdjustedValue10,
		SampledBudget11 = fsb.AdjustedValue11,
		SampledBudget12 = fsb.AdjustedValue12
 FROM
		[fp].[FactStatistics] fs
		INNER JOIN fp.[FactStatistics] fs_parent on fs.EntityGroupConfigID = @EntityGroupConfigID and fs_parent.EntityGroupConfigID = @ParentEntityConfigID
		and fs.DepartmentID = fs_parent.DepartmentID
		and fs.AccountID = fs_parent.AccountID
		and fs.EntityID = fs_parent.EntityID
		and fs.FinancialReportingID = fs_parent.FinancialReportingID
		and fs.PayorID = fs_parent.PayorID
		and fs.PatientClassID = fs_parent.PatientClassID
		and fs.UnitTypeID = fs_parent.UnitTypeID
		and fs.ProviderID = fs_parent.ProviderID
		and fs.ProviderTypeID = fs_parent.ProviderTypeID
		and fs.ProviderSpecialtyID = fs_parent.ProviderSpecialtyID
		and fs.ProviderLineItemID = fs_parent.ProviderLineItemID
		INNER JOIN fp.FactStatisticsBudget fsb on fsb.StatisticsID = fs_parent.StatisticsID and fsb.BudgetPhaseID = 3
ELSE
	-- set all of the values from the source fy/tc
BEGIN
	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	-- Non provider stats
	UPDATE
		fs
	SET
		SampledBudget01 = ISNULL(Month01, 0),
		SampledBudget02 = ISNULL(Month02, 0),
		SampledBudget03 = ISNULL(Month03, 0),
		SampledBudget04 = ISNULL(Month04, 0),
		SampledBudget05 = ISNULL(Month05, 0),
		SampledBudget06 = ISNULL(Month06, 0),
		SampledBudget07 = ISNULL(Month07, 0),
		SampledBudget08 = ISNULL(Month08, 0),
		SampledBudget09 = ISNULL(Month09, 0),
		SampledBudget10 = ISNULL(Month10, 0),
		SampledBudget11 = ISNULL(Month11, 0),
		SampledBudget12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactStatistics] fs
		INNER JOIN 
		(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value
			FROM [int].[FactStatistic] stat
		 		INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
				INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
			WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
			GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0)

	DECLARE @IsUsingSystemGeneratedStats BIT;
	SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;
	IF @IsUsingSystemGeneratedStats IS NULL BEGIN SET @IsUsingSystemGeneratedStats = 0 END

	IF(@IsUsingSystemGeneratedStats = 1)
		BEGIN
	 		IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats
			CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) 
	
			--Pull existing stats data so we know what not to touch			
			INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) 
			SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID
			FROM int.FactStatistic stat
				INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
			WHERE stat.IsDeleted = 0 
				AND stat.FiscalMonthID != 0
				AND stat.FiscalYearID = @SourceFiscalYearID
				AND stat.TimeClassID = @SourceTimeClassID
			GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID		
			
			UPDATE fs SET
				SampledBudget01 = ISNULL(Month01, SampledBudget01),
				SampledBudget02 = ISNULL(Month02, SampledBudget02),
				SampledBudget03 = ISNULL(Month03, SampledBudget03),
				SampledBudget04 = ISNULL(Month04, SampledBudget04),
				SampledBudget05 = ISNULL(Month05, SampledBudget05),
				SampledBudget06 = ISNULL(Month06, SampledBudget06),
				SampledBudget07 = ISNULL(Month07, SampledBudget07),
				SampledBudget08 = ISNULL(Month08, SampledBudget08),
				SampledBudget09 = ISNULL(Month09, SampledBudget09),
				SampledBudget10 = ISNULL(Month10, SampledBudget10),
				SampledBudget11 = ISNULL(Month11, SampledBudget11),
				SampledBudget12 = ISNULL(Month12, SampledBudget12)
			FROM
				[fp].[FactStatistics] fs 
				INNER JOIN 
				(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.PatientClassID
					FROM 
						(
						SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value
							FROM fw.FactChargeBasedStatisticsMonthly stat 							
						    INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID
							WHERE stat.FiscalYearID = @SourceFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 					  
					  ) stat
					
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
						
						LEFT JOIN #existingStats intData 
						 ON stat.DepartmentID = intData.DepartmentID 
						    AND stat.AccountID = intData.AccountID	
						    AND stat.FiscalMonthID = intData.FiscalMonthID
						    AND stat.PatientClassID = intData.PatientClassID
					WHERE stat.FiscalYearID = @SourceFiscalYearID
					  AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
					  AND intData.DepartmentID IS NULL
					GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data	
						PIVOT
						(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])
				) as pv 
					ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID
			WHERE
				fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0
			
			
		END

IF @IsProviderPlanningEnabled = 1 BEGIN

	DECLARE @BudgetConfigID INT 
	SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID

		-- Update Provider Stats

		UPDATE
			fs
		SET
			SampledBudget01 = ISNULL(Month01, 0),
			SampledBudget02 = ISNULL(Month02, 0),
			SampledBudget03 = ISNULL(Month03, 0),
			SampledBudget04 = ISNULL(Month04, 0),
			SampledBudget05 = ISNULL(Month05, 0),
			SampledBudget06 = ISNULL(Month06, 0),
			SampledBudget07 = ISNULL(Month07, 0),
			SampledBudget08 = ISNULL(Month08, 0),
			SampledBudget09 = ISNULL(Month09, 0),
			SampledBudget10 = ISNULL(Month10, 0),
			SampledBudget11 = ISNULL(Month11, 0),
			SampledBudget12 = ISNULL(Month12, 0)
		FROM [fp].[FactStatistics] fs
			LEFT JOIN 
			(SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID
				FROM [int].[FactProvider] stat
		 			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID
				INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
				WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 
						AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
						AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID
				GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data
			PIVOT
			(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
				ON fs.DepartmentID = pv.DepartmentID
				AND fs.AccountID = pv.AccountID
				AND fs.ProviderID = pv.ProviderID
				AND fs.ProviderLineItemID = pv.ProviderLineItemID
			LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- we will want to update this when we add the actual SubSection stuff
	
	END

		-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data
		IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) 
		BEGIN
			-- per stackoverflow (per MY)
			DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
			DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
			DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded)
        	
			UPDATE fs
	        SET
	          -- not doing month 1 because it wouldn't really make sense to annualize without at least 1 month of actual data
	          SampledBudget02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget02 END,
	          SampledBudget03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget03 END,
	          SampledBudget04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget04 END,
	          SampledBudget05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget05 END,
	          SampledBudget06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget06 END,
	          SampledBudget07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget07 END,
	          SampledBudget08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget08 END,
	          SampledBudget09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget09 END,
	          SampledBudget10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget10 END,
	          SampledBudget11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget11 END,
	          SampledBudget12 = CASE WHEN @MonthsLoaded < 12 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget12 END
          FROM [fp].[FactStatistics] fs
			WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			
		END			
	END
	
	-- update the initial values to be equal to the sampled values on the dimensionality table
	UPDATE
		fs
	SET
		InitialBudget01 = SampledBudgetTotal / 12,
		InitialBudget02 = SampledBudgetTotal / 12,
		InitialBudget03 = SampledBudgetTotal / 12,
		InitialBudget04 = SampledBudgetTotal / 12,
		InitialBudget05 = SampledBudgetTotal / 12,
		InitialBudget06 = SampledBudgetTotal / 12,
		InitialBudget07 = SampledBudgetTotal / 12,
		InitialBudget08 = SampledBudgetTotal / 12,
		InitialBudget09 = SampledBudgetTotal / 12,
		InitialBudget10 = SampledBudgetTotal / 12,
		InitialBudget11 = SampledBudgetTotal / 12,
		InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12)
											  + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12))
	FROM [fp].[FactStatistics] fs
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
END
GO


---------------------------------------------

-- fp.procSampleStatsOriginalBudgetVolume_WithNewAnnualization
CREATE   PROCEDURE [fp].[procSampleStatsOriginalBudgetVolume_WithNewAnnualization]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@SourceFiscalYearID smallint,
	@SourceTimeClassID tinyint,
	@MonthsLoaded int
AS
BEGIN

/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			 Description
** 1      2018-05-06                               Created
** 2		2018-11-05       OV	       B-20952       Add new budget config sampling sources (Statistics only)
** 3		2018-11-07       BK	       B-21035       Spread InitialValue evenly across months
** 4		2020-10-27       BK	       JAZZ-2905     Add provider data
** 5		2021-04-21       BK	       JAZZ-18500    Fix subsection
** 6		2022-02-17       MD	       JAZZ-33345    Add code to handle projection of system generated stats
** 7      2022-03-08       NT	       JAZZ-34087   Add FiscalMonthID in the JOIN when generating charge based stats 		
** 8      2022-04-04       BK	       JAZZ-35385   Add Patient Type to join for Charge-Based stats sampling
** 9      2022-06-09       AO	       JAZZ-32943	Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics
** 10     2023-07-15       BK	       JAZZ-35385   Add Patient Type to join for Charge-Based stats sampling
** 11     2023-07-14       BK        JAZZ-56315   If using provider do not use overwrite with System Generate Stats
** 12     2024-01-31       NH        JAZZ-64064   Move Provider Planning FF as a setting in Plan Config
** 13     2024-07-24       BK        JAZZ-74600   Change Annualization to use daily 'rate'
***************************************************************/

DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END)


declare @ParentEntityConfigID int = (
select EntityGroupConfigID 
from fp.EntityGroupConfig
where EntityGroupConfigGUID = (
select ParentEntityGroupConfigGuid
from fp.EntityGroupConfig ecg
inner join fp.BudgetConfig bc on bc.BudgetConfigGUID = ecg.BudgetConfigGUID and bc.IsMRTracking = 1
where ecg.EntityGroupConfigID = @EntityGroupConfigID)
)

IF @ParentEntityConfigID > 0

		UPDATE
		fs
	SET
		SampledBudget01 = fsb.AdjustedValue01,
		SampledBudget02 = fsb.AdjustedValue02,
		SampledBudget03 = fsb.AdjustedValue03,
		SampledBudget04 = fsb.AdjustedValue04,
		SampledBudget05 = fsb.AdjustedValue05,
		SampledBudget06 = fsb.AdjustedValue06,
		SampledBudget07 = fsb.AdjustedValue07,
		SampledBudget08 = fsb.AdjustedValue08,
		SampledBudget09 = fsb.AdjustedValue09,
		SampledBudget10 = fsb.AdjustedValue10,
		SampledBudget11 = fsb.AdjustedValue11,
		SampledBudget12 = fsb.AdjustedValue12
 FROM
		[fp].[FactStatistics] fs
		INNER JOIN fp.[FactStatistics] fs_parent on fs.EntityGroupConfigID = @EntityGroupConfigID and fs_parent.EntityGroupConfigID = @ParentEntityConfigID
		and fs.DepartmentID = fs_parent.DepartmentID
		and fs.AccountID = fs_parent.AccountID
		and fs.EntityID = fs_parent.EntityID
		and fs.FinancialReportingID = fs_parent.FinancialReportingID
		and fs.PayorID = fs_parent.PayorID
		and fs.PatientClassID = fs_parent.PatientClassID
		and fs.UnitTypeID = fs_parent.UnitTypeID
		and fs.ProviderID = fs_parent.ProviderID
		and fs.ProviderTypeID = fs_parent.ProviderTypeID
		and fs.ProviderSpecialtyID = fs_parent.ProviderSpecialtyID
		and fs.ProviderLineItemID = fs_parent.ProviderLineItemID
		INNER JOIN fp.FactStatisticsBudget fsb on fsb.StatisticsID = fs_parent.StatisticsID and fsb.BudgetPhaseID = 3
ELSE
	-- set all of the values from the source fy/tc
BEGIN
	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	-- Non provider stats
	UPDATE
		fs
	SET
		SampledBudget01 = ISNULL(Month01, 0),
		SampledBudget02 = ISNULL(Month02, 0),
		SampledBudget03 = ISNULL(Month03, 0),
		SampledBudget04 = ISNULL(Month04, 0),
		SampledBudget05 = ISNULL(Month05, 0),
		SampledBudget06 = ISNULL(Month06, 0),
		SampledBudget07 = ISNULL(Month07, 0),
		SampledBudget08 = ISNULL(Month08, 0),
		SampledBudget09 = ISNULL(Month09, 0),
		SampledBudget10 = ISNULL(Month10, 0),
		SampledBudget11 = ISNULL(Month11, 0),
		SampledBudget12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactStatistics] fs
		INNER JOIN 
		(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value
			FROM [int].[FactStatistic] stat
		 		INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
				INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
			WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
			GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0)

	DECLARE @IsUsingSystemGeneratedStats BIT;
	SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;
	IF @IsUsingSystemGeneratedStats IS NULL BEGIN SET @IsUsingSystemGeneratedStats = 0 END

	IF(@IsUsingSystemGeneratedStats = 1)
		BEGIN
	 		IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats
			CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) 
	
			--Pull existing stats data so we know what not to touch			
			INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) 
			SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID
			FROM int.FactStatistic stat
				INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
			WHERE stat.IsDeleted = 0 
				AND stat.FiscalMonthID != 0
				AND stat.FiscalYearID = @SourceFiscalYearID
				AND stat.TimeClassID = @SourceTimeClassID
			GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID		
			
			UPDATE fs SET
				SampledBudget01 = ISNULL(Month01, SampledBudget01),
				SampledBudget02 = ISNULL(Month02, SampledBudget02),
				SampledBudget03 = ISNULL(Month03, SampledBudget03),
				SampledBudget04 = ISNULL(Month04, SampledBudget04),
				SampledBudget05 = ISNULL(Month05, SampledBudget05),
				SampledBudget06 = ISNULL(Month06, SampledBudget06),
				SampledBudget07 = ISNULL(Month07, SampledBudget07),
				SampledBudget08 = ISNULL(Month08, SampledBudget08),
				SampledBudget09 = ISNULL(Month09, SampledBudget09),
				SampledBudget10 = ISNULL(Month10, SampledBudget10),
				SampledBudget11 = ISNULL(Month11, SampledBudget11),
				SampledBudget12 = ISNULL(Month12, SampledBudget12)
			FROM
				[fp].[FactStatistics] fs 
				INNER JOIN 
				(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.PatientClassID
					FROM 
						(
						SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value
							FROM fw.FactChargeBasedStatisticsMonthly stat 							
						    INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID
							WHERE stat.FiscalYearID = @SourceFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 					  
					  ) stat
					
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
						
						LEFT JOIN #existingStats intData 
						 ON stat.DepartmentID = intData.DepartmentID 
						    AND stat.AccountID = intData.AccountID	
						    AND stat.FiscalMonthID = intData.FiscalMonthID
						    AND stat.PatientClassID = intData.PatientClassID
					WHERE stat.FiscalYearID = @SourceFiscalYearID
					  AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
					  AND intData.DepartmentID IS NULL
					GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data	
						PIVOT
						(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])
				) as pv 
					ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID
			WHERE
				fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0
			
			
		END

IF @IsProviderPlanningEnabled = 1 BEGIN

	DECLARE @BudgetConfigID INT 
	SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID

		-- Update Provider Stats

		UPDATE
			fs
		SET
			SampledBudget01 = ISNULL(Month01, 0),
			SampledBudget02 = ISNULL(Month02, 0),
			SampledBudget03 = ISNULL(Month03, 0),
			SampledBudget04 = ISNULL(Month04, 0),
			SampledBudget05 = ISNULL(Month05, 0),
			SampledBudget06 = ISNULL(Month06, 0),
			SampledBudget07 = ISNULL(Month07, 0),
			SampledBudget08 = ISNULL(Month08, 0),
			SampledBudget09 = ISNULL(Month09, 0),
			SampledBudget10 = ISNULL(Month10, 0),
			SampledBudget11 = ISNULL(Month11, 0),
			SampledBudget12 = ISNULL(Month12, 0)
		FROM [fp].[FactStatistics] fs
			LEFT JOIN 
			(SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID
				FROM [int].[FactProvider] stat
		 			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
					INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID
				INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
				INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID
				INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
				WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 
						AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))
						AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID
				GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data
			PIVOT
			(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
				ON fs.DepartmentID = pv.DepartmentID
				AND fs.AccountID = pv.AccountID
				AND fs.ProviderID = pv.ProviderID
				AND fs.ProviderLineItemID = pv.ProviderLineItemID
			LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
		WHERE
			fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- we will want to update this when we add the actual SubSection stuff
	
	END

		-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data
		IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) 
		BEGIN
			-- per stackoverflow (per MY)
			DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END)
			DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
			DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded)
        	DECLARE @IsBudgetLeapYear BIT = (CASE WHEN ((@CurrentFiscalYearID + 1) % 4 = 0 AND (@CurrentFiscalYearID  + 1) % 100 <> 0) OR (@CurrentFiscalYearID + 1) % 400 = 0 THEN 1 ELSE 0 END)  
			DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12)

			UPDATE fs
	        SET
	         SampledBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			SampledBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12,
			InitialBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12
					  FROM [fp].[FactStatistics] fs
			WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
			
		END			
		ELSE BEGIN
			-- update the initial values to be equal to the sampled values on the dimensionality table
			UPDATE
				fs
			SET
				InitialBudget01 = SampledBudgetTotal / 12,
				InitialBudget02 = SampledBudgetTotal / 12,
				InitialBudget03 = SampledBudgetTotal / 12,
				InitialBudget04 = SampledBudgetTotal / 12,
				InitialBudget05 = SampledBudgetTotal / 12,
				InitialBudget06 = SampledBudgetTotal / 12,
				InitialBudget07 = SampledBudgetTotal / 12,
				InitialBudget08 = SampledBudgetTotal / 12,
				InitialBudget09 = SampledBudgetTotal / 12,
				InitialBudget10 = SampledBudgetTotal / 12,
				InitialBudget11 = SampledBudgetTotal / 12,
				InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12)
													  + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12))
			FROM [fp].[FactStatistics] fs
			WHERE fs.EntityGroupConfigID = @EntityGroupConfigID
		END
	END
END
GO


---------------------------------------------

-- fp.procSampleStatsOriginalProjectionVolume
CREATE PROCEDURE [fp].[procSampleStatsOriginalProjectionVolume]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
AS
BEGIN

/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			  Description
** 1      2012-02-17    MD          JAZZ-33345   Move system generated stats sql to before copying of baseline to initial projection
** 2      2022-03-09    NT          JAZZ-34087   Add FiscalMonthID in the JOIN when generating charge based stats 
** 3      2022-04-04    BK          JAZZ-35385   Add Patient Type to join for Charge-Based stats sampling
** 4      2022-06-09    AO          JAZZ-32943   Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics
** 5      2023-07-13    BK          JAZZ-56315   If using provider do not use overwrite with System Generate Stats
** 6      2024-01-31    NH          JAZZ-64064   Move Provider Planning FF as a setting in Plan Config
***************************************************************/

	IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals

	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	DECLARE @IsUsingSystemGeneratedStats BIT;
	SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	-- set the orig values for the months where we have data (month sort order <= @MonthsLoaded)
	UPDATE
		fs
	SET
		SampledProjection01 = ISNULL(Month01, 0),
		SampledProjection02 = ISNULL(Month02, 0),
		SampledProjection03 = ISNULL(Month03, 0),
		SampledProjection04 = ISNULL(Month04, 0),
		SampledProjection05 = ISNULL(Month05, 0),
		SampledProjection06 = ISNULL(Month06, 0),
		SampledProjection07 = ISNULL(Month07, 0),
		SampledProjection08 = ISNULL(Month08, 0),
		SampledProjection09 = ISNULL(Month09, 0),
		SampledProjection10 = ISNULL(Month10, 0),
		SampledProjection11 = ISNULL(Month11, 0),
		SampledProjection12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactStatistics] fs
		INNER JOIN 
		(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value
		 FROM [int].[FactStatistic] stat
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
		 WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded
		 GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0)

	IF @IsProviderPlanningEnabled = 1 BEGIN
			DECLARE @BudgetConfigID INT 
			SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID

			-- Update Provider Stats
			UPDATE
				fs
			SET
				SampledProjection01 = ISNULL(Month01, 0),
			SampledProjection02 = ISNULL(Month02, 0),
			SampledProjection03 = ISNULL(Month03, 0),
			SampledProjection04 = ISNULL(Month04, 0),
			SampledProjection05 = ISNULL(Month05, 0),
			SampledProjection06 = ISNULL(Month06, 0),
			SampledProjection07 = ISNULL(Month07, 0),
			SampledProjection08 = ISNULL(Month08, 0),
			SampledProjection09 = ISNULL(Month09, 0),
			SampledProjection10 = ISNULL(Month10, 0),
			SampledProjection11 = ISNULL(Month11, 0),
			SampledProjection12 = ISNULL(Month12, 0)
			FROM [fp].[FactStatistics] fs
				LEFT JOIN 
				(SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID
					FROM [int].[FactProvider] stat
		 				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID
					INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
					WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded				
							AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID
					GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data
				PIVOT
				(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
					ON fs.DepartmentID = pv.DepartmentID
					AND fs.AccountID = pv.AccountID
					AND fs.ProviderID = pv.ProviderID
					AND fs.ProviderLineItemID = pv.ProviderLineItemID
				LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
			WHERE
				fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- as long as we haven't updated the driver/dependent SubsectionID yet this should be fine

		END

	-- We do not want to annualize projection from fw.FactChargeBasedStatisticsMonthly, months not loaded should be crosswalked from ChargeVolumes
	IF(@IsUsingSystemGeneratedStats = 1)
		BEGIN
	 		IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats
			CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) 
	
			--Pull existing stats data so we know what not to touch			
			INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) 
			SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID
			FROM int.FactStatistic stat
				INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
			WHERE stat.IsDeleted = 0 
				AND stat.FiscalMonthID != 0
				AND stat.FiscalYearID = @CurrentFiscalYearID
				AND stat.TimeClassID = 1
			GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID			
			
			UPDATE fs SET
				SampledProjection01 = ISNULL(Month01, SampledProjection01),
				SampledProjection02 = ISNULL(Month02, SampledProjection02),
				SampledProjection03 = ISNULL(Month03, SampledProjection03),
				SampledProjection04 = ISNULL(Month04, SampledProjection04),
				SampledProjection05 = ISNULL(Month05, SampledProjection05),
				SampledProjection06 = ISNULL(Month06, SampledProjection06),
				SampledProjection07 = ISNULL(Month07, SampledProjection07),
				SampledProjection08 = ISNULL(Month08, SampledProjection08),
				SampledProjection09 = ISNULL(Month09, SampledProjection09),
				SampledProjection10 = ISNULL(Month10, SampledProjection10),
				SampledProjection11 = ISNULL(Month11, SampledProjection11),
				SampledProjection12 = ISNULL(Month12, SampledProjection12)
			FROM
				[fp].[FactStatistics] fs 
				INNER JOIN 
				(SELECT stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName, SUM(Value) as Value
					FROM 
					    (
					    
					    SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value
							FROM fw.FactChargeBasedStatisticsMonthly stat 							
						    INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID
							WHERE stat.FiscalYearID = @CurrentFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 	
					  
					  ) stat					
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID			
						LEFT JOIN #existingStats intData 
						  ON stat.DepartmentID = intData.DepartmentID 
						 AND stat.AccountID = intData.AccountID
						 AND stat.FiscalMonthID = intData.FiscalMonthID
						 AND stat.PatientClassID = intData.PatientClassID
					WHERE stat.FiscalYearID = @CurrentFiscalYearID 					  
					    AND fm.SortOrder <= @MonthsLoaded
					    AND intData.DepartmentID IS NULL
					GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data	
						PIVOT
						(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])
				) as pv 
					ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID
			WHERE
				fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0
			
			
		END
		
	-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	-- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize
	UPDATE
		fs
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END,
		SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END
	FROM
		[fp].[FactStatistics] fs
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID	

	
						
	CREATE TABLE #Totals  (StatisticsID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)) 

	INSERT INTO #Totals (StatisticsID, SampledProjectionTotal)
	SELECT StatisticsID, 
		CASE WHEN @MonthsLoaded = 11 THEN stat.SampledProjection12  
				WHEN @MonthsLoaded = 10 THEN stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 9 THEN stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 8 THEN stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 7 THEN stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 6 THEN stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 5 THEN stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 4 THEN stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 3 THEN stat.SampledProjection04 + stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10  + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 2 THEN stat.SampledProjection03 + stat.SampledProjection04 + stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12
				WHEN @MonthsLoaded = 1 THEN stat.SampledProjection02 + stat.SampledProjection03 + stat.SampledProjection04 + stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12  
				ELSE 0
		END
		FROM [fp].[FactStatistics] stat
	WHERE stat.EntityGroupConfigID = @EntityGroupConfigID
		      
	UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded)  FROM #Totals a	
		   
	UPDATE
		fs
	SET
		InitialProjection01 = CASE WHEN @MonthsLoaded >= 1  THEN fs.SampledProjection01 ELSE t.NewValue END,
		InitialProjection02 = CASE WHEN @MonthsLoaded >= 2  THEN fs.SampledProjection02 ELSE t.NewValue END,
		InitialProjection03 = CASE WHEN @MonthsLoaded >= 3  THEN fs.SampledProjection03 ELSE t.NewValue END,
		InitialProjection04 = CASE WHEN @MonthsLoaded >= 4  THEN fs.SampledProjection04 ELSE t.NewValue END,
		InitialProjection05 = CASE WHEN @MonthsLoaded >= 5  THEN fs.SampledProjection05 ELSE t.NewValue END,
		InitialProjection06 = CASE WHEN @MonthsLoaded >= 6  THEN fs.SampledProjection06 ELSE t.NewValue END,
		InitialProjection07 = CASE WHEN @MonthsLoaded >= 7  THEN fs.SampledProjection07 ELSE t.NewValue END,
		InitialProjection08 = CASE WHEN @MonthsLoaded >= 8  THEN fs.SampledProjection08 ELSE t.NewValue END,
		InitialProjection09 = CASE WHEN @MonthsLoaded >= 9  THEN fs.SampledProjection09 ELSE t.NewValue END,
		InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjection10 ELSE t.NewValue END,
		InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjection11 ELSE t.NewValue END,
		InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjection12 ELSE t.NewValue END
	FROM [fp].[FactStatistics] fs INNER JOIN #Totals t on fs.StatisticsID = t.StatisticsID
	WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID 

	
	
END
GO


---------------------------------------------

-- fp.procSampleStatsOriginalProjectionVolume_WithNewAnnualization
CREATE   PROCEDURE [fp].[procSampleStatsOriginalProjectionVolume_WithNewAnnualization]
	@EntityGroupConfigID int,
	@CurrentFiscalYearID smallint,
	@MonthsLoaded int
AS
BEGIN

/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author	   WI			  Description
** 1      2012-02-17    MD          JAZZ-33345   Move system generated stats sql to before copying of baseline to initial projection
** 2      2022-03-09    NT          JAZZ-34087   Add FiscalMonthID in the JOIN when generating charge based stats 
** 3      2022-04-04    BK          JAZZ-35385   Add Patient Type to join for Charge-Based stats sampling
** 4      2022-06-09    AO          JAZZ-32943   Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics
** 5      2023-07-13    BK          JAZZ-56315   If using provider do not use overwrite with System Generate Stats
** 6      2024-01-31    NH          JAZZ-64064   Move Provider Planning FF as a setting in Plan Config
** 7      2024-07-24    BK          JAZZ-74600   Update annualization logic to use daily 'rate'
** 8      2024-08-07    BK          JAZZ-75213   Add check if using annualization
***************************************************************/

	IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals

	DECLARE @IsProviderPlanningEnabled BIT;
	SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	DECLARE @IsUsingSystemGeneratedStats BIT;
	SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID;

	-- set the orig values for the months where we have data (month sort order <= @MonthsLoaded)
	UPDATE
		fs
	SET
		SampledProjection01 = ISNULL(Month01, 0),
		SampledProjection02 = ISNULL(Month02, 0),
		SampledProjection03 = ISNULL(Month03, 0),
		SampledProjection04 = ISNULL(Month04, 0),
		SampledProjection05 = ISNULL(Month05, 0),
		SampledProjection06 = ISNULL(Month06, 0),
		SampledProjection07 = ISNULL(Month07, 0),
		SampledProjection08 = ISNULL(Month08, 0),
		SampledProjection09 = ISNULL(Month09, 0),
		SampledProjection10 = ISNULL(Month10, 0),
		SampledProjection11 = ISNULL(Month11, 0),
		SampledProjection12 = ISNULL(Month12, 0)
	FROM
		[fp].[FactStatistics] fs
		INNER JOIN 
		(SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value
		 FROM [int].[FactStatistic] stat
		 	  INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
			  INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
		 WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded
		 GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data
		PIVOT
		(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
			ON fs.DepartmentID = pv.DepartmentID
			AND fs.AccountID = pv.AccountID
		INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0)

	IF @IsProviderPlanningEnabled = 1 BEGIN
			DECLARE @BudgetConfigID INT 
			SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID

			-- Update Provider Stats
			UPDATE
				fs
			SET
				SampledProjection01 = ISNULL(Month01, 0),
			SampledProjection02 = ISNULL(Month02, 0),
			SampledProjection03 = ISNULL(Month03, 0),
			SampledProjection04 = ISNULL(Month04, 0),
			SampledProjection05 = ISNULL(Month05, 0),
			SampledProjection06 = ISNULL(Month06, 0),
			SampledProjection07 = ISNULL(Month07, 0),
			SampledProjection08 = ISNULL(Month08, 0),
			SampledProjection09 = ISNULL(Month09, 0),
			SampledProjection10 = ISNULL(Month10, 0),
			SampledProjection11 = ISNULL(Month11, 0),
			SampledProjection12 = ISNULL(Month12, 0)
			FROM [fp].[FactStatistics] fs
				LEFT JOIN 
				(SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID
					FROM [int].[FactProvider] stat
		 				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID
						INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID
					INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID
					INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID
					INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID 
					WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded				
							AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID
					GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data
				PIVOT
				(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv
					ON fs.DepartmentID = pv.DepartmentID
					AND fs.AccountID = pv.AccountID
					AND fs.ProviderID = pv.ProviderID
					AND fs.ProviderLineItemID = pv.ProviderLineItemID
				LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID
			WHERE
				fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- as long as we haven't updated the driver/dependent SubsectionID yet this should be fine

		END

	-- We do not want to annualize projection from fw.FactChargeBasedStatisticsMonthly, months not loaded should be crosswalked from ChargeVolumes
	IF(@IsUsingSystemGeneratedStats = 1)
		BEGIN
	 		IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats
			CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) 
	
			--Pull existing stats data so we know what not to touch			
			INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) 
			SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID
			FROM int.FactStatistic stat
				INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID
			WHERE stat.IsDeleted = 0 
				AND stat.FiscalMonthID != 0
				AND stat.FiscalYearID = @CurrentFiscalYearID
				AND stat.TimeClassID = 1
			GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID			
			
			UPDATE fs SET
				SampledProjection01 = ISNULL(Month01, SampledProjection01),
				SampledProjection02 = ISNULL(Month02, SampledProjection02),
				SampledProjection03 = ISNULL(Month03, SampledProjection03),
				SampledProjection04 = ISNULL(Month04, SampledProjection04),
				SampledProjection05 = ISNULL(Month05, SampledProjection05),
				SampledProjection06 = ISNULL(Month06, SampledProjection06),
				SampledProjection07 = ISNULL(Month07, SampledProjection07),
				SampledProjection08 = ISNULL(Month08, SampledProjection08),
				SampledProjection09 = ISNULL(Month09, SampledProjection09),
				SampledProjection10 = ISNULL(Month10, SampledProjection10),
				SampledProjection11 = ISNULL(Month11, SampledProjection11),
				SampledProjection12 = ISNULL(Month12, SampledProjection12)
			FROM
				[fp].[FactStatistics] fs 
				INNER JOIN 
				(SELECT stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName, SUM(Value) as Value
					FROM 
					    (
					    
					    SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value
							FROM fw.FactChargeBasedStatisticsMonthly stat 							
						    INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID
							WHERE stat.FiscalYearID = @CurrentFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 	
					  
					  ) stat					
						INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID			
						LEFT JOIN #existingStats intData 
						  ON stat.DepartmentID = intData.DepartmentID 
						 AND stat.AccountID = intData.AccountID
						 AND stat.FiscalMonthID = intData.FiscalMonthID
						 AND stat.PatientClassID = intData.PatientClassID
					WHERE stat.FiscalYearID = @CurrentFiscalYearID 					  
					    AND fm.SortOrder <= @MonthsLoaded
					    AND intData.DepartmentID IS NULL
					GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data	
						PIVOT
						(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])
				) as pv 
					ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID
			WHERE
				fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0
			
			
		END
		
	-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	DECLARE @IsLeapYear BIT = (CASE WHEN ( @CurrentFiscalYearID  % 4 = 0 AND  @CurrentFiscalYearID  % 100 <> 0) OR  @CurrentFiscalYearID  % 400 = 0 THEN 1 ELSE 0 END)
	DECLARE @DaysInYear decimal = (SELECT (CASE WHEN @IsLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12)
	DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded)
	DECLARE @MonthsNotLoaded decimal = 12 - @MonthsLoaded
	DECLARE @DaysRemaining decimal = @DaysInYear - @DaysInMonthsLoaded
	DECLARE @SourceYear SMALLINT;
	DECLARE @TimeClassID TINYINT
	SELECT @SourceYear = StatisticsFiscalYearID, @TimeClassID = StatisticsTimeClassID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID

IF @CurrentFiscalYearID = @SourceYear AND @TimeClassID = 1 BEGIN
	UPDATE
		fs
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection11 END,
		SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection12 END
	FROM
		[fp].[FactStatistics] fs
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID	
END ELSE BEGIN
-- copy the baseline data over for months without data (month sort order > @MonthsLoaded)
	-- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize
	UPDATE
		fs
	SET
		SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END,
		SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END,
		SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END,
		SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END,
		SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END,
		SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END,
		SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END,
		SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END,
		SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END,
		SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END,
		SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END
	FROM
		[fp].[FactStatistics] fs
	WHERE
		fs.EntityGroupConfigID = @EntityGroupConfigID	
END
			   
	UPDATE
		fs
	SET
		InitialProjection01 = fs.SampledProjection01,
		InitialProjection02 = fs.SampledProjection02,
		InitialProjection03 = fs.SampledProjection03,
		InitialProjection04 = fs.SampledProjection04,
		InitialProjection05 = fs.SampledProjection05,
		InitialProjection06 = fs.SampledProjection06,
		InitialProjection07 = fs.SampledProjection07,
		InitialProjection08 = fs.SampledProjection08,
		InitialProjection09 = fs.SampledProjection09,
		InitialProjection10 = fs.SampledProjection10,
		InitialProjection11 = fs.SampledProjection11,
		InitialProjection12 = fs.SampledProjection12
	FROM [fp].[FactStatistics] fs 
	WHERE fs.EntityGroupConfigID  = @EntityGroupConfigID 

	
	
END
GO


---------------------------------------------

-- fp.procSampleStatsProjectionData
CREATE PROCEDURE [fp].[procSampleStatsProjectionData]
	@EntityGroupConfigID int
AS
/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1 	2022-10-13	JB		JAZZ-43489	Remove FlexedValue references
	*************************************************************/
BEGIN

	-- update the projection data
	INSERT INTO [fp].[FactStatisticsProjection]([StatisticsID], [BudgetPhaseID], 
											    [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12])
												   
	SELECT [StatisticsID], [BudgetPhaseID], 
		   [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12]
	FROM [fp].[FactStatistics] fs
		 CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID)	
	WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0

END
GO


---------------------------------------------

-- fp.procSampleUnitPerEncounterRates
/**************************************************************
** Change History
**************************************************************
** CID  Date		Author	WI			Description
** 1   2023-01-31   NT     JAZZ-48268   Make change to use the new fp.ChargeVolume (data restructure)
*************************************************************/
CREATE   PROCEDURE [fp].[procSampleUnitPerEncounterRates]
	 @BudgetConfigID INT,
	 @MonthsLoaded INT,
	 @CurrentYearID INT,
	 @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	 @IsDebug BIT = 0
WITH RECOMPILE
 AS
 BEGIN
	IF OBJECT_ID('tempdb..#tbl_ids') IS NOT NULL DROP TABLE #tbl_ids;
	IF OBJECT_ID('tempdb..#units') IS NOT NULL DROP TABLE #units;
	IF OBJECT_ID('tempdb..#proj_units') IS NOT NULL DROP TABLE #proj_units;
	IF OBJECT_ID('tempdb..#unit') IS NOT NULL DROP TABLE #unit;
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
  	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #FilteredData (ChargeVolumeID INT PRIMARY KEY CLUSTERED)
	
	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilteredData
		SELECT cv.ChargeVolumeID
		FROM [fp].[ChargeVolume] cv
		INNER JOIN #FilterByDepartment ft on ft.DepartmentID = cv.DepartmentID	
		WHERE cv.BudgetConfigID = @BudgetConfigID
	END ELSE BEGIN
		INSERT INTO #FilteredData
		SELECT ChargeVolumeID
		FROM [fp].[ChargeVolume] cv	
		WHERE cv.BudgetConfigID = @BudgetConfigID
	END
			  
	CREATE TABLE #filterTable (
		ChargeVolumeID INT PRIMARY KEY CLUSTERED,
		BudgetConfigID INT,
		EntityGroupConfigID INT,
		SampledBudgetChargeUnits DECIMAL(19, 8) NOT NULL DEFAULT(0),
		SampledBudgetEncounters DECIMAL(19, 8) NOT NULL DEFAULT(0),
		SampledProjectionChargeUnits DECIMAL(19, 8) NOT NULL DEFAULT(0),
		SampledProjectionEncounters DECIMAL(19, 8) NOT NULL DEFAULT(0),
		SampledProjectionUnits01 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits02 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits03 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits04 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits05 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits06 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits07 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits08 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits09 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits10 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionUnits11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		SampledProjectionEncounters01 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters02 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters03 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters04 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters05 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters06 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters07 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters08 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters09 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters10 DECIMAL(19, 8) NOT NULL DEFAULT(0), 
		SampledProjectionEncounters11 DECIMAL(19, 8) NOT NULL DEFAULT(0)
	);

	INSERT INTO #filterTable (
			ChargeVolumeID, EntityGroupConfigID, BudgetConfigID, 
			SampledBudgetChargeUnits, SampledBudgetEncounters, SampledProjectionChargeUnits, SampledProjectionEncounters,
			SampledProjectionUnits01, SampledProjectionUnits02, SampledProjectionUnits03, SampledProjectionUnits04, SampledProjectionUnits05, SampledProjectionUnits06, 
			SampledProjectionUnits07, SampledProjectionUnits08, SampledProjectionUnits09, SampledProjectionUnits10, SampledProjectionUnits11,
			SampledProjectionEncounters01, SampledProjectionEncounters02, SampledProjectionEncounters03, SampledProjectionEncounters04, 
			SampledProjectionEncounters05, SampledProjectionEncounters06, SampledProjectionEncounters07, SampledProjectionEncounters08, 
			SampledProjectionEncounters09, SampledProjectionEncounters10, SampledProjectionEncounters11)
	SELECT cv.ChargeVolumeID, cv.EntityGroupConfigID, cv.BudgetConfigID, 
		   cv.SampledBudgetTotal AS SampledBudgetChargeUnits, SUM(sle.InitialBudgetTotal) AS SampledBudgetEncounters, 
		   cv.SampledProjectionTotal AS SampledProjectionChargeUnits, SUM(sle.InitialProjectionTotal) AS SampledProjectionEncounters,
		   cv.SampledProjection01, cv.SampledProjection02, cv.SampledProjection03, cv.SampledProjection04, cv.SampledProjection05, cv.SampledProjection06, 
		   cv.SampledProjection07, cv.SampledProjection08, cv.SampledProjection09, cv.SampledProjection10, cv.SampledProjection11,
		SUM(sle.InitialProjection01) AS InitialProjection01, 
		SUM(sle.InitialProjection02) AS InitialProjection02, 
		SUM(sle.InitialProjection03) AS InitialProjection03, 
		SUM(sle.InitialProjection04) AS InitialProjection04, 
		SUM(sle.InitialProjection05) AS InitialProjection05, 
		SUM(sle.InitialProjection06) AS InitialProjection06, 
		SUM(sle.InitialProjection07) AS InitialProjection07, 
		SUM(sle.InitialProjection08) AS InitialProjection08, 
		SUM(sle.InitialProjection09) AS InitialProjection09, 
		SUM(sle.InitialProjection10) AS InitialProjection10, 
		SUM(sle.InitialProjection11) AS InitialProjection11
	FROM [fp].[ChargeVolume] cv
	INNER JOIN #FilteredData filter ON cv.ChargeVolumeID = filter.ChargeVolumeID
    INNER JOIN fp.ServiceLineEncounter sle 
        ON cv.BudgetConfigID = sle.BudgetConfigID
		AND cv.AgeCohortID = sle.AgeCohortID
        AND cv.MedicalSurgicalID = sle.MedicalSurgicalID 
        AND cv.PatientClassID = sle.PatientClassID
        AND cv.ServiceLineID = sle.ServiceLineID 
        AND cv.ServiceEntityID = sle.EntityID
        AND cv.MSDRGID = sle.MSDRGID
        AND cv.PrimaryCPTID = sle.CPTID
        AND cv.ServiceProviderID = sle.ProviderID
	WHERE cv.BudgetConfigID = @BudgetConfigID
	    AND cv.UnitTypeID = 145
	GROUP BY cv.ChargeVolumeID, cv.EntityGroupConfigID, cv.BudgetConfigID, cv.SampledBudgetTotal, cv.SampledProjectionTotal,
		cv.SampledProjection01, cv.SampledProjection02, cv.SampledProjection03, cv.SampledProjection04, cv.SampledProjection05, cv.SampledProjection06, cv.SampledProjection07, cv.SampledProjection08, cv.SampledProjection09, cv.SampledProjection10, cv.SampledProjection11
			  
	IF (@IsDebug = 1)
	BEGIN
		SELECT 
			'Budget UnitsPerEncounter Calculation',
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter01,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter02,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter03,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter04,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter05,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter06,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter07,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter08,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter09,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter10,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter11,
			IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter12,
			cv.*
	    FROM [fp].[ChargeVolume] cv
	        INNER JOIN #filterTable ft 
			 ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index
			AND cv.ChargeVolumeID = ft.ChargeVolumeID
		WHERE cv.BudgetConfigID = @BudgetConfigID
		  AND cv.UnitTypeID = 145
	END ELSE
	BEGIN
	    UPDATE cv
		SET 
			cv.InitialBudgetUnitsPerEncounter01 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter02 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter03 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter04 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter05 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter06 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter07 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter08 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter09 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter10 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter11 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0),
			cv.InitialBudgetUnitsPerEncounter12 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0)
	    FROM [fp].[ChargeVolume] cv
	        INNER JOIN #filterTable ft 
			 ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index
			AND cv.ChargeVolumeID = ft.ChargeVolumeID
		WHERE cv.BudgetConfigID = @BudgetConfigID
		  AND cv.UnitTypeID = 145
	END
		
	IF OBJECT_ID('tempdb..#tbl_entitygroup') IS NOT NULL DROP TABLE #tbl_entitygroup;
	CREATE TABLE #tbl_entitygroup (EntityGroupConfigID INT, IsAnnualized INT);
			
	INSERT INTO #tbl_entitygroup (EntityGroupConfigID, IsAnnualized)
	SELECT EntityGroupConfigID, CASE WHEN ServiceLineEncounterTimeClassID = 1 AND ServiceLineEncounterFiscalYearID = @CurrentYearID THEN 1 ELSE 0 END
	FROM [fp].[EntityGroupConfig] egc 
	INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID 
	WHERE bc.BudgetConfigID = @BudgetConfigID		

	IF (@IsDebug = 1)
	BEGIN
		SELECT 'Entity Groups Sampled', EntityGroupConfigID, IsAnnualized FROM #tbl_entitygroup
	END

	-- Process Entity Group Configs that are not annualized
	IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 0) BEGIN				
		IF (@IsDebug = 1)
		BEGIN
			SELECT 
				'Not Annualized Projection UnitsPerEncounter Calculation',
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter01,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter02,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter03,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter04,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter05,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter06,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter07,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter08,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter09,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter10,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter11,
				IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter12,
				cv.*
		    FROM [fp].[ChargeVolume] cv
			INNER JOIN #tbl_entitygroup egc 
			 ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
		    INNER JOIN #filterTable ft 
			 ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index
			AND cv.ChargeVolumeID = ft.ChargeVolumeID
		    WHERE cv.BudgetConfigID = @BudgetConfigID
		        AND cv.UnitTypeID = 145
				AND egc.IsAnnualized = 0
		END ELSE
		BEGIN
			UPDATE cv
			SET 
				cv.InitialProjectionUnitsPerEncounter01 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter02 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter03 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter04 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter05 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter06 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter07 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter08 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter09 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter10 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter11 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0),
				cv.InitialProjectionUnitsPerEncounter12 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0)
		    FROM [fp].[ChargeVolume] cv
			INNER JOIN #tbl_entitygroup egc 
			 ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
		    INNER JOIN #filterTable ft 
			 ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index
			AND cv.ChargeVolumeID = ft.ChargeVolumeID
		    WHERE cv.BudgetConfigID = @BudgetConfigID
		        AND cv.UnitTypeID = 145
				AND egc.IsAnnualized = 0
		END
	 END
	 
	-- Annualized
	IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 1) BEGIN
	
        IF OBJECT_ID('tempdb..#tbl_UnitsPerEncounters') IS NOT NULL DROP TABLE #tbl_UnitsPerEncounters;
		
	    CREATE TABLE #tbl_UnitsPerEncounters (
			ChargeVolumeID INT PRIMARY KEY CLUSTERED,
			EntityGroupConfigID INT, 			
			ChargeVolumeTotal DECIMAL(19,8), 
			ServiceLineTotal DECIMAL(19,8), 
			UnitsPerEncounter DECIMAL(19,8)
		);

		INSERT INTO #tbl_UnitsPerEncounters (ChargeVolumeID, EntityGroupConfigID, ChargeVolumeTotal, ServiceLineTotal, UnitsPerEncounter)
		SELECT ChargeVolumeID, egc.EntityGroupConfigID,
		CASE 
			 WHEN @MonthsLoaded  = 12 THEN ft.SampledProjectionChargeUnits
			 WHEN @MonthsLoaded >= 11 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08 + ft.SampledProjectionUnits09 + ft.SampledProjectionUnits10 + ft.SampledProjectionUnits11
			 WHEN @MonthsLoaded >= 10 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08 + ft.SampledProjectionUnits09 + ft.SampledProjectionUnits10
			 WHEN @MonthsLoaded >= 9  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08 + ft.SampledProjectionUnits09 
			 WHEN @MonthsLoaded >= 8  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08
			 WHEN @MonthsLoaded >= 7  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07
			 WHEN @MonthsLoaded >= 6  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06
			 WHEN @MonthsLoaded >= 5  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 
			 WHEN @MonthsLoaded >= 4  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04
			 WHEN @MonthsLoaded >= 3  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03
			 WHEN @MonthsLoaded >= 2  THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 
			ELSE ft.SampledProjectionUnits01				
			END AS ChargeVolumeTotal,
		CASE 
			 WHEN @MonthsLoaded  = 12 THEN ft.SampledProjectionEncounters
			 WHEN @MonthsLoaded >= 11 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08 + ft.SampledProjectionEncounters09 + ft.SampledProjectionEncounters10 + ft.SampledProjectionEncounters11
			 WHEN @MonthsLoaded >= 10 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08 + ft.SampledProjectionEncounters09 + ft.SampledProjectionEncounters10
			 WHEN @MonthsLoaded >= 9  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08 + ft.SampledProjectionEncounters09 
			 WHEN @MonthsLoaded >= 8  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08
			 WHEN @MonthsLoaded >= 7  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07
			 WHEN @MonthsLoaded >= 6  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06
			 WHEN @MonthsLoaded >= 5  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 
			 WHEN @MonthsLoaded >= 4  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04
			 WHEN @MonthsLoaded >= 3  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03
			 WHEN @MonthsLoaded >= 2  THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 
			ELSE ft.SampledProjectionEncounters01				
			END AS ServiceLineTotal, 0	
		FROM #tbl_entitygroup egc	
			INNER JOIN #filterTable ft ON egc.EntityGroupConfigID = ft.EntityGroupConfigID
	    WHERE egc.IsAnnualized = 1
			
		UPDATE #tbl_UnitsPerEncounters SET UnitsPerEncounter = ChargeVolumeTotal / ServiceLineTotal WHERE ServiceLineTotal <> 0;
			
		IF (@IsDebug = 1)
		BEGIN
			SELECT 'Annualized Projection UnitsPerEncounter Calculation', ChargeVolumeID, EntityGroupConfigID, ChargeVolumeTotal, ServiceLineTotal, UnitsPerEncounter
			FROM #tbl_UnitsPerEncounters

			SELECT 
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter01,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter02,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter03,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter04,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter05,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter06,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter07,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter08,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter09,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter10,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter11,
				UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter12,
				cv.ChargeVolumeID, 
				cv.EntityGroupConfigID, 
				UnitsPerEncounter.ChargeVolumeTotal, 
				UnitsPerEncounter.ServiceLineTotal
			FROM [fp].[ChargeVolume] cv			
			INNER JOIN #tbl_entitygroup egc 
			 ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
			INNER JOIN #tbl_UnitsPerEncounters UnitsPerEncounter 
			 ON cv.EntityGroupConfigID = UnitsPerEncounter.EntityGroupConfigID
			AND cv.ChargeVolumeID = UnitsPerEncounter.ChargeVolumeID
			WHERE cv.BudgetConfigID = @BudgetConfigID
		 	  AND cv.UnitTypeID = 145
			  AND egc.IsAnnualized = 1
		END ELSE
		BEGIN
			UPDATE cv
			SET 
				cv.InitialProjectionUnitsPerEncounter01 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter02 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter03 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter04 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter05 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter06 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter07 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter08 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter09 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter10 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter11 = UnitsPerEncounter.UnitsPerEncounter,
				cv.InitialProjectionUnitsPerEncounter12 = UnitsPerEncounter.UnitsPerEncounter
			FROM [fp].[ChargeVolume] cv			
			INNER JOIN #tbl_entitygroup egc 
			 ON cv.EntityGroupConfigID = egc.EntityGroupConfigID
			INNER JOIN #tbl_UnitsPerEncounters UnitsPerEncounter 
			 ON cv.EntityGroupConfigID = UnitsPerEncounter.EntityGroupConfigID
			AND cv.ChargeVolumeID = UnitsPerEncounter.ChargeVolumeID
			WHERE cv.BudgetConfigID = @BudgetConfigID
			  AND cv.UnitTypeID = 145
			  AND egc.IsAnnualized = 1
		END					
	END		
 END
GO


---------------------------------------------

-- fp.procServiceLineEncountersApplySpread
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2022-02-18  MV      JAZZ-33683		Spread Target and Budget
** 2	2022-09-13	SD		JAZZ-42555		Skip newly added dimensionality records during Encounter spreads
** 3	2023-02-13	BW		JAZZ-48306		Updated for new data model, use [fp].[ServiceLineEncounter]
** 4	2023-05-19	SD		JAZZ-54066		Added changes for deleting 'Apply Encounter spread on Target and Budget' FF after restructure Service Line Encounters page
** 5 	2024-01-22	MY		JAZZ-64799		History Viewer does not handle Spread Impact for Monthly Values
*************************************************************/ 
CREATE   PROCEDURE [fp].[procServiceLineEncountersApplySpread]
  @BudgetConfigID INT
AS
BEGIN
	DECLARE @volumeUnitType INT = 140;

	IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable;
	IF OBJECT_ID('tempdb..#spreadsChangeHistory') IS NOT NULL DROP TABLE #spreadsChangeHistory;

	CREATE TABLE #spreadsChangeHistory (
		ServiceLineEncounterID INT,
		OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
	);

	CREATE TABLE #filterTable (ServiceLineEncounterID INT PRIMARY KEY CLUSTERED);

	IF EXISTS(SELECT 1 FROM [fp].[viewBudgetConfigSetting] setting WHERE setting.Name = 'Skip newly added dimensionality records during Encounter spreads' AND setting.BudgetConfigID = @BudgetConfigID AND setting.Value = 1) 
	BEGIN
		INSERT INTO #filterTable (ServiceLineEncounterID)
			SELECT DISTINCT basis.ServiceLineEncounterID
			FROM [fp].[ServiceLineEncounter] basis
				INNER JOIN [fp].[ServiceLineEncounterSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.EntityID = basis.EntityID AND spread.ServiceLineID = basis.ServiceLineID AND spread.PatientClassID = basis.PatientClassID 
			WHERE basis.BudgetConfigID = @BudgetConfigID
				AND basis.UnitTypeID = @volumeUnitType
				AND basis.BudgetLockType <> 1 AND basis.BudgetLockType <> 7
				AND basis.TargetLockType <> 1 AND basis.TargetLockType <> 7 AND basis.isNew = 0
	END
	ELSE
	BEGIN
		INSERT INTO #filterTable (ServiceLineEncounterID)
			SELECT DISTINCT basis.ServiceLineEncounterID
			FROM [fp].[ServiceLineEncounter] basis
				INNER JOIN [fp].[ServiceLineEncounterSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.EntityID = basis.EntityID AND spread.ServiceLineID = basis.ServiceLineID AND spread.PatientClassID = basis.PatientClassID 
			WHERE basis.BudgetConfigID = @BudgetConfigID
				AND basis.UnitTypeID = @volumeUnitType
				AND basis.BudgetLockType <> 1 AND basis.BudgetLockType <> 7 
				AND basis.TargetLockType <> 1 AND basis.TargetLockType <> 7 
	END

	--Apply spreads for target firstly
	UPDATE sle
	SET	 sle.TargetLockType = 6, sle.TargetLockFlag = 1
			, TargetAdjusted01 = CAST(TargetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8))
			, TargetAdjusted02 = 
				CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
			, TargetAdjusted03 = 
				CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
			, TargetAdjusted04 = 
				CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
			, TargetAdjusted05 = 
				CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
			, TargetAdjusted06 = 
				CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
			, TargetAdjusted07 = 
				CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
			, TargetAdjusted08 = 
				CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
			, TargetAdjusted09 = 
				CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
			, TargetAdjusted10 = 
				CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
			, TargetAdjusted11 = 
				CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
			, TargetAdjusted12 = 
				CASE WHEN SpreadPercentage12 != 0
				THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
				ELSE CAST(TargetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
	FROM [fp].[viewServiceLineEncounterSpreads] encsp
		INNER JOIN [fp].[ServiceLineEncounter] sle ON encsp.BudgetConfigID = sle.BudgetConfigID AND encsp.EntityID = sle.EntityID AND encsp.ServiceLineID = sle.ServiceLineID AND encsp.PatientClassID = sle.PatientClassID
		INNER JOIN #filterTable tmp on sle.ServiceLineEncounterID = tmp.ServiceLineEncounterID
	WHERE encsp.IsInactive = 0

	--Apply spreads for budget
	UPDATE sle
	SET	 sle.BudgetLockType = 6, sle.BudgetLockFlag = 1
			, BudgetAdjusted01 = CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8))
			, BudgetAdjusted02 = 
				CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
			, BudgetAdjusted03 = 
				CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
			, BudgetAdjusted04 = 
				CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
			, BudgetAdjusted05 = 
				CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
			, BudgetAdjusted06 = 
				CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
			, BudgetAdjusted07 = 
				CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
			, BudgetAdjusted08 = 
				CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
			, BudgetAdjusted09 = 
				CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
			, BudgetAdjusted10 = 
				CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
			, BudgetAdjusted11 = 
				CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
			, BudgetAdjusted12 = 
				CASE WHEN SpreadPercentage12 != 0
				THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
				ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
	OUTPUT -- Only doing budget here because Target and Budget are always the same value and when we make encounters like every other section this will help be one less thing to update
	    inserted.ServiceLineEncounterID, 
		deleted.BudgetAdjusted01, deleted.BudgetAdjusted02, deleted.BudgetAdjusted03, deleted.BudgetAdjusted04, deleted.BudgetAdjusted05, deleted.BudgetAdjusted06,
		deleted.BudgetAdjusted07, deleted.BudgetAdjusted08, deleted.BudgetAdjusted09, deleted.BudgetAdjusted10, deleted.BudgetAdjusted11, deleted.BudgetAdjusted12,
		inserted.BudgetAdjusted01, inserted.BudgetAdjusted02, inserted.BudgetAdjusted03, inserted.BudgetAdjusted04, inserted.BudgetAdjusted05, inserted.BudgetAdjusted06,
		inserted.BudgetAdjusted07, inserted.BudgetAdjusted08, inserted.BudgetAdjusted09, inserted.BudgetAdjusted10, inserted.BudgetAdjusted11, inserted.BudgetAdjusted12
	INTO
	    #spreadsChangeHistory (ServiceLineEncounterID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) 
	FROM [fp].[viewServiceLineEncounterSpreads] encsp
		INNER JOIN [fp].[ServiceLineEncounter] sle ON encsp.BudgetConfigID = sle.BudgetConfigID AND encsp.EntityID = sle.EntityID AND encsp.ServiceLineID = sle.ServiceLineID AND encsp.PatientClassID = sle.PatientClassID
		INNER JOIN #filterTable tmp on sle.ServiceLineEncounterID = tmp.ServiceLineEncounterID
	WHERE encsp.IsInactive = 0

	-- Populate Change History
	IF EXISTS(SELECT 1 
			  FROM fp.BudgetConfigSetting setting
				INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
			  WHERE def.Name = 'Spreads Change History Logic Is Enabled'
			  	AND setting.Value = 1)
	BEGIN
		
		INSERT INTO fp.ServiceLineEncounterSpreadsChangeHistory (ServiceLineEncounterID, BudgetConfigID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
						OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,	NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
						NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
		SELECT ServiceLineEncounterID, @BudgetConfigID,
			ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0),
			ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0),
			ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0),
			ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0)
		FROM #spreadsChangeHistory
		WHERE 1 = 1
			AND (
				   OldValue01 != NewValue01
				OR OldValue02 != NewValue02
				OR OldValue03 != NewValue03
				OR OldValue04 != NewValue04
				OR OldValue05 != NewValue05
				OR OldValue06 != NewValue06
				OR OldValue07 != NewValue07
				OR OldValue08 != NewValue08
				OR OldValue09 != NewValue09
				OR OldValue10 != NewValue10
				OR OldValue11 != NewValue11
				OR OldValue12 != NewValue12
			)
	END
		
END
GO


---------------------------------------------

-- fp.procSetupBudgetConfigDefaultHoursMix
CREATE PROCEDURE fp.procSetupBudgetConfigDefaultHoursMix
 AS
 BEGIN

	INSERT INTO fp.BudgetConfigDefaultHoursMix (BudgetConfigGUID, PayCodeGroupID)

	SELECT bc.BudgetConfigGUID, dpcg.PayCodeGroupID
	FROM fp.BudgetConfig bc
	CROSS JOIN fw.DimPayCodeGroup dpcg
	WHERE dpcg.PayCodeGroupID != 0
	EXCEPT
	SELECT bcdhm.BudgetConfigGUID, bcdhm.PayCodeGroupID
	FROM fp.BudgetConfigDefaultHoursMix bcdhm;
	
 END
GO


---------------------------------------------

-- fp.procStaffingApplySpread
CREATE   PROCEDURE [fp].[procStaffingApplySpread]
  @BudgetConfigID int,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI			Description
	** 1	2021-01-21	BW		JAZZ-13122	Performance update for employee budgeting; using option recompile on long running Update stmt: Dollars based on Hours and Wage Rate
	** 2	2021-04-12	OP		JAZZ-18025	Filtered by subsection
	** 3	2022-01-28	NT		JAZZ-32003	Add EmployeeID in the JOIN when recalculating FTEs and Dollars
	** 4	2023-02-07	MY		JAZZ-63890	Added Change History to Spreads
	** 5	2023-12-13	BW		JAZZ-62541	Update for new data structure - update to use the latest working hours view [fp].[viewWorkingHours]
	** 6	2024-01-02	MY		JAZZ-64770	Upgrade JAZZ-63890 for Restructure Branch
	** 7	2024-01-02	BK		JAZZ-xxxxx	Fix with failing tests
	*************************************************************/ 

	DECLARE @dollarsUnitType INT = 34;
	DECLARE @hoursUnitType INT = 51;
	DECLARE @ftesUnitType INT = 144;
	DECLARE @wageRateUnitType INT = 159;

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #filterTable (StaffingID INT PRIMARY KEY CLUSTERED);

	CREATE TABLE #spreadsChangeHistory (
		StaffingID INT,
		UnitTypeID SMALLINT NOT NULL DEFAULT(0),
		OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
	);

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN

		INSERT INTO #filterTable (StaffingID)
		SELECT DISTINCT basis.StaffingID
		FROM [fp].[Staffing] basis
			INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID
			INNER JOIN [fp].[StaffingSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID 
				AND spread.DepartmentID = basis.DepartmentID 
				AND spread.JobCodeID = basis.JobCodeID 
				AND spread.PayCodeGroupID = basis.PayCodeGroupID
		WHERE basis.BudgetConfigID = @BudgetConfigID 
			AND basis.VariabilityID = 1 -- fixed
			AND spread.IsInactive = 0
			AND (
				(basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments
			 OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments
			 OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments
			)
			AND basis.SubsectionID = 3 -- Staffing Stuff

	END ELSE BEGIN

		-- If the table source dimensionality is unfiltered, we don't wanna join on the department filter.
		INSERT INTO #filterTable (StaffingID)
		SELECT DISTINCT basis.StaffingID
		FROM [fp].[Staffing] basis
			INNER JOIN [fp].[StaffingSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.JobCodeID = basis.JobCodeID AND spread.PayCodeGroupID = basis.PayCodeGroupID
		WHERE basis.BudgetConfigID = @BudgetConfigID 
			AND basis.VariabilityID = 1 -- fixed
			AND spread.IsInactive = 0
			AND (
				(basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments
			 OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments
			 OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments
			)
			AND basis.SubsectionID = 3 -- Staffing Stuff

	END

	-- Update dollars
	UPDATE dollars
	SET   
		  dollars.BudgetAdjustedDollars01 = CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01 AS DECIMAL(19,8))
		, dollars.BudgetAdjustedDollars02 = 
			CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars03 = 
			CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars04 = 
			CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars05 = 
			CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars06 = 
			CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars07 = 
			CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars08 = 
			CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars09 = 
			CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars10 = 
			CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars11 = 
			CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
		, dollars.BudgetAdjustedDollars12 = 
			CASE WHEN SpreadPercentage12 != 0
			THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
			ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
		, BudgetDollarsLockType = CASE WHEN dollars.BudgetDollarsLockType IN (1,4,5) THEN dollars.BudgetDollarsLockType ELSE 6 END
		, BudgetDollarsLockFlag = 1
	OUTPUT 
	    inserted.StaffingID, 34, 
		deleted.BudgetAdjustedDollars01, deleted.BudgetAdjustedDollars02, deleted.BudgetAdjustedDollars03, deleted.BudgetAdjustedDollars04, deleted.BudgetAdjustedDollars05, deleted.BudgetAdjustedDollars06,
		deleted.BudgetAdjustedDollars07, deleted.BudgetAdjustedDollars08, deleted.BudgetAdjustedDollars09, deleted.BudgetAdjustedDollars10, deleted.BudgetAdjustedDollars11, deleted.BudgetAdjustedDollars12,
		inserted.BudgetAdjustedDollars01, inserted.BudgetAdjustedDollars02, inserted.BudgetAdjustedDollars03, inserted.BudgetAdjustedDollars04, inserted.BudgetAdjustedDollars05, inserted.BudgetAdjustedDollars06,
		inserted.BudgetAdjustedDollars07, inserted.BudgetAdjustedDollars08, inserted.BudgetAdjustedDollars09, inserted.BudgetAdjustedDollars10, inserted.BudgetAdjustedDollars11, inserted.BudgetAdjustedDollars12
	INTO
	    #spreadsChangeHistory (StaffingID, UnitTypeID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) 
	FROM [fp].[viewStaffingSpreads] spread
		INNER JOIN [fp].[Staffing] dollars ON spread.BudgetConfigID = dollars.BudgetConfigID 
			AND spread.DepartmentID = dollars.DepartmentID 
			AND spread.JobCodeID = dollars.JobCodeID 
			AND spread.PayCodeGroupID = dollars.PayCodeGroupID
		INNER JOIN #filterTable tmp on dollars.StaffingID = tmp.StaffingID
	WHERE spread.IsInactive = 0
	   AND ((BudgetAdjustedHours01 = 0
	      AND BudgetAdjustedHours02 = 0
	      AND BudgetAdjustedHours03 = 0
	      AND BudgetAdjustedHours04 = 0
	      AND BudgetAdjustedHours05 = 0
	      AND BudgetAdjustedHours06 = 0
	      AND BudgetAdjustedHours07 = 0
	      AND BudgetAdjustedHours08 = 0
	      AND BudgetAdjustedHours09 = 0
	      AND BudgetAdjustedHours10 = 0
	      AND BudgetAdjustedHours11 = 0
	      AND BudgetAdjustedHours12 = 0))

	-- Update hours
	UPDATE hours
	  SET 
		  hours.BudgetAdjustedHours01 = CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage01 AS DECIMAL(19,8))
		, hours.BudgetAdjustedHours02 = 
			CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours03 = 
			CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours04 = 
			CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours05 = 
			CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours06 = 
			CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours07 = 
			CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours08 = 
			CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours09 = 
			CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours10 = 
			CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours11 = 
			CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
		, hours.BudgetAdjustedHours12 = 
			CASE WHEN SpreadPercentage12 != 0
			THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
			ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
		, BudgetHoursLockType = CASE WHEN BudgetHoursLockType IN (1,4,5) THEN BudgetHoursLockType ELSE 6 END
		, BudgetHoursLockFlag = 1
	OUTPUT 
	    inserted.StaffingID, 51, 
		deleted.BudgetAdjustedHours01, deleted.BudgetAdjustedHours02, deleted.BudgetAdjustedHours03, deleted.BudgetAdjustedHours04, deleted.BudgetAdjustedHours05, deleted.BudgetAdjustedHours06,
		deleted.BudgetAdjustedHours07, deleted.BudgetAdjustedHours08, deleted.BudgetAdjustedHours09, deleted.BudgetAdjustedHours10, deleted.BudgetAdjustedHours11, deleted.BudgetAdjustedHours12,
		inserted.BudgetAdjustedHours01, inserted.BudgetAdjustedHours02, inserted.BudgetAdjustedHours03, inserted.BudgetAdjustedHours04, inserted.BudgetAdjustedHours05, inserted.BudgetAdjustedHours06,
		inserted.BudgetAdjustedHours07, inserted.BudgetAdjustedHours08, inserted.BudgetAdjustedHours09, inserted.BudgetAdjustedHours10, inserted.BudgetAdjustedHours11, inserted.BudgetAdjustedHours12
	INTO
	    #spreadsChangeHistory (StaffingID, UnitTypeID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
	FROM [fp].[viewStaffingSpreads] spread
		INNER JOIN [fp].[Staffing] hours ON spread.BudgetConfigID = hours.BudgetConfigID 
			AND spread.DepartmentID = hours.DepartmentID 
			AND spread.JobCodeID = hours.JobCodeID 
			AND spread.PayCodeGroupID = hours.PayCodeGroupID
		INNER JOIN #filterTable tmp on hours.StaffingID = tmp.StaffingID
	WHERE spread.IsInactive = 0
	    AND (hours.BudgetAdjustedHours01 <> 0
	     OR hours.BudgetAdjustedHours02 <> 0
	     OR hours.BudgetAdjustedHours03 <> 0
	     OR hours.BudgetAdjustedHours04 <> 0
	     OR hours.BudgetAdjustedHours05 <> 0
	     OR hours.BudgetAdjustedHours06 <> 0
	     OR hours.BudgetAdjustedHours07 <> 0
	     OR hours.BudgetAdjustedHours08 <> 0
	     OR hours.BudgetAdjustedHours09 <> 0
	     OR hours.BudgetAdjustedHours10 <> 0
	     OR hours.BudgetAdjustedHours11 <> 0
	     OR hours.BudgetAdjustedHours12 <> 0)

	-- Recalculate FTEs based on Hours
	UPDATE ftes
	SET
	    ftes.BudgetAdjustedFTEs01 = CASE WHEN hours.BudgetWorkingHours01 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours01 / hours.BudgetWorkingHours01 END,
	    ftes.BudgetAdjustedFTEs02 = CASE WHEN hours.BudgetWorkingHours02 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours02 / hours.BudgetWorkingHours02 END,
	    ftes.BudgetAdjustedFTEs03 = CASE WHEN hours.BudgetWorkingHours03 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours03 / hours.BudgetWorkingHours03 END,
	    ftes.BudgetAdjustedFTEs04 = CASE WHEN hours.BudgetWorkingHours04 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours04 / hours.BudgetWorkingHours04 END,
	    ftes.BudgetAdjustedFTEs05 = CASE WHEN hours.BudgetWorkingHours05 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours05 / hours.BudgetWorkingHours05 END,
	    ftes.BudgetAdjustedFTEs06 = CASE WHEN hours.BudgetWorkingHours06 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours06 / hours.BudgetWorkingHours06 END,
	    ftes.BudgetAdjustedFTEs07 = CASE WHEN hours.BudgetWorkingHours07 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours07 / hours.BudgetWorkingHours07 END,
	    ftes.BudgetAdjustedFTEs08 = CASE WHEN hours.BudgetWorkingHours08 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours08 / hours.BudgetWorkingHours08 END,
	    ftes.BudgetAdjustedFTEs09 = CASE WHEN hours.BudgetWorkingHours09 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours09 / hours.BudgetWorkingHours09 END,
	    ftes.BudgetAdjustedFTEs10 = CASE WHEN hours.BudgetWorkingHours10 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours10 / hours.BudgetWorkingHours10 END,
	    ftes.BudgetAdjustedFTEs11 = CASE WHEN hours.BudgetWorkingHours11 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours11 / hours.BudgetWorkingHours11 END,
	    ftes.BudgetAdjustedFTEs12 = CASE WHEN hours.BudgetWorkingHours12 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours12 / hours.BudgetWorkingHours12 END,
		ftes.BudgetFTEsLockType = CASE WHEN ftes.BudgetFTEsLockType IN (1,4,5) THEN ftes.BudgetFTEsLockType ELSE 6 END,
		ftes.BudgetFTEsLockFlag = 1
	OUTPUT 
	    inserted.StaffingID, 144, 
		deleted.BudgetAdjustedFTEs01, deleted.BudgetAdjustedFTEs02, deleted.BudgetAdjustedFTEs03, deleted.BudgetAdjustedFTEs04, deleted.BudgetAdjustedFTEs05, deleted.BudgetAdjustedFTEs06,
		deleted.BudgetAdjustedFTEs07, deleted.BudgetAdjustedFTEs08, deleted.BudgetAdjustedFTEs09, deleted.BudgetAdjustedFTEs10, deleted.BudgetAdjustedFTEs11, deleted.BudgetAdjustedFTEs12,
		inserted.BudgetAdjustedFTEs01, inserted.BudgetAdjustedFTEs02, inserted.BudgetAdjustedFTEs03, inserted.BudgetAdjustedFTEs04, inserted.BudgetAdjustedFTEs05, inserted.BudgetAdjustedFTEs06,
		inserted.BudgetAdjustedFTEs07, inserted.BudgetAdjustedFTEs08, inserted.BudgetAdjustedFTEs09, inserted.BudgetAdjustedFTEs10, inserted.BudgetAdjustedFTEs11, inserted.BudgetAdjustedFTEs12
	INTO
	    #spreadsChangeHistory (StaffingID, UnitTypeID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
	FROM [fp].[Staffing] ftes
	    INNER JOIN [fp].[viewWorkingHours] hours
	    ON ftes.DepartmentID = hours.DepartmentID
	        AND ftes.EntityID = hours.EntityID
	        AND ftes.JobCodeID = hours.JobCodeID
	        AND ftes.PayCodeGroupID = hours.PayCodeGroupID
	        AND ftes.ProductiveClassID = hours.ProductiveClassID
	        AND ftes.EntityGroupConfigID = hours.EntityGroupConfigID
	        AND ftes.EmployeeID = hours.EmployeeID
	        AND ftes.VariabilityID = hours.VariabilityID
	    INNER JOIN #filterTable f ON f.StaffingID = ftes.StaffingID
	WHERE
	    ftes.VariabilityID = 1
	    AND ftes.ProductiveClassID NOT IN (4, 5, 6) -- Dollars-Only, Differential, Productive Non-FTE 
	    AND (ftes.BudgetAdjustedHours01 <> 0
	    OR ftes.BudgetAdjustedHours02 <> 0
	    OR ftes.BudgetAdjustedHours03 <> 0
	    OR ftes.BudgetAdjustedHours04 <> 0
	    OR ftes.BudgetAdjustedHours05 <> 0
	    OR ftes.BudgetAdjustedHours06 <> 0
	    OR ftes.BudgetAdjustedHours07 <> 0
	    OR ftes.BudgetAdjustedHours08 <> 0
	    OR ftes.BudgetAdjustedHours09 <> 0
	    OR ftes.BudgetAdjustedHours10 <> 0
	    OR ftes.BudgetAdjustedHours11 <> 0
	    OR ftes.BudgetAdjustedHours12 <> 0)

	-- Recalculate Dollars based on Hours and Wage Rate
	UPDATE base
	SET
	    base.BudgetAdjustedDollars01 = BudgetAdjustedHours01 * wageRate.BudgetAdjusted01,
	    base.BudgetAdjustedDollars02 = BudgetAdjustedHours02 * wageRate.BudgetAdjusted02,
	    base.BudgetAdjustedDollars03 = BudgetAdjustedHours03 * wageRate.BudgetAdjusted03,
	    base.BudgetAdjustedDollars04 = BudgetAdjustedHours04 * wageRate.BudgetAdjusted04,
	    base.BudgetAdjustedDollars05 = BudgetAdjustedHours05 * wageRate.BudgetAdjusted05,
	    base.BudgetAdjustedDollars06 = BudgetAdjustedHours06 * wageRate.BudgetAdjusted06,
	    base.BudgetAdjustedDollars07 = BudgetAdjustedHours07 * wageRate.BudgetAdjusted07,
	    base.BudgetAdjustedDollars08 = BudgetAdjustedHours08 * wageRate.BudgetAdjusted08,
	    base.BudgetAdjustedDollars09 = BudgetAdjustedHours09 * wageRate.BudgetAdjusted09,
	    base.BudgetAdjustedDollars10 = BudgetAdjustedHours10 * wageRate.BudgetAdjusted10,
	    base.BudgetAdjustedDollars11 = BudgetAdjustedHours11 * wageRate.BudgetAdjusted11,
	    base.BudgetAdjustedDollars12 = BudgetAdjustedHours12 * wageRate.BudgetAdjusted12
	OUTPUT 
	    inserted.StaffingID, 34, 
		deleted.BudgetAdjustedDollars01, deleted.BudgetAdjustedDollars02, deleted.BudgetAdjustedDollars03, deleted.BudgetAdjustedDollars04, deleted.BudgetAdjustedDollars05, deleted.BudgetAdjustedDollars06,
		deleted.BudgetAdjustedDollars07, deleted.BudgetAdjustedDollars08, deleted.BudgetAdjustedDollars09, deleted.BudgetAdjustedDollars10, deleted.BudgetAdjustedDollars11, deleted.BudgetAdjustedDollars12,
		inserted.BudgetAdjustedDollars01, inserted.BudgetAdjustedDollars02, inserted.BudgetAdjustedDollars03, inserted.BudgetAdjustedDollars04, inserted.BudgetAdjustedDollars05, inserted.BudgetAdjustedDollars06,
		inserted.BudgetAdjustedDollars07, inserted.BudgetAdjustedDollars08, inserted.BudgetAdjustedDollars09, inserted.BudgetAdjustedDollars10, inserted.BudgetAdjustedDollars11, inserted.BudgetAdjustedDollars12
	INTO
	    #spreadsChangeHistory (StaffingID, UnitTypeID,	
		  					   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
							   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
							   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
							   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
	FROM [fp].[Staffing] base
		INNER JOIN fp.StaffingWageRate wageRate on base.StaffingWageRateID = wageRate.StaffingWageRateID	  
		INNER JOIN #filterTable f ON f.StaffingID = base.StaffingID	 
	WHERE
	      base.VariabilityID = 1
	      AND (BudgetAdjustedHours01 <> 0
	       OR BudgetAdjustedHours02 <> 0
	       OR BudgetAdjustedHours03 <> 0
	       OR BudgetAdjustedHours04 <> 0
	       OR BudgetAdjustedHours05 <> 0
	       OR BudgetAdjustedHours06 <> 0
	       OR BudgetAdjustedHours07 <> 0
	       OR BudgetAdjustedHours08 <> 0
	       OR BudgetAdjustedHours09 <> 0
	       OR BudgetAdjustedHours10 <> 0
	       OR BudgetAdjustedHours11 <> 0
	       OR BudgetAdjustedHours12 <> 0)
	OPTION(RECOMPILE)

	-- Populate Change History
	IF EXISTS(SELECT 1 
			  FROM fp.BudgetConfigSetting setting
				INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
			  WHERE def.Name = 'Spreads Change History Logic Is Enabled'
			  	AND setting.Value = 1 AND setting.BudgetConfigID = @BudgetConfigID)
	BEGIN

		INSERT INTO fp.StaffingSpreadsChangeHistory (StaffingID, BudgetConfigID, SubsectionID, UnitTypeID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
						OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,	NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
						NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
		SELECT StaffingID, @BudgetConfigID, 3, UnitTypeID,
			ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0),
			ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0),
			ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0),
			ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0)
		FROM #spreadsChangeHistory
		WHERE 1 = 1
			AND (
				   OldValue01 != NewValue01
				OR OldValue02 != NewValue02
				OR OldValue03 != NewValue03
				OR OldValue04 != NewValue04
				OR OldValue05 != NewValue05
				OR OldValue06 != NewValue06
				OR OldValue07 != NewValue07
				OR OldValue08 != NewValue08
				OR OldValue09 != NewValue09
				OR OldValue10 != NewValue10
				OR OldValue11 != NewValue11
				OR OldValue12 != NewValue12
			)

	END

END
GO


---------------------------------------------

-- fp.procStaffingBudgetStampOff
CREATE   PROCEDURE [fp].[procStaffingBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	01-31-2023  MY      JAZZ-48962		Initial Creation
	** 2	01-03-2024  MZ      JAZZ-65385		Added Target TimeClass
	** 3 	12-04-2023  BW/MZ	JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 4	03-18-2024  MZ		JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 5	04-22-2024  NH		JAZZ-69921		Provider Submission during Stamp-off: During Stamp-off process populate Employee ID in int.factstaffing when data comes from Provider Comp
	** 6	10-18-2024  VZ		JAZZ-77158		Added join on jobcode to avoid duplication
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Budgeted Time Class
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) FROM [int].[FactStaffing] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
	
	IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
	CREATE TABLE #emp (PhysicianID INT, EmployeeID INT, EmployeeCode varchar(200), JobCodeID INT)
	INSERT INTO #emp (PhysicianID, EmployeeID, EmployeeCode, JobCodeID)
	SELECT 
		dp.PhysicianID,
		de.EmployeeID,
		de.Code EmployeeCode,
		de.JobCodeID
	FROM dss.DimPhysician dp
		INNER JOIN fw.dimemployee de ON dp.npi = de.npi
	WHERE de.NPI NOT IN ('Not Specified', '0', '')
		AND isFP = 1
	INSERT INTO [int].[FactStaffing] (DepartmentID, DepartmentCode, JobCodeID, JobCode, PayCodeID, PayCode, FiscalYearID, FiscalYearCode, TimeClassID, 
		TimeClassCode, UnitTypeID, UnitType, FiscalMonthID, FiscalMonthCode, Value, IsDeleted, HistoryItemGUID, EmployeeID,EmployeeCode)   
	SELECT 
			d.DepartmentID,
			d.DepartmentCode,
			jc.JobCodeID,
			jc.JobCode,
			pc.PayCodeID,
			pc.PayCode,
			bc.FiscalYearID,
			bc.FiscalYearID AS FiscalYearCode,
			@TargetTimeClassID AS TimeClassID,
			@TimeClassCode AS TimeClassCode,
			UT.UnitTypeID,
			UT.Name AS [UnitType],
			m.FiscalMonthID,
			m.FiscalMonthCode,
			Value AS Value,
			'0' AS IsDeleted,
			@HistoryItemGUID AS HistoryItemGUID,
			CASE                
				WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID -- Valid Ids if employee budgeting enabled    
				ELSE pcemp.EmployeeID          
			END AS EmployeeID,
			CASE                
				WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code --Valid Code, if employee budgeting enabled
				ELSE pcemp.EmployeeCode          
			END AS EmployeeCode
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
		CROSS APPLY (
		VALUES
			( 1, 34, BudgetAdjustedDollars01), 
			( 2, 34, BudgetAdjustedDollars02),
			( 3, 34, BudgetAdjustedDollars03),
			( 4, 34, BudgetAdjustedDollars04), 
			( 5, 34, BudgetAdjustedDollars05), 
			( 6, 34, BudgetAdjustedDollars06),
			( 7, 34, BudgetAdjustedDollars07), 
			( 8, 34, BudgetAdjustedDollars08), 
			( 9, 34, BudgetAdjustedDollars09), 
			( 10, 34, BudgetAdjustedDollars10),
			( 11, 34, BudgetAdjustedDollars11), 
			( 12, 34, BudgetAdjustedDollars12),
			( 1, 51, BudgetAdjustedHours01), 
			( 2, 51, BudgetAdjustedHours02),
			( 3, 51, BudgetAdjustedHours03),
			( 4, 51, BudgetAdjustedHours04), 
			( 5, 51, BudgetAdjustedHours05), 
			( 6, 51, BudgetAdjustedHours06),
			( 7, 51, BudgetAdjustedHours07), 
			( 8, 51, BudgetAdjustedHours08), 
			( 9, 51, BudgetAdjustedHours09), 
			( 10, 51, BudgetAdjustedHours10),
			( 11, 51, BudgetAdjustedHours11), 
			( 12, 51, BudgetAdjustedHours12),
			( 1, 144, BudgetAdjustedFTEs01), 
			( 2, 144, BudgetAdjustedFTEs02),
			( 3, 144, BudgetAdjustedFTEs03),
			( 4, 144, BudgetAdjustedFTEs04), 
			( 5, 144, BudgetAdjustedFTEs05), 
			( 6, 144, BudgetAdjustedFTEs06),
			( 7, 144, BudgetAdjustedFTEs07), 
			( 8, 144, BudgetAdjustedFTEs08), 
			( 9, 144, BudgetAdjustedFTEs09), 
			( 10, 144, BudgetAdjustedFTEs10),
			( 11, 144, BudgetAdjustedFTEs11), 
			( 12, 144, BudgetAdjustedFTEs12),
			( 1, 172, BudgetAdjustedRate01), 
			( 2, 172, BudgetAdjustedRate02),
			( 3, 172, BudgetAdjustedRate03),
			( 4, 172, BudgetAdjustedRate04), 
			( 5, 172, BudgetAdjustedRate05), 
			( 6, 172, BudgetAdjustedRate06),
			( 7, 172, BudgetAdjustedRate07), 
			( 8, 172, BudgetAdjustedRate08), 
			( 9, 172, BudgetAdjustedRate09), 
			( 10, 172, BudgetAdjustedRate10),
			( 11, 172, BudgetAdjustedRate11), 
			( 12, 172, BudgetAdjustedRate12)
	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID
			INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			LEFT JOIN  #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID
			WHERE staff.BudgetConfigID = @BudgetConfigID
			AND Value <> 0
	UNION ALL
	SELECT 
			d.DepartmentID,
			d.DepartmentCode,
			jc.JobCodeID,
			jc.JobCode,
			pc.PayCodeID,
			pc.PayCode,
			bc.FiscalYearID,
			bc.FiscalYearID AS FiscalYearCode,
			@TargetTimeClassID AS TimeClassID,
			@TimeClassCode AS TimeClassCode,
			UT.UnitTypeID,
			UT.Name AS [UnitType],
			m.FiscalMonthID,
			m.FiscalMonthCode,
			Value AS Value,
			'0' AS IsDeleted,
			@HistoryItemGUID AS HistoryItemGUID,
			CASE                
				WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID -- Valid Ids if employee budgeting enabled    
				ELSE pcemp.EmployeeID          
			END AS EmployeeID,
			CASE                
				WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code --Valid Code, if employee budgeting enabled
				ELSE pcemp.EmployeeCode          
			END AS EmployeeCode
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
		INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED)
		ON staff.StaffingWageRateID = wr.StaffingWageRateID
		AND staff.VariabilityID = 1
		CROSS APPLY (
		VALUES
			( 1, 159, BudgetAdjusted01), 
			( 2, 159, BudgetAdjusted02),
			( 3, 159, BudgetAdjusted03),
			( 4, 159, BudgetAdjusted04), 
			( 5, 159, BudgetAdjusted05), 
			( 6, 159, BudgetAdjusted06),
			( 7, 159, BudgetAdjusted07), 
			( 8, 159, BudgetAdjusted08), 
			( 9, 159, BudgetAdjusted09), 
			( 10, 159, BudgetAdjusted10),
			( 11, 159, BudgetAdjusted11), 
			( 12, 159, BudgetAdjusted12)
	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID
			INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			LEFT JOIN  #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID
			WHERE staff.BudgetConfigID = @BudgetConfigID
			AND Value <> 0
END
GO


---------------------------------------------

-- fp.procStaffingByStatisticsFlexConfigPopulation
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2017-06-12  IP      B-19913		APE Data Refresh - Flex Mappings, add parameter to process particular departments
** 2    2018-07-03  IP      TK-59678	fix case when @SourceDimensionality is empty
** 3    2018-09-11  apukii  TK-62350	fixed typo in code
** 4    2018-09-25  GF      E-02313		Simplify source dimensionality to only department
** 5	2019-03-08	IP		B-22295		Removed using table variables, small optimizations
** 6    2021-03-12  NT      JAZZ-14118  simplify code and remove null joins on targeting object
** 7 	2023-02-06  MY	    JAZZ-48980  Update flexing to support x-department flexing
** 8 	2023-05-01  MY	    JAZZ-54277  Flex Config Mapping is not taking handling Cross Department Flexing properly
** 9 	2023-11-07  MD	    JAZZ-62448  Update for staffing restructure
*************************************************************/
CREATE   PROCEDURE [fp].[procStaffingByStatisticsFlexConfigPopulation]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER	,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN
 	DECLARE @BudgetConfigID INT,
			@EntityGroupConfigID INT
	
	SET @BudgetConfigID = (SELECT bc.BudgetConfigID 
						   FROM [fp].[EntityGroupConfig] egc
						   	INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
						   WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	
	CREATE TABLE #flexMap (
                    DepartmentID INT NOT NULL,
                    PRJobCodeID INT NOT NULL,
	                StatAccountID INT NOT NULL,
					SourceDepartmentID INT NOT NULL
                );
  
	IF OBJECT_ID('tempdb..#FilterPR') IS NOT NULL DROP TABLE #FilterPR
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment

	CREATE TABLE #FilterPR (DepartmentID int, BudgetConfigID int, JobCodeID int)
		
  	CREATE TABLE #FilterByDepartment (DepartmentID int)
  	INSERT INTO #FilterByDepartment (DepartmentID)
  	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	
	-- If the filter is empty, passing in all to avoid OR NULL		
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[PrimaryStatisticsConfig]
		WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
			AND IsStaffing = 1
	END
  
	-- Build a list of Department / Job Code combinations
	-- Only department/job code combinations in staffing are populated in the fp.FlexConfigMapping table. New records will be added as new dimensionality is imported in.
	INSERT INTO #FilterPR
	SELECT DISTINCT pr.DepartmentID, pr.BudgetConfigID, pr.JobCodeID FROM  [fp].[Staffing] pr
	INNER JOIN #FilterByDepartment SD on SD.DepartmentID = pr.DepartmentID
	WHERE pr.VariabilityID = 2 -- Variable Only (used for filtering the data down)
		
	-- Populate all overrides for the revenue accounts. Overrides ignore traditional logic and override anything set at the department level.
	INSERT INTO #flexMap (DepartmentID, PRJobCodeID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT stat.DepartmentID, pr.JobCodeID AS PRJobCodeID, nso.AccountID AS StatAccountID, stat.DepartmentID
	FROM [fp].[FactStatistics] stat
		INNER JOIN #FilterPR pr ON pr.DepartmentID = stat.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[StaffingFlexingOverrideConfig] ns ON ns.DepartmentID = pr.DepartmentID AND ns.JobCodeID = pr.JobCodeID
		INNER JOIN [fp].[StaffingFlexingOverrideConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID and nso.AccountID = stat.AccountID
	WHERE 
		ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND stat.BudgetConfigID = @BudgetConfigID
		AND ns.FlexMethodID = 1 -- Statistic Accounts
 
	-- Process department level configuration changes that are not overriden. We also will exclude Department/job code combos
	-- that have multiple source departments here as that is handled in the statement below.
	-- Aka: Process the Department/job code combinations that have primary stats of "Same as Department" in the Primary Stat Config
	INSERT INTO #flexMap (DepartmentID, PRJobCodeID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT stat.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, stat.DepartmentID
	FROM [fp].[FactStatistics] stat
		INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID
		INNER JOIN #FilterPR pr ON pr.DepartmentID = stat.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = pr.DepartmentID
		LEFT JOIN (SELECT DepartmentID, JobCodeID FROM [fp].[StaffingFlexingOverrideConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr
			ON ovr.DepartmentID = stat.DepartmentID
			AND ovr.JobCodeID = pr.JobCodeID
		LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID
	WHERE 
			fsc.IsStaffing = 1
		AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND stat.BudgetConfigID = @BudgetConfigID
		AND ns.FlexMethodID = 1			-- Statistic Accounts
		AND ovr.DepartmentID IS NULL	-- We only want records that are not overridden
		AND pscsd.DepartmentID IS NULL; --	We want records where there is no source department specified. When no source department is specified, it's the same as the regular department

	-- Process departments with multiple source departments
	INSERT INTO #flexMap (DepartmentID, PRJobCodeID, StatAccountID, SourceDepartmentID)
	SELECT DISTINCT fsc.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, pscsd.DepartmentID
	FROM [fp].[PrimaryStatisticsConfig] fsc
		INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID
		INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID
		INNER JOIN #FilterPR pr ON pr.DepartmentID = fsc.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID
		LEFT JOIN (
			SELECT DepartmentID, JobCodeID 
			FROM [fp].[StaffingFlexingOverrideConfig] 
			WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
		) ovr
			ON ovr.DepartmentID = fsc.DepartmentID
			AND ovr.JobCodeID = pr.JobCodeID
	WHERE 
			fsc.IsStaffing = 1
		AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND stat.BudgetConfigID = @BudgetConfigID
		AND ns.FlexMethodID = 1			-- Statistic Accounts
		AND ovr.DepartmentID IS NULL;	-- We only want records that are not overridden
		
	IF @IsDebug = 1
	BEGIN
		SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment
		SELECT '#FilterPR', DepartmentID, BudgetConfigID, JobCodeID FROM #FilterPR
		SELECT '#flexMap', @EntityGroupConfigID AS EntityGroupConfigID, DepartmentID, PRJobCodeID, StatAccountID, 3 AS FlexingTypeID, SourceDepartmentID FROM #flexMap
	END ELSE
	BEGIN

		;WITH TRG AS 
		(
			SELECT EntityGroupConfigID, fcm.DepartmentID, fcm.PRJobCodeID, fcm.StatAccountID, fcm.FlexingTypeID, SourceDepartmentID 
			FROM [fp].[FlexConfigMapping] fcm
			INNER JOIN #FilterByDepartment SD 
				ON SD.DepartmentID = fcm.DepartmentID
			WHERE EntityGroupConfigID = @EntityGroupConfigID 
				AND FlexingTypeID = 3 -- Staffing Flexing Type
		)

 		MERGE TRG
		USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID,
			DepartmentID,
			PRJobCodeID,
			StatAccountID,
			3 AS FlexingTypeID, -- Staffing Flexing Type
			SourceDepartmentID
		FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID 
			AND TRG.PRJobCodeID = SRC.PRJobCodeID 
			AND TRG.StatAccountID = SRC.StatAccountID
			AND TRG.SourceDepartmentID = SRC.SourceDepartmentID
		WHEN NOT MATCHED BY TARGET THEN
		INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.PRJobCodeID, src.StatAccountID, src.FlexingTypeID, src.SourceDepartmentID) 
		WHEN NOT MATCHED BY SOURCE THEN DELETE;	

	END
	
 END
GO


---------------------------------------------

-- fp.procStaffingCopyNewItems
CREATE PROCEDURE [fp].[procStaffingCopyNewItems]
    @SourceBudgetConfigID INT,
    @SourceEntityGroupConfigID INT,
    @BudgetConfigID INT,
    @EntityGroupConfigID INT
AS
BEGIN

/*************************************************************
** Description
**************************************************************
** Copy the dimensionality of IsNew Staffing rows to the new
** plan. IsNew rows are not sourced from INT tables and need
** to be copied from the Copy From related budget to the
** Copy To related budget.
*************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI   		Description
** 1 	 2021-06-28  NT		 JAZZ-21664 Add missing provider dimensions
** 2 	 2023-11-17  Matt Hayden    JAZZ-63563 Staffing restructure change
*************************************************************/
INSERT INTO [fp].[Staffing]
( 
  [BudgetConfigID]
, [EntityGroupConfigID]
, [EntityID]
, [DepartmentID]
, [JobCodeID]
, [PayCodeGroupID]
, [ProductiveClassID]
, [ProviderID]
, [ProviderLineItemID]
, [ProviderTypeID]
, [ProviderSpecialtyID]
, [EmployeeID]
, [VariabilityID]
, [AddDate]
, [IsNew]
, [SubsectionID]
, [FixedVariabilityPercentage]
, [FlexingTypeID]
)
SELECT
  @BudgetConfigID
, @EntityGroupConfigID
, [EntityID]
, [DepartmentID]
, [JobCodeID]
, [PayCodeGroupID]
, [ProductiveClassID]
, [ProviderID]
, [ProviderLineItemID]
, [ProviderTypeID]
, [ProviderSpecialtyID]
, [EmployeeID]
, [VariabilityID]
, [AddDate]
, [IsNew]
, [SubsectionID]
, [FixedVariabilityPercentage]
, [FlexingTypeID]
FROM [fp].[Staffing]
WHERE   BudgetConfigID = @SourceBudgetConfigID
    AND EntityGroupConfigID = @SourceEntityGroupConfigID
    AND IsNew = 1

END
GO


---------------------------------------------

-- fp.procStaffingProjectionStampOff
CREATE     PROCEDURE [fp].[procStaffingProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	11-10-2023 AO      JAZZ-62128		Initial Creation
	** 2	01-04-2024 MZ      JAZZ-65385		Added Target TimeClass and IsMonthsLoadedIncluded
	** 3	01-24-2024 MZ      JAZZ-64527		Fix Months Loaded
	** 4 	12-04-2023 BW/MZ   JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 5	03-18-2024 MZ      JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 6	04-03-2024 MZ      JAZZ-70053		Fix Month Loaded excluding logic
	** 7	04-22-2024 NH      JAZZ-69921		Provider Submission during Stamp-off: During Stamp-off process populate Employee ID in int.factstaffing when data comes from Provider Comp
	** 8	10-18-2024 VZ	   JAZZ-77158		Added join on jobcode to avoid duplication
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Projected Time Class
	-- and all months if months loaded included otherwise only months NOT loaded will be cleared
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) s FROM [int].[FactStaffing] s
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = s.FiscalMonthID
		WHERE s.FiscalYearID = @FiscalYear
			AND s.TimeClassID = @TargetTimeClassID
			AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded)
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
	
	IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp
	CREATE TABLE #emp (PhysicianID INT, EmployeeID INT, EmployeeCode varchar(200), JobCodeID INT)

	INSERT INTO #emp (PhysicianID, EmployeeID, EmployeeCode, JobCodeID)
	SELECT 
		dp.PhysicianID,
		de.EmployeeID,
		de.Code EmployeeCode,
		de.JobCodeID
	FROM dss.DimPhysician dp
		INNER JOIN fw.dimemployee de ON dp.npi = de.npi
	WHERE de.NPI NOT IN ('Not Specified', '0', '')
		AND isFP = 1

	INSERT INTO [int].[FactStaffing] (DepartmentID, DepartmentCode, JobCodeID, JobCode, PayCodeID, PayCode, FiscalYearID, FiscalYearCode, TimeClassID, 
		TimeClassCode, UnitTypeID, UnitType, FiscalMonthID, FiscalMonthCode, Value, IsDeleted, HistoryItemGUID, EmployeeID, EmployeeCode)   
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		jc.JobCodeID,
		jc.JobCode,
		pc.PayCodeID,
		pc.PayCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		UT.UnitTypeID,
		UT.Name AS [UnitType],
		m.FiscalMonthID,
		m.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID,
		CASE                
			WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID -- Valid Ids if employee budgeting enabled    
			ELSE pcemp.EmployeeID          
		END AS EmployeeID,
		CASE                
			WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code --Valid Code, if employee budgeting enabled
			ELSE pcemp.EmployeeCode          
		END AS EmployeeCode
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
		CROSS APPLY (
		VALUES
			( 1, 34, ProjectionAdjustedDollars01), 
			( 2, 34, ProjectionAdjustedDollars02),
			( 3, 34, ProjectionAdjustedDollars03),
			( 4, 34, ProjectionAdjustedDollars04), 
			( 5, 34, ProjectionAdjustedDollars05), 
			( 6, 34, ProjectionAdjustedDollars06),
			( 7, 34, ProjectionAdjustedDollars07), 
			( 8, 34, ProjectionAdjustedDollars08), 
			( 9, 34, ProjectionAdjustedDollars09), 
			( 10, 34, ProjectionAdjustedDollars10),
			( 11, 34, ProjectionAdjustedDollars11), 
			( 12, 34, ProjectionAdjustedDollars12),

			( 1, 51, ProjectionAdjustedHours01), 
			( 2, 51, ProjectionAdjustedHours02),
			( 3, 51, ProjectionAdjustedHours03),
			( 4, 51, ProjectionAdjustedHours04), 
			( 5, 51, ProjectionAdjustedHours05), 
			( 6, 51, ProjectionAdjustedHours06),
			( 7, 51, ProjectionAdjustedHours07), 
			( 8, 51, ProjectionAdjustedHours08), 
			( 9, 51, ProjectionAdjustedHours09), 
			( 10, 51, ProjectionAdjustedHours10),
			( 11, 51, ProjectionAdjustedHours11), 
			( 12, 51, ProjectionAdjustedHours12),

			( 1, 144, ProjectionAdjustedFTEs01), 
			( 2, 144, ProjectionAdjustedFTEs02),
			( 3, 144, ProjectionAdjustedFTEs03),
			( 4, 144, ProjectionAdjustedFTEs04), 
			( 5, 144, ProjectionAdjustedFTEs05), 
			( 6, 144, ProjectionAdjustedFTEs06),
			( 7, 144, ProjectionAdjustedFTEs07), 
			( 8, 144, ProjectionAdjustedFTEs08), 
			( 9, 144, ProjectionAdjustedFTEs09), 
			( 10, 144, ProjectionAdjustedFTEs10),
			( 11, 144, ProjectionAdjustedFTEs11), 
			( 12, 144, ProjectionAdjustedFTEs12),

			( 1, 172, ProjectionAdjustedRate01), 
			( 2, 172, ProjectionAdjustedRate02),
			( 3, 172, ProjectionAdjustedRate03),
			( 4, 172, ProjectionAdjustedRate04), 
			( 5, 172, ProjectionAdjustedRate05), 
			( 6, 172, ProjectionAdjustedRate06),
			( 7, 172, ProjectionAdjustedRate07), 
			( 8, 172, ProjectionAdjustedRate08), 
			( 9, 172, ProjectionAdjustedRate09), 
			( 10, 172, ProjectionAdjustedRate10),
			( 11, 172, ProjectionAdjustedRate11), 
			( 12, 172, ProjectionAdjustedRate12)

	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID
			INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			LEFT JOIN  #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID
			WHERE staff.BudgetConfigID = @BudgetConfigID
			AND Value <> 0
			AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded)

	UNION ALL

	SELECT 
		d.DepartmentID,
		d.DepartmentCode,
		jc.JobCodeID,
		jc.JobCode,
		pc.PayCodeID,
		pc.PayCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		UT.UnitTypeID,
		UT.Name AS [UnitType],
		m.FiscalMonthID,
		m.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID,
		CASE                
			WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID      -- Valid Ids if employee budgeting enabled
			ELSE pcemp.EmployeeID          
		END AS EmployeeID,
		CASE                
			WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code  --Valid Code, if employee budgeting enabled    
			ELSE pcemp.EmployeeCode          
		END AS EmployeeCode
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
		INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED)
		ON staff.StaffingWageRateID = wr.StaffingWageRateID
		AND staff.VariabilityID = 1
		CROSS APPLY (
		VALUES
			( 1, 159, ProjectionAdjusted01), 
			( 2, 159, ProjectionAdjusted02),
			( 3, 159, ProjectionAdjusted03),
			( 4, 159, ProjectionAdjusted04), 
			( 5, 159, ProjectionAdjusted05), 
			( 6, 159, ProjectionAdjusted06),
			( 7, 159, ProjectionAdjusted07), 
			( 8, 159, ProjectionAdjusted08), 
			( 9, 159, ProjectionAdjusted09), 
			( 10, 159, ProjectionAdjusted10),
			( 11, 159, ProjectionAdjusted11), 
			( 12, 159, ProjectionAdjusted12)

	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID
			INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			LEFT JOIN  #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID
			WHERE staff.BudgetConfigID = @BudgetConfigID
			AND Value <> 0	
			AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded)
END
GO


---------------------------------------------

-- fp.procStaffingProviderByStatisticsFlexConfigPopulation
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI			Description
** 1    2020-01-13  MY      JAZZ-12607	Initial
** 2    2022-02-07  MY      JAZZ-48980	Update flexing to support x-department flexing
** 3 	2023-05-01  MY	    JAZZ-54277  Flex Config Mapping is not taking handling Cross Department Flexing properly
** 4 	2023-11-08  MD	    JAZZ-62448  Update for staffing restructure
*************************************************************/
CREATE   PROCEDURE [fp].[procStaffingProviderByStatisticsFlexConfigPopulation]
	@EntityGroupConfigGUID UNIQUEIDENTIFIER	,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN

 	DECLARE @BudgetConfigID INT,
			@EntityGroupConfigID INT,
			@StatisticAccounts INT;
	 
	IF OBJECT_ID('tempdb..#flexMap') IS NOT NULL DROP TABLE #flexMap
	IF OBJECT_ID('tempdb..#FilterPR') IS NOT NULL DROP TABLE #FilterPR
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment

	SET @BudgetConfigID = (SELECT bc.BudgetConfigID 
						   FROM [fp].[EntityGroupConfig] egc
						   	INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
						   WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
	
	CREATE TABLE #flexMap (
                    DepartmentID INT NOT NULL,
                    PRJobCodeID INT NOT NULL,
	                StatAccountID INT NOT NULL,
					ProviderLineItemID INT NOT NULL,
					SourceDepartmentID INT NOT NULL
                );
 
	CREATE TABLE #FilterPR (DepartmentID INT, BudgetConfigID INT, JobCodeID INT, ProviderLineItemID INT)
		
  	CREATE TABLE #FilterByDepartment (DepartmentID INT)
  	INSERT INTO #FilterByDepartment (DepartmentID)
  	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
  
	-- If the filter is empty, passing in all to avoid OR NULL	
	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN
		INSERT INTO #FilterByDepartment (DepartmentID)
		SELECT DISTINCT DepartmentID 
		FROM [fp].[PrimaryStatisticsConfig]
		WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID
			AND IsStaffing = 1
	END

	-- Build a list of Department / Job Code combinations
	-- Only department/job code combinations in staffing are populated in the fp.FlexConfigMapping table. New records will be added as new dimensionality is imported in.
	INSERT INTO #FilterPR
	SELECT pr.DepartmentID, pr.BudgetConfigID, pr.JobCodeID, pr.ProviderLineItemID
	FROM [fp].[Staffing] pr
		INNER JOIN #FilterByDepartment SD on SD.DepartmentID = pr.DepartmentID
		INNER JOIN fp.ProviderStaffingConfig psc ON pr.BudgetConfigID = psc.BudgetConfigID 
			AND pr.ProviderLineItemID = psc.ProviderLineItemID
	WHERE pr.VariabilityID = 2	  -- Variable Only (used for filtering the data down)
		AND pr.SubsectionID = 4   -- Provider
		AND psc.VariabilityID = 2 -- We only want Variable Line Items
		AND pr.EntityGroupConfigID = @EntityGroupConfigID

	-- NOTE: Provider Flexing Ignores overrides and only cares if the department itself is fixed. 
		
	-- We want to get all of the records assuming that:
	--		The Primary Statistic is setup to flex this account
	--		The Provider Line Item is Variable
	--		The Department is not fixed
	--		The Statistics data exists

	-- Process department level configuration changes that are not overriden. We also will exclude Department/job code combos
	-- that have multiple source departments here as that is handled in the statement below.
	-- Aka: Process the Department/job code combinations that have primary stats of "Same as Department" in the Primary Stat Config
	INSERT INTO #flexMap(DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID)
	SELECT DISTINCT stat.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, pr.ProviderLineItemID, stat.DepartmentID
	FROM [fp].[FactStatistics] stat
		INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID
		INNER JOIN #FilterPR pr ON pr.DepartmentID = stat.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = pr.DepartmentID
		LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID
	WHERE 
			fsc.IsStaffing = 1
		AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND stat.BudgetConfigID = @BudgetConfigID
		AND ns.FlexMethodID != 0 -- 0 = Fixed
		AND pscsd.DepartmentID IS NULL; --	We want records where there is no source department specified. When no source department is specified, it's the same as the regular department
		
	-- Process departments with multiple source departments
	INSERT INTO #flexMap(DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID)
	SELECT DISTINCT fsc.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, pr.ProviderLineItemID, pscsd.DepartmentID
	FROM [fp].[PrimaryStatisticsConfig] fsc
		INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID
		INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID
		INNER JOIN #FilterPR pr ON pr.DepartmentID = fsc.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID
		INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID
	WHERE 
			fsc.IsStaffing = 1
		AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND stat.BudgetConfigID = @BudgetConfigID
		AND ns.FlexMethodID != 0 -- 0 = Fixed
		
	IF @IsDebug = 1
	BEGIN
		SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment
		SELECT '#FilterPR', DepartmentID, BudgetConfigID, JobCodeID, ProviderLineItemID FROM #FilterPR
		SELECT '#flexMap', DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID FROM #flexMap
	END ELSE BEGIN

		;WITH TRG AS 
		(
			SELECT EntityGroupConfigID, fcm.DepartmentID, fcm.PRJobCodeID, fcm.StatAccountID, fcm.ProviderLineItemID, fcm.FlexingTypeID, fcm.SourceDepartmentID
			FROM [fp].[FlexConfigMapping] fcm
				INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fcm.DepartmentID
			WHERE EntityGroupConfigID = @EntityGroupConfigID 
				AND FlexingTypeID = 9 -- Provider Flexing
		) 
		MERGE TRG
		USING (
			SELECT @EntityGroupConfigID AS EntityGroupConfigID,
				DepartmentID,
				PRJobCodeID,
				StatAccountID,
				ProviderLineItemID,
				9 AS FlexingTypeID, -- Provider Flexing
				SourceDepartmentID
			FROM #flexMap
		) AS Src ON 
				TRG.DepartmentID = SRC.DepartmentID 
			AND TRG.PRJobCodeID = SRC.PRJobCodeID 
			AND TRG.StatAccountID = SRC.StatAccountID 
			AND TRG.ProviderLineItemID = SRC.ProviderLineItemID
			AND TRG.SourceDepartmentID = SRC.SourceDepartmentID
		WHEN NOT MATCHED BY TARGET THEN
		INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.PRJobCodeID, src.StatAccountID, src.ProviderLineItemID, src.FlexingTypeID, src.SourceDepartmentID) 
		WHEN NOT MATCHED BY SOURCE THEN DELETE;	

	END

 END
GO


---------------------------------------------

-- fp.procStaffingToGlCrosswalk
/**************************************************************
** Change History
**************************************************************
** CID  Date        Author  WI   Description
** 1 2017-07-30 IP   B-20351  Staffing to GL - Performance Improvements and roster targeted thing
** 2 2018-08-14 GF   TK-62078    Limit targeted refresh to only filter by department to prevent zeroing other data
** 3    2018-09-25  GF      E-02313  Simplify source dimensionality to only department
** 4    2018-12-14  BK      B-19174  Add BudgetPhase to source dimensionality
** 5    2021-05-05  BK      JAZZ-18217 Add Provider Compensation to crosswalk and clean up SQL
** 6    2023-07-31  BK      JAZZ-58155 Update for GL data restructure
** 7    2023-10-31  Matt Hayden  JAZZ-62450 Update for Staffing table restructure
** 8    2024-01-31  NH      JAZZ-64064 Move Provider Planning FF as a setting in Plan Config
*************************************************************/
CREATE   PROCEDURE [fp].[procStaffingToGlCrosswalk]
	@EntityGroupConfigID INT,
	@BudgetConfigID INT,
	@SqlJoin NVARCHAR(MAX),
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
	@IsDebug BIT = 0
AS
BEGIN

IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing
IF OBJECT_ID('tempdb..#tmpProvider') IS NOT NULL DROP TABLE #tmpProvider
IF OBJECT_ID('tempdb..#tmpAcct') IS NOT NULL DROP TABLE #tmpAcct
IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment

CREATE TABLE #tmpAcct (AccountID INT)

CREATE TABLE #FilterByDepartment (DepartmentID INT)
INSERT INTO #FilterByDepartment (DepartmentID)
    SELECT DISTINCT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN
    INSERT INTO #FilterByDepartment (DepartmentID)
    SELECT DISTINCT DepartmentID
    FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED)  -- using GL here because ultimately we are updating GL and anything from Staffing should have been padded to GL
    WHERE d.EntityGroupConfigID = @EntityGroupConfigID
END

DECLARE @IsProviderPlanningEnabled BIT;
SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

CREATE TABLE #tmpStaffing (
    DepartmentID INT,
    AccountID INT,
    VariabilityID INT,
    EntityGroupConfigID INT,
    TargetAdjustedDollars01 DECIMAL(19,8), TargetAdjustedDollars02 DECIMAL(19,8), TargetAdjustedDollars03 DECIMAL(19,8), TargetAdjustedDollars04 DECIMAL(19,8), TargetAdjustedDollars05 DECIMAL(19,8), TargetAdjustedDollars06 DECIMAL(19,8),
    TargetAdjustedDollars07 DECIMAL(19,8), TargetAdjustedDollars08 DECIMAL(19,8), TargetAdjustedDollars09 DECIMAL(19,8), TargetAdjustedDollars10 DECIMAL(19,8), TargetAdjustedDollars11 DECIMAL(19,8), TargetAdjustedDollars12 DECIMAL(19,8),

    BudgetAdjustedDollars01 DECIMAL(19,8), BudgetAdjustedDollars02 DECIMAL(19,8), BudgetAdjustedDollars03 DECIMAL(19,8), BudgetAdjustedDollars04 DECIMAL(19,8), BudgetAdjustedDollars05 DECIMAL(19,8), BudgetAdjustedDollars06 DECIMAL(19,8),
    BudgetAdjustedDollars07 DECIMAL(19,8), BudgetAdjustedDollars08 DECIMAL(19,8), BudgetAdjustedDollars09 DECIMAL(19,8), BudgetAdjustedDollars10 DECIMAL(19,8), BudgetAdjustedDollars11 DECIMAL(19,8), BudgetAdjustedDollars12 DECIMAL(19,8),

    ProjectionAdjustedDollars01 DECIMAL(19,8), ProjectionAdjustedDollars02 DECIMAL(19,8), ProjectionAdjustedDollars03 DECIMAL(19,8), ProjectionAdjustedDollars04 DECIMAL(19,8), ProjectionAdjustedDollars05 DECIMAL(19,8), ProjectionAdjustedDollars06 DECIMAL(19,8),
    ProjectionAdjustedDollars07 DECIMAL(19,8), ProjectionAdjustedDollars08 DECIMAL(19,8), ProjectionAdjustedDollars09 DECIMAL(19,8), ProjectionAdjustedDollars10 DECIMAL(19,8), ProjectionAdjustedDollars11 DECIMAL(19,8), ProjectionAdjustedDollars12 DECIMAL(19,8)
    )

INSERT INTO #tmpAcct (AccountID)
SELECT DISTINCT AccountID FROM [clientob].[FactPayrollToAccountCrosswalk] (readuncommitted)
WHERE UnitTypeID = 34

DECLARE @SqlStaffing NVARCHAR(MAX)
SET @SqlStaffing = '
    INSERT INTO #tmpStaffing (
        DepartmentID, AccountID, VariabilityID, EntityGroupConfigID, 
        
        TargetAdjustedDollars01, TargetAdjustedDollars02, TargetAdjustedDollars03, TargetAdjustedDollars04, TargetAdjustedDollars05, TargetAdjustedDollars06, 
        TargetAdjustedDollars07, TargetAdjustedDollars08, TargetAdjustedDollars09, TargetAdjustedDollars10, TargetAdjustedDollars11, TargetAdjustedDollars12, 
        
        BudgetAdjustedDollars01, BudgetAdjustedDollars02, BudgetAdjustedDollars03, BudgetAdjustedDollars04, BudgetAdjustedDollars05, BudgetAdjustedDollars06, 
        BudgetAdjustedDollars07, BudgetAdjustedDollars08, BudgetAdjustedDollars09, BudgetAdjustedDollars10, BudgetAdjustedDollars11, BudgetAdjustedDollars12, 

        ProjectionAdjustedDollars01, ProjectionAdjustedDollars02, ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05, ProjectionAdjustedDollars06, 
        ProjectionAdjustedDollars07, ProjectionAdjustedDollars08, ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11, ProjectionAdjustedDollars12
        )
    SELECT
        staff.DepartmentID, pax.AccountID, staff.VariabilityID, staff.EntityGroupConfigID,

        staff.TargetAdjustedDollars01, staff.TargetAdjustedDollars02, staff.TargetAdjustedDollars03, staff.TargetAdjustedDollars04, staff.TargetAdjustedDollars05, staff.TargetAdjustedDollars06,
        staff.TargetAdjustedDollars07, staff.TargetAdjustedDollars08, staff.TargetAdjustedDollars09, staff.TargetAdjustedDollars10, staff.TargetAdjustedDollars11, staff.TargetAdjustedDollars12,
        
        staff.BudgetAdjustedDollars01, staff.BudgetAdjustedDollars02, staff.BudgetAdjustedDollars03, staff.BudgetAdjustedDollars04, staff.BudgetAdjustedDollars05, staff.BudgetAdjustedDollars06,
        staff.BudgetAdjustedDollars07, staff.BudgetAdjustedDollars08, staff.BudgetAdjustedDollars09, staff.BudgetAdjustedDollars10, staff.BudgetAdjustedDollars11, staff.BudgetAdjustedDollars12,

        staff.ProjectionAdjustedDollars01, staff.ProjectionAdjustedDollars02, staff.ProjectionAdjustedDollars03, staff.ProjectionAdjustedDollars04, staff.ProjectionAdjustedDollars05, staff.ProjectionAdjustedDollars06,
        staff.ProjectionAdjustedDollars07, staff.ProjectionAdjustedDollars08, staff.ProjectionAdjustedDollars09, staff.ProjectionAdjustedDollars10, staff.ProjectionAdjustedDollars11, staff.ProjectionAdjustedDollars12
    FROM [fp].[Staffing] staff (readuncommitted)
        INNER JOIN #FilterByDepartment dept ON staff.DepartmentID = dept.DepartmentID
        ' + @SqlJoin + '
    WHERE staff.SubsectionID = 3
        AND pax.UnitTypeID = 34
        AND staff.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS NVARCHAR(10))

EXEC (@SqlStaffing);  -- populate #tmpStaffing

IF @IsProviderPlanningEnabled = 1 BEGIN
    CREATE TABLE #tmpProvider (
        ProviderLineItemID TINYINT,
        AccountID INT,
        ProviderTypeID INT,
        VariabilityID INT
        )
    INSERT INTO #tmpProvider (ProviderLineItemID, AccountID, ProviderTypeID, VariabilityID)
        SELECT  ProviderLineItemID, COALESCE(detail.AccountID, psc.AccountID) AS AccountID, ISNULL(ProviderTypeID, 0), VariabilityID
        FROM    fp.ProviderStaffingConfig psc 
            LEFT JOIN fp.ProviderStaffingConfigProviderType detail on psc.ProviderStaffingConfigID = detail.ProviderStaffingConfigID
        WHERE   BudgetConfigID = @BudgetConfigID
 
    INSERT INTO #tmpAcct (AccountID)
        SELECT DISTINCT a.AccountID FROM #tmpProvider a
        LEFT JOIN #tmpAcct t on a.AccountID = t.AccountID
        WHERE t.AccountID IS NULL

    INSERT INTO #tmpStaffing (
        DepartmentID, AccountID, VariabilityID, EntityGroupConfigID,

        TargetAdjustedDollars01, TargetAdjustedDollars02, TargetAdjustedDollars03, TargetAdjustedDollars04, TargetAdjustedDollars05, TargetAdjustedDollars06,
        TargetAdjustedDollars07, TargetAdjustedDollars08, TargetAdjustedDollars09, TargetAdjustedDollars10, TargetAdjustedDollars11, TargetAdjustedDollars12,

        BudgetAdjustedDollars01, BudgetAdjustedDollars02, BudgetAdjustedDollars03, BudgetAdjustedDollars04, BudgetAdjustedDollars05, BudgetAdjustedDollars06,
        BudgetAdjustedDollars07, BudgetAdjustedDollars08, BudgetAdjustedDollars09, BudgetAdjustedDollars10, BudgetAdjustedDollars11, BudgetAdjustedDollars12,

        ProjectionAdjustedDollars01, ProjectionAdjustedDollars02, ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05, ProjectionAdjustedDollars06,
        ProjectionAdjustedDollars07, ProjectionAdjustedDollars08, ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11, ProjectionAdjustedDollars12
        )
    SELECT
        staff.DepartmentID, prov.AccountID,  staff.VariabilityID,  staff.EntityGroupConfigID,

        staff.TargetAdjustedDollars01, staff.TargetAdjustedDollars02, staff.TargetAdjustedDollars03, staff.TargetAdjustedDollars04, staff.TargetAdjustedDollars05, staff.TargetAdjustedDollars06,
        staff.TargetAdjustedDollars07, staff.TargetAdjustedDollars08, staff.TargetAdjustedDollars09, staff.TargetAdjustedDollars10, staff.TargetAdjustedDollars11, staff.TargetAdjustedDollars12,
        
        staff.BudgetAdjustedDollars01, staff.BudgetAdjustedDollars02, staff.BudgetAdjustedDollars03, staff.BudgetAdjustedDollars04, staff.BudgetAdjustedDollars05, staff.BudgetAdjustedDollars06,
        staff.BudgetAdjustedDollars07, staff.BudgetAdjustedDollars08, staff.BudgetAdjustedDollars09, staff.BudgetAdjustedDollars10, staff.BudgetAdjustedDollars11, staff.BudgetAdjustedDollars12,

        staff.ProjectionAdjustedDollars01, staff.ProjectionAdjustedDollars02, staff.ProjectionAdjustedDollars03, staff.ProjectionAdjustedDollars04, staff.ProjectionAdjustedDollars05, staff.ProjectionAdjustedDollars06,
        staff.ProjectionAdjustedDollars07, staff.ProjectionAdjustedDollars08, staff.ProjectionAdjustedDollars09, staff.ProjectionAdjustedDollars10, staff.ProjectionAdjustedDollars11, staff.ProjectionAdjustedDollars12
    FROM [fp].[Staffing] staff (readuncommitted)
        INNER JOIN #tmpProvider prov on  staff.ProviderLineItemID = prov.ProviderLineItemID AND staff.VariabilityID = prov.VariabilityID
        INNER JOIN #FilterByDepartment dept ON  staff.DepartmentID = dept.DepartmentID
        INNER JOIN #tmpAcct acc on prov.AccountID = acc.AccountID
    WHERE staff.SubsectionID = 4
        AND staff.EntityGroupConfigID = @EntityGroupConfigID
        AND (prov.ProviderTypeID = 0 OR prov.ProviderTypeID = staff.ProviderTypeID)
END

IF (@IsDebug = 1) BEGIN

	WITH StaffingSubquery AS (
    SELECT
        s.DepartmentID,
        s.AccountID,
        s.VariabilityID,
        s.EntityGroupConfigID,
        SUM(s.TargetAdjustedDollars01) AS TargetAdjustedDollars01,
        SUM(s.TargetAdjustedDollars02) AS TargetAdjustedDollars02,
        SUM(s.TargetAdjustedDollars03) AS TargetAdjustedDollars03,
        SUM(s.TargetAdjustedDollars04) AS TargetAdjustedDollars04,
        SUM(s.TargetAdjustedDollars05) AS TargetAdjustedDollars05,
        SUM(s.TargetAdjustedDollars06) AS TargetAdjustedDollars06,
        SUM(s.TargetAdjustedDollars07) AS TargetAdjustedDollars07,
        SUM(s.TargetAdjustedDollars08) AS TargetAdjustedDollars08,
        SUM(s.TargetAdjustedDollars09) AS TargetAdjustedDollars09,
        SUM(s.TargetAdjustedDollars10) AS TargetAdjustedDollars10,
        SUM(s.TargetAdjustedDollars11) AS TargetAdjustedDollars11,
        SUM(s.TargetAdjustedDollars12) AS TargetAdjustedDollars12,
        SUM(s.BudgetAdjustedDollars01) AS BudgetAdjustedDollars01,
        SUM(s.BudgetAdjustedDollars02) AS BudgetAdjustedDollars02,
        SUM(s.BudgetAdjustedDollars03) AS BudgetAdjustedDollars03,
        SUM(s.BudgetAdjustedDollars04) AS BudgetAdjustedDollars04,
        SUM(s.BudgetAdjustedDollars05) AS BudgetAdjustedDollars05,
        SUM(s.BudgetAdjustedDollars06) AS BudgetAdjustedDollars06,
        SUM(s.BudgetAdjustedDollars07) AS BudgetAdjustedDollars07,
        SUM(s.BudgetAdjustedDollars08) AS BudgetAdjustedDollars08,
        SUM(s.BudgetAdjustedDollars09) AS BudgetAdjustedDollars09,
        SUM(s.BudgetAdjustedDollars10) AS BudgetAdjustedDollars10,
        SUM(s.BudgetAdjustedDollars11) AS BudgetAdjustedDollars11,
        SUM(s.BudgetAdjustedDollars12) AS BudgetAdjustedDollars12,
        SUM(s.ProjectionAdjustedDollars01) AS ProjectionAdjustedDollars01,
        SUM(s.ProjectionAdjustedDollars02) AS ProjectionAdjustedDollars02,
        SUM(s.ProjectionAdjustedDollars03) AS ProjectionAdjustedDollars03,
        SUM(s.ProjectionAdjustedDollars04) AS ProjectionAdjustedDollars04,
        SUM(s.ProjectionAdjustedDollars05) AS ProjectionAdjustedDollars05,
        SUM(s.ProjectionAdjustedDollars06) AS ProjectionAdjustedDollars06,
        SUM(s.ProjectionAdjustedDollars07) AS ProjectionAdjustedDollars07,
        SUM(s.ProjectionAdjustedDollars08) AS ProjectionAdjustedDollars08,
        SUM(s.ProjectionAdjustedDollars09) AS ProjectionAdjustedDollars09,
        SUM(s.ProjectionAdjustedDollars10) AS ProjectionAdjustedDollars10,
        SUM(s.ProjectionAdjustedDollars11) AS ProjectionAdjustedDollars11,
        SUM(s.ProjectionAdjustedDollars12) AS ProjectionAdjustedDollars12
    FROM #tmpStaffing s
    GROUP BY
        s.DepartmentID,
        s.AccountID,
        s.VariabilityID,
        s.EntityGroupConfigID
	)
    SELECT 
        gl.AccountID, gl.DepartmentID, gl.VariabilityID, gl.EntityGroupConfigID,

        staff.TargetAdjustedDollars01, staff.TargetAdjustedDollars02, staff.TargetAdjustedDollars03, staff.TargetAdjustedDollars04, staff.TargetAdjustedDollars05, staff.TargetAdjustedDollars06,
        staff.TargetAdjustedDollars07, staff.TargetAdjustedDollars08, staff.TargetAdjustedDollars09, staff.TargetAdjustedDollars10, staff.TargetAdjustedDollars11, staff.TargetAdjustedDollars12,
        
        staff.BudgetAdjustedDollars01, staff.BudgetAdjustedDollars02, staff.BudgetAdjustedDollars03, staff.BudgetAdjustedDollars04, staff.BudgetAdjustedDollars05, staff.BudgetAdjustedDollars06,
        staff.BudgetAdjustedDollars07, staff.BudgetAdjustedDollars08, staff.BudgetAdjustedDollars09, staff.BudgetAdjustedDollars10, staff.BudgetAdjustedDollars11, staff.BudgetAdjustedDollars12,

        staff.ProjectionAdjustedDollars01, staff.ProjectionAdjustedDollars02, staff.ProjectionAdjustedDollars03, staff.ProjectionAdjustedDollars04, staff.ProjectionAdjustedDollars05, staff.ProjectionAdjustedDollars06,
        staff.ProjectionAdjustedDollars07, staff.ProjectionAdjustedDollars08, staff.ProjectionAdjustedDollars09, staff.ProjectionAdjustedDollars10, staff.ProjectionAdjustedDollars11, staff.ProjectionAdjustedDollars12,

        1 AS LockFlag, 3 as LockType
    FROM [fp].[GeneralLedger] gl
        INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID --AND fglb.BudgetPhaseID = dept.BudgetPhaseID
        INNER JOIN #tmpAcct fptac ON gl.AccountID = fptac.AccountID
        LEFT JOIN  StaffingSubquery staff ON staff.DepartmentID = gl.DepartmentID
            AND staff.AccountID = gl.AccountID
            AND staff.EntityGroupConfigID = gl.EntityGroupConfigID
            AND staff.VariabilityID = gl.VariabilityID
    WHERE gl.EntityGroupConfigID = @EntityGroupConfigID
        AND ( 
            gl.TargetAdjusted01 != ISNULL(staff.TargetAdjustedDollars01, 0) OR
            gl.TargetAdjusted02 != ISNULL(staff.TargetAdjustedDollars02, 0) OR
            gl.TargetAdjusted03 != ISNULL(staff.TargetAdjustedDollars03, 0) OR
            gl.TargetAdjusted04 != ISNULL(staff.TargetAdjustedDollars04, 0) OR
            gl.TargetAdjusted05 != ISNULL(staff.TargetAdjustedDollars05, 0) OR
            gl.TargetAdjusted06 != ISNULL(staff.TargetAdjustedDollars06, 0) OR
            gl.TargetAdjusted07 != ISNULL(staff.TargetAdjustedDollars07, 0) OR
            gl.TargetAdjusted08 != ISNULL(staff.TargetAdjustedDollars08, 0) OR
            gl.TargetAdjusted09 != ISNULL(staff.TargetAdjustedDollars09, 0) OR
            gl.TargetAdjusted10 != ISNULL(staff.TargetAdjustedDollars10, 0) OR
            gl.TargetAdjusted11 != ISNULL(staff.TargetAdjustedDollars11, 0) OR
            gl.TargetAdjusted12 != ISNULL(staff.TargetAdjustedDollars12, 0) OR
            gl.TargetLockFlag != 1 OR
            gl.BudgetAdjusted01 != ISNULL(staff.BudgetAdjustedDollars01, 0) OR
            gl.BudgetAdjusted02 != ISNULL(staff.BudgetAdjustedDollars02, 0) OR
            gl.BudgetAdjusted03 != ISNULL(staff.BudgetAdjustedDollars03, 0) OR
            gl.BudgetAdjusted04 != ISNULL(staff.BudgetAdjustedDollars04, 0) OR
            gl.BudgetAdjusted05 != ISNULL(staff.BudgetAdjustedDollars05, 0) OR
            gl.BudgetAdjusted06 != ISNULL(staff.BudgetAdjustedDollars06, 0) OR
            gl.BudgetAdjusted07 != ISNULL(staff.BudgetAdjustedDollars07, 0) OR
            gl.BudgetAdjusted08 != ISNULL(staff.BudgetAdjustedDollars08, 0) OR
            gl.BudgetAdjusted09 != ISNULL(staff.BudgetAdjustedDollars09, 0) OR
            gl.BudgetAdjusted10 != ISNULL(staff.BudgetAdjustedDollars10, 0) OR
            gl.BudgetAdjusted11 != ISNULL(staff.BudgetAdjustedDollars11, 0) OR
            gl.BudgetAdjusted12 != ISNULL(staff.BudgetAdjustedDollars12, 0) OR
            gl.BudgetLockFlag != 1 OR
            gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.ProjectionAdjustedDollars01, 0) ELSE gl.ProjectionAdjusted01 END OR
            gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.ProjectionAdjustedDollars02, 0) ELSE gl.ProjectionAdjusted02 END OR
            gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.ProjectionAdjustedDollars03, 0) ELSE gl.ProjectionAdjusted03 END OR
            gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.ProjectionAdjustedDollars04, 0) ELSE gl.ProjectionAdjusted04 END OR
            gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.ProjectionAdjustedDollars05, 0) ELSE gl.ProjectionAdjusted05 END OR
            gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.ProjectionAdjustedDollars06, 0) ELSE gl.ProjectionAdjusted06 END OR
            gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.ProjectionAdjustedDollars07, 0) ELSE gl.ProjectionAdjusted07 END OR
            gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.ProjectionAdjustedDollars08, 0) ELSE gl.ProjectionAdjusted08 END OR
            gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.ProjectionAdjustedDollars09, 0) ELSE gl.ProjectionAdjusted09 END OR
            gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.ProjectionAdjustedDollars10, 0) ELSE gl.ProjectionAdjusted10 END OR
            gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.ProjectionAdjustedDollars11, 0) ELSE gl.ProjectionAdjusted11 END OR
            gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.ProjectionAdjustedDollars12, 0) ELSE gl.ProjectionAdjusted12 END OR
            gl.ProjectionLockFlag != 1
            )

END ELSE BEGIN
    
    WITH StaffingSubquery AS (
    SELECT
        s.DepartmentID,
        s.AccountID,
        s.VariabilityID,
        s.EntityGroupConfigID,
        SUM(s.TargetAdjustedDollars01) AS TargetAdjustedDollars01,
        SUM(s.TargetAdjustedDollars02) AS TargetAdjustedDollars02,
        SUM(s.TargetAdjustedDollars03) AS TargetAdjustedDollars03,
        SUM(s.TargetAdjustedDollars04) AS TargetAdjustedDollars04,
        SUM(s.TargetAdjustedDollars05) AS TargetAdjustedDollars05,
        SUM(s.TargetAdjustedDollars06) AS TargetAdjustedDollars06,
        SUM(s.TargetAdjustedDollars07) AS TargetAdjustedDollars07,
        SUM(s.TargetAdjustedDollars08) AS TargetAdjustedDollars08,
        SUM(s.TargetAdjustedDollars09) AS TargetAdjustedDollars09,
        SUM(s.TargetAdjustedDollars10) AS TargetAdjustedDollars10,
        SUM(s.TargetAdjustedDollars11) AS TargetAdjustedDollars11,
        SUM(s.TargetAdjustedDollars12) AS TargetAdjustedDollars12,
        SUM(s.BudgetAdjustedDollars01) AS BudgetAdjustedDollars01,
        SUM(s.BudgetAdjustedDollars02) AS BudgetAdjustedDollars02,
        SUM(s.BudgetAdjustedDollars03) AS BudgetAdjustedDollars03,
        SUM(s.BudgetAdjustedDollars04) AS BudgetAdjustedDollars04,
        SUM(s.BudgetAdjustedDollars05) AS BudgetAdjustedDollars05,
        SUM(s.BudgetAdjustedDollars06) AS BudgetAdjustedDollars06,
        SUM(s.BudgetAdjustedDollars07) AS BudgetAdjustedDollars07,
        SUM(s.BudgetAdjustedDollars08) AS BudgetAdjustedDollars08,
        SUM(s.BudgetAdjustedDollars09) AS BudgetAdjustedDollars09,
        SUM(s.BudgetAdjustedDollars10) AS BudgetAdjustedDollars10,
        SUM(s.BudgetAdjustedDollars11) AS BudgetAdjustedDollars11,
        SUM(s.BudgetAdjustedDollars12) AS BudgetAdjustedDollars12,
        SUM(s.ProjectionAdjustedDollars01) AS ProjectionAdjustedDollars01,
        SUM(s.ProjectionAdjustedDollars02) AS ProjectionAdjustedDollars02,
        SUM(s.ProjectionAdjustedDollars03) AS ProjectionAdjustedDollars03,
        SUM(s.ProjectionAdjustedDollars04) AS ProjectionAdjustedDollars04,
        SUM(s.ProjectionAdjustedDollars05) AS ProjectionAdjustedDollars05,
        SUM(s.ProjectionAdjustedDollars06) AS ProjectionAdjustedDollars06,
        SUM(s.ProjectionAdjustedDollars07) AS ProjectionAdjustedDollars07,
        SUM(s.ProjectionAdjustedDollars08) AS ProjectionAdjustedDollars08,
        SUM(s.ProjectionAdjustedDollars09) AS ProjectionAdjustedDollars09,
        SUM(s.ProjectionAdjustedDollars10) AS ProjectionAdjustedDollars10,
        SUM(s.ProjectionAdjustedDollars11) AS ProjectionAdjustedDollars11,
        SUM(s.ProjectionAdjustedDollars12) AS ProjectionAdjustedDollars12
    FROM #tmpStaffing s
    GROUP BY
        s.DepartmentID,
        s.AccountID,
        s.VariabilityID,
        s.EntityGroupConfigID
	)
	UPDATE gl
	SET
		gl.TargetAdjusted01 = ISNULL(ss.TargetAdjustedDollars01, 0),
		gl.TargetAdjusted02 = ISNULL(ss.TargetAdjustedDollars02, 0),
		gl.TargetAdjusted03 = ISNULL(ss.TargetAdjustedDollars03, 0),
		gl.TargetAdjusted04 = ISNULL(ss.TargetAdjustedDollars04, 0),
		gl.TargetAdjusted05 = ISNULL(ss.TargetAdjustedDollars05, 0),
		gl.TargetAdjusted06 = ISNULL(ss.TargetAdjustedDollars06, 0),
		gl.TargetAdjusted07 = ISNULL(ss.TargetAdjustedDollars07, 0),
		gl.TargetAdjusted08 = ISNULL(ss.TargetAdjustedDollars08, 0),
		gl.TargetAdjusted09 = ISNULL(ss.TargetAdjustedDollars09, 0),
		gl.TargetAdjusted10 = ISNULL(ss.TargetAdjustedDollars10, 0),
		gl.TargetAdjusted11 = ISNULL(ss.TargetAdjustedDollars11, 0),
		gl.TargetAdjusted12 = ISNULL(ss.TargetAdjustedDollars12, 0),
		gl.TargetLockFlag = 1,
		gl.TargetLockType = 3,
		gl.BudgetAdjusted01 = ISNULL(ss.BudgetAdjustedDollars01, 0),
		gl.BudgetAdjusted02 = ISNULL(ss.BudgetAdjustedDollars02, 0),
		gl.BudgetAdjusted03 = ISNULL(ss.BudgetAdjustedDollars03, 0),
		gl.BudgetAdjusted04 = ISNULL(ss.BudgetAdjustedDollars04, 0),
		gl.BudgetAdjusted05 = ISNULL(ss.BudgetAdjustedDollars05, 0),
		gl.BudgetAdjusted06 = ISNULL(ss.BudgetAdjustedDollars06, 0),
		gl.BudgetAdjusted07 = ISNULL(ss.BudgetAdjustedDollars07, 0),
		gl.BudgetAdjusted08 = ISNULL(ss.BudgetAdjustedDollars08, 0),
		gl.BudgetAdjusted09 = ISNULL(ss.BudgetAdjustedDollars09, 0),
		gl.BudgetAdjusted10 = ISNULL(ss.BudgetAdjustedDollars10, 0),
		gl.BudgetAdjusted11 = ISNULL(ss.BudgetAdjustedDollars11, 0),
		gl.BudgetAdjusted12 = ISNULL(ss.BudgetAdjustedDollars12, 0),
		gl.BudgetLockFlag = 1,
		gl.BudgetLockType = 3,
		gl.ProjectionAdjusted01 = CASE WHEN @MonthsLoaded < 1 THEN ISNULL(ss.ProjectionAdjustedDollars01, 0) ELSE gl.ProjectionAdjusted01 END,
		gl.ProjectionAdjusted02 = CASE WHEN @MonthsLoaded < 2 THEN ISNULL(ss.ProjectionAdjustedDollars02, 0) ELSE gl.ProjectionAdjusted02 END,
		gl.ProjectionAdjusted03 = CASE WHEN @MonthsLoaded < 3 THEN ISNULL(ss.ProjectionAdjustedDollars03, 0) ELSE gl.ProjectionAdjusted03 END,
		gl.ProjectionAdjusted04 = CASE WHEN @MonthsLoaded < 4 THEN ISNULL(ss.ProjectionAdjustedDollars04, 0) ELSE gl.ProjectionAdjusted04 END,
		gl.ProjectionAdjusted05 = CASE WHEN @MonthsLoaded < 5 THEN ISNULL(ss.ProjectionAdjustedDollars05, 0) ELSE gl.ProjectionAdjusted05 END,
		gl.ProjectionAdjusted06 = CASE WHEN @MonthsLoaded < 6 THEN ISNULL(ss.ProjectionAdjustedDollars06, 0) ELSE gl.ProjectionAdjusted06 END,
		gl.ProjectionAdjusted07 = CASE WHEN @MonthsLoaded < 7 THEN ISNULL(ss.ProjectionAdjustedDollars07, 0) ELSE gl.ProjectionAdjusted07 END,
		gl.ProjectionAdjusted08 = CASE WHEN @MonthsLoaded < 8 THEN ISNULL(ss.ProjectionAdjustedDollars08, 0) ELSE gl.ProjectionAdjusted08 END,
		gl.ProjectionAdjusted09 = CASE WHEN @MonthsLoaded < 9 THEN ISNULL(ss.ProjectionAdjustedDollars09, 0) ELSE gl.ProjectionAdjusted09 END,
		gl.ProjectionAdjusted10 = CASE WHEN @MonthsLoaded < 10 THEN ISNULL(ss.ProjectionAdjustedDollars10, 0) ELSE gl.ProjectionAdjusted10 END,
		gl.ProjectionAdjusted11 = CASE WHEN @MonthsLoaded < 11 THEN ISNULL(ss.ProjectionAdjustedDollars11, 0) ELSE gl.ProjectionAdjusted11 END,
		gl.ProjectionAdjusted12 = CASE WHEN @MonthsLoaded < 12 THEN ISNULL(ss.ProjectionAdjustedDollars12, 0) ELSE gl.ProjectionAdjusted12 END,
		gl.ProjectionLockFlag = 1,
		gl.ProjectionLockType = 3
	FROM [fp].[GeneralLedger] gl
	INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID
	INNER JOIN #tmpAcct acct ON gl.AccountID = acct.AccountID
	LEFT JOIN StaffingSubquery ss ON ss.DepartmentID = gl.DepartmentID
		AND ss.AccountID = gl.AccountID
		AND ss.EntityGroupConfigID = gl.EntityGroupConfigID
		AND ss.VariabilityID = gl.VariabilityID
	WHERE gl.EntityGroupConfigID = @EntityGroupConfigID
		AND (
			gl.TargetAdjusted01 != ISNULL(ss.TargetAdjustedDollars01, 0) OR
			gl.TargetAdjusted02 != ISNULL(ss.TargetAdjustedDollars02, 0) OR
			gl.TargetAdjusted03 != ISNULL(ss.TargetAdjustedDollars03, 0) OR
			gl.TargetAdjusted04 != ISNULL(ss.TargetAdjustedDollars04, 0) OR
			gl.TargetAdjusted05 != ISNULL(ss.TargetAdjustedDollars05, 0) OR
			gl.TargetAdjusted06 != ISNULL(ss.TargetAdjustedDollars06, 0) OR
			gl.TargetAdjusted07 != ISNULL(ss.TargetAdjustedDollars07, 0) OR
			gl.TargetAdjusted08 != ISNULL(ss.TargetAdjustedDollars08, 0) OR
			gl.TargetAdjusted09 != ISNULL(ss.TargetAdjustedDollars09, 0) OR
			gl.TargetAdjusted10 != ISNULL(ss.TargetAdjustedDollars10, 0) OR
			gl.TargetAdjusted11 != ISNULL(ss.TargetAdjustedDollars11, 0) OR
			gl.TargetAdjusted12 != ISNULL(ss.TargetAdjustedDollars12, 0) OR
			gl.TargetLockFlag != 1 OR
			gl.BudgetAdjusted01 != ISNULL(ss.BudgetAdjustedDollars01, 0) OR
			gl.BudgetAdjusted02 != ISNULL(ss.BudgetAdjustedDollars02, 0) OR
			gl.BudgetAdjusted03 != ISNULL(ss.BudgetAdjustedDollars03, 0) OR
			gl.BudgetAdjusted04 != ISNULL(ss.BudgetAdjustedDollars04, 0) OR
			gl.BudgetAdjusted05 != ISNULL(ss.BudgetAdjustedDollars05, 0) OR
			gl.BudgetAdjusted06 != ISNULL(ss.BudgetAdjustedDollars06, 0) OR
			gl.BudgetAdjusted07 != ISNULL(ss.BudgetAdjustedDollars07, 0) OR
			gl.BudgetAdjusted08 != ISNULL(ss.BudgetAdjustedDollars08, 0) OR
			gl.BudgetAdjusted09 != ISNULL(ss.BudgetAdjustedDollars09, 0) OR
			gl.BudgetAdjusted10 != ISNULL(ss.BudgetAdjustedDollars10, 0) OR
			gl.BudgetAdjusted11 != ISNULL(ss.BudgetAdjustedDollars11, 0) OR
			gl.BudgetAdjusted12 != ISNULL(ss.BudgetAdjustedDollars12, 0) OR
			gl.BudgetLockFlag != 1 OR
			gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(ss.ProjectionAdjustedDollars01, 0) ELSE gl.ProjectionAdjusted01 END OR
			gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(ss.ProjectionAdjustedDollars02, 0) ELSE gl.ProjectionAdjusted02 END OR
			gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(ss.ProjectionAdjustedDollars03, 0) ELSE gl.ProjectionAdjusted03 END OR
			gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(ss.ProjectionAdjustedDollars04, 0) ELSE gl.ProjectionAdjusted04 END OR
			gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(ss.ProjectionAdjustedDollars05, 0) ELSE gl.ProjectionAdjusted05 END OR
			gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(ss.ProjectionAdjustedDollars06, 0) ELSE gl.ProjectionAdjusted06 END OR
			gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(ss.ProjectionAdjustedDollars07, 0) ELSE gl.ProjectionAdjusted07 END OR
			gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(ss.ProjectionAdjustedDollars08, 0) ELSE gl.ProjectionAdjusted08 END OR
			gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(ss.ProjectionAdjustedDollars09, 0) ELSE gl.ProjectionAdjusted09 END OR
			gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(ss.ProjectionAdjustedDollars10, 0) ELSE gl.ProjectionAdjusted10 END OR
			gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(ss.ProjectionAdjustedDollars11, 0) ELSE gl.ProjectionAdjusted11 END OR
			gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(ss.ProjectionAdjustedDollars12, 0) ELSE gl.ProjectionAdjusted12 END OR
			gl.ProjectionLockFlag != 1
		);

END
END
GO


---------------------------------------------

-- fp.procStaffingToGlCrosswalk_Initial
/*************************************************************  
 ** Change History  
 **************************************************************  
 ** CID  Date        Author  WI   Description  
 ** 1    2023-08-22  MY      JAZZ-59505 Initial Creation  
 ** 2    2023-10-23  Matt Hayden  JAZZ-62450 Update for Staffing table restructure
 ** 3    2024-01-31  NH      JAZZ-64064 Move Provider Planning FF as a setting in Plan Config
 *************************************************************/
CREATE PROCEDURE [fp].[procStaffingToGlCrosswalk_Initial] 
    @EntityGroupConfigID INT,
    @BudgetConfigID INT,
    @SqlJoin NVARCHAR(MAX),
    @MonthsLoaded INT,
    @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY,
    @IsDebug BIT = 0 
AS BEGIN 

IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing
IF OBJECT_ID('tempdb..#tmpProvider') IS NOT NULL DROP TABLE #tmpProvider
IF OBJECT_ID('tempdb..#tmpAcct') IS NOT NULL DROP TABLE #tmpAcct
IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment

CREATE TABLE #tmpAcct (AccountID INT)
CREATE TABLE #FilterByDepartment (DepartmentID INT)

INSERT INTO
    #FilterByDepartment (DepartmentID)
SELECT
    DepartmentID
FROM
    fp.funcGetSourceDimensionalityAsTable(@SourceDimensionality)
    
IF NOT EXISTS(
    SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN

    INSERT INTO
        #FilterByDepartment (DepartmentID)
    SELECT
        DISTINCT DepartmentID
    FROM
        [fp].[GeneralLedger] d WITH (READUNCOMMITTED) -- using GL here because ultimately we are updating GL and anything from Staffing should have been padded to GL  
    WHERE
        d.EntityGroupConfigID = @EntityGroupConfigID
END 

DECLARE @IsProviderPlanningEnabled BIT;
SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;

CREATE TABLE #tmpStaffing (
    DepartmentID INT,
    AccountID INT,
    VariabilityID INT,
    EntityGroupConfigID INT,
    InitialBudgetDollars01 DECIMAL(19, 8),
    InitialBudgetDollars02 DECIMAL(19, 8),
    InitialBudgetDollars03 DECIMAL(19, 8),
    InitialBudgetDollars04 DECIMAL(19, 8),
    InitialBudgetDollars05 DECIMAL(19, 8),
    InitialBudgetDollars06 DECIMAL(19, 8),
    InitialBudgetDollars07 DECIMAL(19, 8),
    InitialBudgetDollars08 DECIMAL(19, 8),
    InitialBudgetDollars09 DECIMAL(19, 8),
    InitialBudgetDollars10 DECIMAL(19, 8),
    InitialBudgetDollars11 DECIMAL(19, 8),
    InitialBudgetDollars12 DECIMAL(19, 8),
    InitialProjectionDollars01 DECIMAL(19, 8),
    InitialProjectionDollars02 DECIMAL(19, 8),
    InitialProjectionDollars03 DECIMAL(19, 8),
    InitialProjectionDollars04 DECIMAL(19, 8),
    InitialProjectionDollars05 DECIMAL(19, 8),
    InitialProjectionDollars06 DECIMAL(19, 8),
    InitialProjectionDollars07 DECIMAL(19, 8),
    InitialProjectionDollars08 DECIMAL(19, 8),
    InitialProjectionDollars09 DECIMAL(19, 8),
    InitialProjectionDollars10 DECIMAL(19, 8),
    InitialProjectionDollars11 DECIMAL(19, 8),
    InitialProjectionDollars12 DECIMAL(19, 8)
)

INSERT INTO
    #tmpAcct (AccountID)
SELECT
    DISTINCT AccountID
FROM
    [clientob].[FactPayrollToAccountCrosswalk] (readuncommitted)
WHERE
    UnitTypeID = 34


DECLARE @SqlStaffing NVARCHAR(MAX)

SET @SqlStaffing = '
    INSERT INTO #tmpStaffing (
        DepartmentID,
        AccountID,
        VariabilityID,
        EntityGroupConfigID,
        InitialBudgetDollars01,
        InitialBudgetDollars02,
        InitialBudgetDollars03,
        InitialBudgetDollars04,
        InitialBudgetDollars05,
        InitialBudgetDollars06,
        InitialBudgetDollars07,
        InitialBudgetDollars08,
        InitialBudgetDollars09,
        InitialBudgetDollars10,
        InitialBudgetDollars11,
        InitialBudgetDollars12,
        InitialProjectionDollars01,
        InitialProjectionDollars02,
        InitialProjectionDollars03,
        InitialProjectionDollars04,
        InitialProjectionDollars05,
        InitialProjectionDollars06,
        InitialProjectionDollars07,
        InitialProjectionDollars08,
        InitialProjectionDollars09,
        InitialProjectionDollars10,
        InitialProjectionDollars11,
        InitialProjectionDollars12)
    SELECT
        staff.DepartmentID,   
        pax.AccountID,   
        staff.VariabilityID,  
        staff.EntityGroupConfigID,
        ISNULL(staff.InitialBudgetDollars01, 0),
        ISNULL(staff.InitialBudgetDollars02, 0),
        ISNULL(staff.InitialBudgetDollars03, 0),
        ISNULL(staff.InitialBudgetDollars04, 0),
        ISNULL(staff.InitialBudgetDollars05, 0),
        ISNULL(staff.InitialBudgetDollars06, 0),
        ISNULL(staff.InitialBudgetDollars07, 0),
        ISNULL(staff.InitialBudgetDollars08, 0),
        ISNULL(staff.InitialBudgetDollars09, 0),
        ISNULL(staff.InitialBudgetDollars10, 0),
        ISNULL(staff.InitialBudgetDollars11, 0),
        ISNULL(staff.InitialBudgetDollars12, 0),
        ISNULL(staff.InitialProjectionDollars01, 0),
        ISNULL(staff.InitialProjectionDollars02, 0),
        ISNULL(staff.InitialProjectionDollars03, 0),
        ISNULL(staff.InitialProjectionDollars04, 0),
        ISNULL(staff.InitialProjectionDollars05, 0),
        ISNULL(staff.InitialProjectionDollars06, 0),
        ISNULL(staff.InitialProjectionDollars07, 0),
        ISNULL(staff.InitialProjectionDollars08, 0),
        ISNULL(staff.InitialProjectionDollars09, 0),
        ISNULL(staff.InitialProjectionDollars10, 0),
        ISNULL(staff.InitialProjectionDollars11, 0),
        ISNULL(staff.InitialProjectionDollars12, 0)
    FROM [fp].[Staffing] staff (readuncommitted)
    INNER JOIN #FilterByDepartment dept ON staff.DepartmentID = dept.DepartmentID '
    + @SqlJoin + ' 
    WHERE staff.SubsectionID = 3  
    AND pax.UnitTypeID = 34  
    AND staff.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS NVARCHAR(10))

EXEC (@SqlStaffing);
    
IF @IsProviderPlanningEnabled = 1 BEGIN

    CREATE TABLE #tmpProvider (
        ProviderLineItemID TINYINT,
        AccountID INT,
        ProviderTypeID INT,
        VariabilityID INT
    )

    INSERT INTO
        #tmpProvider (ProviderLineItemID, AccountID, ProviderTypeID, VariabilityID)
    SELECT
        ProviderLineItemID,
        COALESCE(detail.AccountID, psc.AccountID) AS AccountID,
        ISNULL(ProviderTypeID, 0),
        VariabilityID
    FROM
        fp.ProviderStaffingConfig psc
        LEFT JOIN fp.ProviderStaffingConfigProviderType detail on psc.ProviderStaffingConfigID = detail.ProviderStaffingConfigID
    WHERE
        BudgetConfigID = @BudgetConfigID


    INSERT INTO #tmpAcct (AccountID)
    SELECT  DISTINCT a.AccountID
    FROM
        #tmpProvider a
        LEFT JOIN #tmpAcct t on a.AccountID = t.AccountID
    WHERE
        t.AccountID IS NULL

    INSERT INTO #tmpStaffing (
        DepartmentID,
        AccountID,
        VariabilityID,
        EntityGroupConfigID,
        InitialBudgetDollars01,
        InitialBudgetDollars02,
        InitialBudgetDollars03,
        InitialBudgetDollars04,
        InitialBudgetDollars05,
        InitialBudgetDollars06,
        InitialBudgetDollars07,
        InitialBudgetDollars08,
        InitialBudgetDollars09,
        InitialBudgetDollars10,
        InitialBudgetDollars11,
        InitialBudgetDollars12,
        InitialProjectionDollars01,
        InitialProjectionDollars02,
        InitialProjectionDollars03,
        InitialProjectionDollars04,
        InitialProjectionDollars05,
        InitialProjectionDollars06,
        InitialProjectionDollars07,
        InitialProjectionDollars08,
        InitialProjectionDollars09,
        InitialProjectionDollars10,
        InitialProjectionDollars11,
        InitialProjectionDollars12)
    SELECT
        staff.DepartmentID,
        prov.AccountID,
        staff.VariabilityID,
        staff.EntityGroupConfigID,
        ISNULL(staff.InitialBudgetDollars01, 0),
        ISNULL(staff.InitialBudgetDollars02, 0),
        ISNULL(staff.InitialBudgetDollars03, 0),
        ISNULL(staff.InitialBudgetDollars04, 0),
        ISNULL(staff.InitialBudgetDollars05, 0),
        ISNULL(staff.InitialBudgetDollars06, 0),
        ISNULL(staff.InitialBudgetDollars07, 0),
        ISNULL(staff.InitialBudgetDollars08, 0),
        ISNULL(staff.InitialBudgetDollars09, 0),
        ISNULL(staff.InitialBudgetDollars10, 0),
        ISNULL(staff.InitialBudgetDollars11, 0),
        ISNULL(staff.InitialBudgetDollars12, 0),
        ISNULL(staff.InitialProjectionDollars01, 0),
        ISNULL(staff.InitialProjectionDollars02, 0),
        ISNULL(staff.InitialProjectionDollars03, 0),
        ISNULL(staff.InitialProjectionDollars04, 0),
        ISNULL(staff.InitialProjectionDollars05, 0),
        ISNULL(staff.InitialProjectionDollars06, 0),
        ISNULL(staff.InitialProjectionDollars07, 0),
        ISNULL(staff.InitialProjectionDollars08, 0),
        ISNULL(staff.InitialProjectionDollars09, 0),
        ISNULL(staff.InitialProjectionDollars10, 0),
        ISNULL(staff.InitialProjectionDollars11, 0),
        ISNULL(staff.InitialProjectionDollars12, 0)
    FROM [fp].[Staffing] staff (readuncommitted)
    INNER JOIN #tmpProvider prov ON staff.ProviderLineItemID = prov.ProviderLineItemID AND staff.VariabilityID = prov.VariabilityID
    INNER JOIN #FilterByDepartment dept ON staff.DepartmentID = dept.DepartmentID
    INNER JOIN #tmpAcct acc ON prov.AccountID = acc.AccountID
    WHERE   staff.SubsectionID = 4
        AND staff.EntityGroupConfigID = @EntityGroupConfigID
        AND (prov.ProviderTypeID = 0 OR prov.ProviderTypeID = staff.ProviderTypeID)
END

IF (@IsDebug = 1) BEGIN
    SELECT
        gl.AccountID,
        gl.DepartmentID,
        gl.VariabilityID,
        gl.EntityGroupConfigID,
        ISNULL(staff.InitialBudgetDollars01, 0),
        ISNULL(staff.InitialBudgetDollars02, 0),
        ISNULL(staff.InitialBudgetDollars03, 0),
        ISNULL(staff.InitialBudgetDollars04, 0),
        ISNULL(staff.InitialBudgetDollars05, 0),
        ISNULL(staff.InitialBudgetDollars06, 0),
        ISNULL(staff.InitialBudgetDollars07, 0),
        ISNULL(staff.InitialBudgetDollars08, 0),
        ISNULL(staff.InitialBudgetDollars09, 0),
        ISNULL(staff.InitialBudgetDollars10, 0),
        ISNULL(staff.InitialBudgetDollars11, 0),
        ISNULL(staff.InitialBudgetDollars12, 0),
        ISNULL(staff.InitialProjectionDollars01, 0),
        ISNULL(staff.InitialProjectionDollars02, 0),
        ISNULL(staff.InitialProjectionDollars03, 0),
        ISNULL(staff.InitialProjectionDollars04, 0),
        ISNULL(staff.InitialProjectionDollars05, 0),
        ISNULL(staff.InitialProjectionDollars06, 0),
        ISNULL(staff.InitialProjectionDollars07, 0),
        ISNULL(staff.InitialProjectionDollars08, 0),
        ISNULL(staff.InitialProjectionDollars09, 0),
        ISNULL(staff.InitialProjectionDollars10, 0),
        ISNULL(staff.InitialProjectionDollars11, 0),
        ISNULL(staff.InitialProjectionDollars12, 0)
    FROM
        [fp].[GeneralLedger] gl
        INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID 
        INNER JOIN #tmpAcct fptac ON gl.AccountID = fptac.AccountID
        LEFT JOIN (
            SELECT  DepartmentID, AccountID, VariabilityID, EntityGroupConfigID
            ,       SUM(InitialBudgetDollars01) as InitialBudgetDollars01
            ,       SUM(InitialBudgetDollars02) as InitialBudgetDollars02
            ,       SUM(InitialBudgetDollars03) as InitialBudgetDollars03
            ,       SUM(InitialBudgetDollars04) as InitialBudgetDollars04
            ,       SUM(InitialBudgetDollars05) as InitialBudgetDollars05
            ,       SUM(InitialBudgetDollars06) as InitialBudgetDollars06
            ,       SUM(InitialBudgetDollars07) as InitialBudgetDollars07
            ,       SUM(InitialBudgetDollars08) as InitialBudgetDollars08
            ,       SUM(InitialBudgetDollars09) as InitialBudgetDollars09
            ,       SUM(InitialBudgetDollars10) as InitialBudgetDollars10
            ,       SUM(InitialBudgetDollars11) as InitialBudgetDollars11
            ,       SUM(InitialBudgetDollars12) as InitialBudgetDollars12
            ,       SUM(InitialProjectionDollars01) as InitialProjectionDollars01
            ,       SUM(InitialProjectionDollars02) as InitialProjectionDollars02
            ,       SUM(InitialProjectionDollars03) as InitialProjectionDollars03
            ,       SUM(InitialProjectionDollars04) as InitialProjectionDollars04
            ,       SUM(InitialProjectionDollars05) as InitialProjectionDollars05
            ,       SUM(InitialProjectionDollars06) as InitialProjectionDollars06
            ,       SUM(InitialProjectionDollars07) as InitialProjectionDollars07
            ,       SUM(InitialProjectionDollars08) as InitialProjectionDollars08
            ,       SUM(InitialProjectionDollars09) as InitialProjectionDollars09
            ,       SUM(InitialProjectionDollars10) as InitialProjectionDollars10
            ,       SUM(InitialProjectionDollars11) as InitialProjectionDollars11
            ,       SUM(InitialProjectionDollars12) as InitialProjectionDollars12
            FROM    #tmpStaffing
            GROUP BY DepartmentID, AccountID, VariabilityID, EntityGroupConfigID
        ) staff ON staff.DepartmentID = gl.DepartmentID
            AND staff.AccountID = gl.AccountID
            AND staff.EntityGroupConfigID = gl.EntityGroupConfigID
            AND staff.VariabilityID = gl.VariabilityID
    WHERE
        gl.EntityGroupConfigID = @EntityGroupConfigID
        AND (
            gl.InitialBudget01 != ISNULL(staff.InitialBudgetDollars01, 0)
            OR gl.InitialBudget02 != ISNULL(staff.InitialBudgetDollars02, 0)
            OR gl.InitialBudget03 != ISNULL(staff.InitialBudgetDollars03, 0)
            OR gl.InitialBudget04 != ISNULL(staff.InitialBudgetDollars04, 0)
            OR gl.InitialBudget05 != ISNULL(staff.InitialBudgetDollars05, 0)
            OR gl.InitialBudget06 != ISNULL(staff.InitialBudgetDollars06, 0)
            OR gl.InitialBudget07 != ISNULL(staff.InitialBudgetDollars07, 0)
            OR gl.InitialBudget08 != ISNULL(staff.InitialBudgetDollars08, 0)
            OR gl.InitialBudget09 != ISNULL(staff.InitialBudgetDollars09, 0)
            OR gl.InitialBudget10 != ISNULL(staff.InitialBudgetDollars10, 0)
            OR gl.InitialBudget11 != ISNULL(staff.InitialBudgetDollars11, 0)
            OR gl.InitialBudget12 != ISNULL(staff.InitialBudgetDollars12, 0)
            OR gl.InitialProjection01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.InitialProjectionDollars01, 0) ELSE gl.InitialProjection01 END
            OR gl.InitialProjection02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.InitialProjectionDollars02, 0) ELSE gl.InitialProjection02 END
            OR gl.InitialProjection03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.InitialProjectionDollars03, 0) ELSE gl.InitialProjection03 END
            OR gl.InitialProjection04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.InitialProjectionDollars04, 0) ELSE gl.InitialProjection04 END
            OR gl.InitialProjection05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.InitialProjectionDollars05, 0) ELSE gl.InitialProjection05 END
            OR gl.InitialProjection06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.InitialProjectionDollars06, 0) ELSE gl.InitialProjection06 END
            OR gl.InitialProjection07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.InitialProjectionDollars07, 0) ELSE gl.InitialProjection07 END
            OR gl.InitialProjection08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.InitialProjectionDollars08, 0) ELSE gl.InitialProjection08 END
            OR gl.InitialProjection09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.InitialProjectionDollars09, 0) ELSE gl.InitialProjection09 END
            OR gl.InitialProjection10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.InitialProjectionDollars10, 0) ELSE gl.InitialProjection10 END
            OR gl.InitialProjection11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.InitialProjectionDollars11, 0) ELSE gl.InitialProjection11 END
            OR gl.InitialProjection12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.InitialProjectionDollars12, 0) ELSE gl.InitialProjection12 END
        )
END
ELSE BEGIN

    UPDATE gl
    SET gl.InitialBudget01 = ISNULL(staff.InitialBudgetDollars01, 0),
        gl.InitialBudget02 = ISNULL(staff.InitialBudgetDollars02, 0),
        gl.InitialBudget03 = ISNULL(staff.InitialBudgetDollars03, 0),
        gl.InitialBudget04 = ISNULL(staff.InitialBudgetDollars04, 0),
        gl.InitialBudget05 = ISNULL(staff.InitialBudgetDollars05, 0),
        gl.InitialBudget06 = ISNULL(staff.InitialBudgetDollars06, 0),
        gl.InitialBudget07 = ISNULL(staff.InitialBudgetDollars07, 0),
        gl.InitialBudget08 = ISNULL(staff.InitialBudgetDollars08, 0),
        gl.InitialBudget09 = ISNULL(staff.InitialBudgetDollars09, 0),
        gl.InitialBudget10 = ISNULL(staff.InitialBudgetDollars10, 0),
        gl.InitialBudget11 = ISNULL(staff.InitialBudgetDollars11, 0),
        gl.InitialBudget12 = ISNULL(staff.InitialBudgetDollars12, 0),
        gl.InitialProjection01 = CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.InitialProjectionDollars01, 0) ELSE gl.InitialProjection01 END,
        gl.InitialProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.InitialProjectionDollars02, 0) ELSE gl.InitialProjection02 END,
        gl.InitialProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.InitialProjectionDollars03, 0) ELSE gl.InitialProjection03 END,
        gl.InitialProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.InitialProjectionDollars04, 0) ELSE gl.InitialProjection04 END,
        gl.InitialProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.InitialProjectionDollars05, 0) ELSE gl.InitialProjection05 END,
        gl.InitialProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.InitialProjectionDollars06, 0) ELSE gl.InitialProjection06 END,
        gl.InitialProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.InitialProjectionDollars07, 0) ELSE gl.InitialProjection07 END,
        gl.InitialProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.InitialProjectionDollars08, 0) ELSE gl.InitialProjection08 END,
        gl.InitialProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.InitialProjectionDollars09, 0) ELSE gl.InitialProjection09 END,
        gl.InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.InitialProjectionDollars10, 0) ELSE gl.InitialProjection10 END,
        gl.InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.InitialProjectionDollars11, 0) ELSE gl.InitialProjection11 END,
        gl.InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.InitialProjectionDollars12, 0) ELSE gl.InitialProjection12 END
    FROM [fp].[GeneralLedger] gl
        INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID
        INNER JOIN #tmpAcct acct ON gl.AccountID = acct.AccountID
        LEFT JOIN (
            SELECT  DepartmentID, AccountID, VariabilityID, EntityGroupConfigID
            ,       SUM(InitialBudgetDollars01) as InitialBudgetDollars01
            ,       SUM(InitialBudgetDollars02) as InitialBudgetDollars02
            ,       SUM(InitialBudgetDollars03) as InitialBudgetDollars03
            ,       SUM(InitialBudgetDollars04) as InitialBudgetDollars04
            ,       SUM(InitialBudgetDollars05) as InitialBudgetDollars05
            ,       SUM(InitialBudgetDollars06) as InitialBudgetDollars06
            ,       SUM(InitialBudgetDollars07) as InitialBudgetDollars07
            ,       SUM(InitialBudgetDollars08) as InitialBudgetDollars08
            ,       SUM(InitialBudgetDollars09) as InitialBudgetDollars09
            ,       SUM(InitialBudgetDollars10) as InitialBudgetDollars10
            ,       SUM(InitialBudgetDollars11) as InitialBudgetDollars11
            ,       SUM(InitialBudgetDollars12) as InitialBudgetDollars12
            ,       SUM(InitialProjectionDollars01) as InitialProjectionDollars01
            ,       SUM(InitialProjectionDollars02) as InitialProjectionDollars02
            ,       SUM(InitialProjectionDollars03) as InitialProjectionDollars03
            ,       SUM(InitialProjectionDollars04) as InitialProjectionDollars04
            ,       SUM(InitialProjectionDollars05) as InitialProjectionDollars05
            ,       SUM(InitialProjectionDollars06) as InitialProjectionDollars06
            ,       SUM(InitialProjectionDollars07) as InitialProjectionDollars07
            ,       SUM(InitialProjectionDollars08) as InitialProjectionDollars08
            ,       SUM(InitialProjectionDollars09) as InitialProjectionDollars09
            ,       SUM(InitialProjectionDollars10) as InitialProjectionDollars10
            ,       SUM(InitialProjectionDollars11) as InitialProjectionDollars11
            ,       SUM(InitialProjectionDollars12) as InitialProjectionDollars12
            FROM    #tmpStaffing s
            GROUP BY DepartmentID, AccountID, VariabilityID, EntityGroupConfigID
        ) staff ON staff.DepartmentID = gl.DepartmentID
            AND staff.AccountID = gl.AccountID
            AND staff.EntityGroupConfigID = gl.EntityGroupConfigID
            AND staff.VariabilityID = gl.VariabilityID
    WHERE
        gl.EntityGroupConfigID = @EntityGroupConfigID
        AND (
            gl.InitialBudget01 != ISNULL(staff.InitialBudgetDollars01, 0)
            OR gl.InitialBudget02 != ISNULL(staff.InitialBudgetDollars02, 0)
            OR gl.InitialBudget03 != ISNULL(staff.InitialBudgetDollars03, 0)
            OR gl.InitialBudget04 != ISNULL(staff.InitialBudgetDollars04, 0)
            OR gl.InitialBudget05 != ISNULL(staff.InitialBudgetDollars05, 0)
            OR gl.InitialBudget06 != ISNULL(staff.InitialBudgetDollars06, 0)
            OR gl.InitialBudget07 != ISNULL(staff.InitialBudgetDollars07, 0)
            OR gl.InitialBudget08 != ISNULL(staff.InitialBudgetDollars08, 0)
            OR gl.InitialBudget09 != ISNULL(staff.InitialBudgetDollars09, 0)
            OR gl.InitialBudget10 != ISNULL(staff.InitialBudgetDollars10, 0)
            OR gl.InitialBudget11 != ISNULL(staff.InitialBudgetDollars11, 0)
            OR gl.InitialBudget12 != ISNULL(staff.InitialBudgetDollars12, 0)
            OR gl.InitialProjection01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.InitialProjectionDollars01, 0) ELSE gl.InitialProjection01 END
            OR gl.InitialProjection02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.InitialProjectionDollars02, 0) ELSE gl.InitialProjection02 END
            OR gl.InitialProjection03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.InitialProjectionDollars03, 0) ELSE gl.InitialProjection03 END
            OR gl.InitialProjection04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.InitialProjectionDollars04, 0) ELSE gl.InitialProjection04 END
            OR gl.InitialProjection05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.InitialProjectionDollars05, 0) ELSE gl.InitialProjection05 END
            OR gl.InitialProjection06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.InitialProjectionDollars06, 0) ELSE gl.InitialProjection06 END
            OR gl.InitialProjection07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.InitialProjectionDollars07, 0) ELSE gl.InitialProjection07 END
            OR gl.InitialProjection08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.InitialProjectionDollars08, 0) ELSE gl.InitialProjection08 END
            OR gl.InitialProjection09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.InitialProjectionDollars09, 0) ELSE gl.InitialProjection09 END
            OR gl.InitialProjection10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.InitialProjectionDollars10, 0) ELSE gl.InitialProjection10 END
            OR gl.InitialProjection11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.InitialProjectionDollars11, 0) ELSE gl.InitialProjection11 END
            OR gl.InitialProjection12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.InitialProjectionDollars12, 0) ELSE gl.InitialProjection12 END
            )
END
END
GO


---------------------------------------------

-- fp.procStaffingToStatisticBudgetStampOff
CREATE     PROCEDURE [fp].[procStaffingToStatisticBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	01-31-2023  MY      JAZZ-48962		Initial Creation
	** 2	01-03-2024  MZ      JAZZ-65385		Added Target TimeClass
	** 3 	12-04-2023  BW/MZ   JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 4	01-30-2024  MZ      JAZZ-66319		Fix Join on [clientob].[FactPayrollToAccountCrosswalk] with zero-JobCode records
	** 5	03-18-2024  MZ	    JAZZ-68428		Removed HistoryItemGUID parameter
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode],
		[TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID])
	SELECT 
		d.DepartmentID,
		d.DepartmentCode,
		cw.AccountID,
		acc.AccountCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		m.FiscalMonthID,
		m.FiscalMonthCode,
		SUM(Value) AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
		CROSS APPLY (
		VALUES
			( 1, 51, BudgetAdjustedHours01), 
			( 2, 51, BudgetAdjustedHours02),
			( 3, 51, BudgetAdjustedHours03),
			( 4, 51, BudgetAdjustedHours04), 
			( 5, 51, BudgetAdjustedHours05), 
			( 6, 51, BudgetAdjustedHours06),
			( 7, 51, BudgetAdjustedHours07), 
			( 8, 51, BudgetAdjustedHours08), 
			( 9, 51, BudgetAdjustedHours09), 
			( 10, 51, BudgetAdjustedHours10),
			( 11, 51, BudgetAdjustedHours11), 
			( 12, 51, BudgetAdjustedHours12)

	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID
			INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			INNER JOIN (SELECT JobCodeID, PayCodeGroupID, UnitTypeID, AccountID FROM [clientob].[FactPayrollToAccountCrosswalk] p
					WHERE JobCodeID <> 0 OR (JobCodeID = 0 AND NOT EXISTS (
											SELECT 1
											FROM [clientob].[FactPayrollToAccountCrosswalk]
											WHERE AccountID = p.AccountID AND PayCodeGroupID = p.PayCodeGroupID 
											AND JobCodeID <> 0))
					) cw ON
				(CASE WHEN cw.JobCodeID <> 0 THEN cw.JobCodeID ELSE 1 END) = (CASE WHEN cw.JobCodeID <> 0 THEN jc.JobCodeID ELSE 1 END)
			AND cw.PayCodeGroupID = PCG.PayCodeGroupID
			AND UT.UnitTypeID = cw.UnitTypeID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = cw.AccountID
			WHERE staff.BudgetConfigID = @BudgetConfigID
			AND Value <> 0
   	GROUP BY
		d.DepartmentID,
		d.DepartmentCode,
		cw.AccountID,
		acc.AccountCode,
		bc.FiscalYearID,
		bc.FiscalYearID,
		m.FiscalMonthID,
		m.FiscalMonthCode
END
GO


---------------------------------------------

-- fp.procStaffingToStatisticProjectionStampOff
CREATE   PROCEDURE [fp].[procStaffingToStatisticProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	11-10-2023 AO      JAZZ-62128		Initial Creation
	** 2	01-04-2024 MZ      JAZZ-65385		Added Target TimeClass and IsMonthsLoadedIncluded
	** 3	01-24-2024 MZ      JAZZ-64527		Fix Months Loaded
	** 4 	12-04-2023 BW/MZ   JAZZ-63562		Data model restructure for Staffing/Merge with main
	** 5	01-30-2024 MZ      JAZZ-66319		Fix Join on [clientob].[FactPayrollToAccountCrosswalk] with zero-JobCode records
	** 6	03-18-2024 MZ      JAZZ-68428		Removed HistoryItemGUID parameter
	*************************************************************/

	-- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode],
		[TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID])
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		cw.AccountID,
		acc.AccountCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		m.FiscalMonthID,
		m.FiscalMonthCode,
		SUM(Value) AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM [fp].[Staffing] staff (READUNCOMMITTED)
		CROSS APPLY (
		VALUES
			( 1, 51, ProjectionAdjustedHours01), 
			( 2, 51, ProjectionAdjustedHours02),
			( 3, 51, ProjectionAdjustedHours03),
			( 4, 51, ProjectionAdjustedHours04), 
			( 5, 51, ProjectionAdjustedHours05), 
			( 6, 51, ProjectionAdjustedHours06),
			( 7, 51, ProjectionAdjustedHours07), 
			( 8, 51, ProjectionAdjustedHours08), 
			( 9, 51, ProjectionAdjustedHours09), 
			( 10, 51, ProjectionAdjustedHours10),
			( 11, 51, ProjectionAdjustedHours11), 
			( 12, 51, ProjectionAdjustedHours12)

	) AS CrossApplied (FiscalMonth, UnitTypeID, Value)
			LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID
			LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth 
			INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID
			INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID
			INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID
			INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID
			INNER JOIN (SELECT JobCodeID, PayCodeGroupID, UnitTypeID, AccountID FROM [clientob].[FactPayrollToAccountCrosswalk] p
					WHERE JobCodeID <> 0 OR (JobCodeID = 0 AND NOT EXISTS (
											SELECT 1
											FROM [clientob].[FactPayrollToAccountCrosswalk]
											WHERE AccountID = p.AccountID AND PayCodeGroupID = p.PayCodeGroupID 
											AND JobCodeID <> 0))
					) cw ON
				(CASE WHEN cw.JobCodeID <> 0 THEN cw.JobCodeID ELSE 1 END) = (CASE WHEN cw.JobCodeID <> 0 THEN jc.JobCodeID ELSE 1 END)
			AND cw.PayCodeGroupID = PCG.PayCodeGroupID
			AND UT.UnitTypeID = cw.UnitTypeID
			INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = cw.AccountID
			WHERE staff.BudgetConfigID = @BudgetConfigID
			AND Value <> 0
			AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded)
   	GROUP BY
		d.DepartmentID,
		d.DepartmentCode,
		cw.AccountID,
		acc.AccountCode,
		bc.FiscalYearID,
		bc.FiscalYearID,
		m.FiscalMonthID,
		m.FiscalMonthCode
END
GO


---------------------------------------------

-- fp.procStampOffBackup
CREATE   PROCEDURE [fp].[procStampOffBackup]
	@IsDebug BIT = 0 
AS
BEGIN

/**************************************************************
** Change History
** CID	Date		Author	WI				Description
** 1	2024-02-20	AO		JAZZ-67099		Initial
** 2	2024-03-07	AO		JAZZ-68698		Drop and create tables before each submission
** 3	2024-03-21	MZ		JAZZ-69490		Added [int].[FactStaffingByPayPeriod]
** 4	2024-03-21	AO		JAZZ-73139		Added compression
** 4	2024-03-21	AO		JAZZ-73869		Added [int].[FactStatisticsbyPayPeriod]
** 5	2024-08-29	NH		JAZZ-76159		Updated JobCodeID type
*************************************************************/

	IF OBJECT_ID('tempdb..#tableNamesToDelete') IS NOT NULL DROP TABLE #tableNamesToDelete; 
	CREATE TABLE #tableNamesToDelete (TableName NVARCHAR(255));

	-- Insert previous backup table names into the temporary table (date is dynamic)
	INSERT INTO #tableNamesToDelete (TableName)
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactServiceLine_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactCDM_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStatistic_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactGL_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStaffing_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactProvider_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactImportProvider_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStaffingByPayPeriod_System_%'
	UNION
	SELECT TABLE_NAME
	FROM INFORMATION_SCHEMA.TABLES
	WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStatisticsByPayPeriod_System_%';

	-- Delete previous backup tables
	DECLARE @sqlDropTableStatement NVARCHAR(MAX);
	SET @sqlDropTableStatement = '';

	SELECT @sqlDropTableStatement = @sqlDropTableStatement + 'EXEC [dbo].[procSysDropTable] @schema = ''bak'', @table = ''' + TableName + ''';' 
	FROM #tableNamesToDelete;

	-- Execute dynamic-query
	EXEC (@sqlDropTableStatement);

	DECLARE @datePostfix NVARCHAR(8) = REPLACE(CONVERT(Date, GETDATE()),'-','');

	IF (@IsDebug = 1)
	BEGIN
		SET @datePostfix = 'test'
	END 

	DECLARE @bakTableName NVARCHAR(255) = N'[bak].[intFactServiceLine_System_' + @datePostfix + ']';
	DECLARE @sqlCreateTable NVARCHAR(MAX);

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint] NOT NULL DEFAULT 0,
			[TimeClassID] [tinyint] NOT NULL  DEFAULT '''',
			[TimeClassCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalYearCode] [nvarchar](100) NOT NULL DEFAULT '''', 
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[FiscalMonthCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[EntityID] [int] NOT NULL DEFAULT 0,
			[EntityCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[PatientClassID] [int] NOT NULL DEFAULT 0,
			[PatientClassCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[ServiceLineID] [int] NOT NULL DEFAULT 0,
			[ServiceLine] [nvarchar](100) NOT NULL DEFAULT '''',
			[AgeCohortID] [int] NOT NULL DEFAULT 0,
			[AgeCohort] [nvarchar](100) NOT NULL DEFAULT '''',
			[MedicalSurgicalID] [int] NOT NULL DEFAULT 0, 
			[MedSurg] [nvarchar](100) NOT NULL DEFAULT '''',
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[OBForecastDetailID] [int] NOT NULL DEFAULT 0,
			[ForecastDetail] [nvarchar](100) NOT NULL DEFAULT '''',
			[PayorGroupID] [int] NOT NULL DEFAULT 0,
			[PayorID] [int] NOT NULL DEFAULT 0,
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NOT NULL DEFAULT 0,
			[PayorGroupCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[PayorCode] [nvarchar](100) NOT NULL DEFAULT ''''
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			TimeClassID,
			TimeClassCode,
			FiscalYearID,
			FiscalYearCode,
			FiscalMonthID,
			FiscalMonthCode,
			EntityID,
			EntityCode,
			PatientClassID,
			PatientClassCode,
			ServiceLineID,
			ServiceLine,
			AgeCohortID,
			AgeCohort,
			MedicalSurgicalID,
			MedSurg,
			DepartmentID,
			DepartmentCode,
			OBForecastDetailID,
			ForecastDetail,
			PayorGroupID,
			PayorID,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID,
			PayorGroupCode,
			PayorCode) 
		SELECT 		
			RowID,
			TimeClassID,
			TimeClassCode,
			FiscalYearID,
			FiscalYearCode,
			FiscalMonthID,
			FiscalMonthCode,
			EntityID,
			EntityCode,
			PatientClassID,
			PatientClassCode,
			ServiceLineID,
			ServiceLine,
			AgeCohortID,
			AgeCohort,
			MedicalSurgicalID,
			MedSurg,
			DepartmentID,
			DepartmentCode,
			OBForecastDetailID,
			ForecastDetail,
			PayorGroupID,
			PayorID,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID,
			PayorGroupCode,
			PayorCode
		FROM [int].[FactServiceLine];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';
	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactCDM_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint]  NOT NULL DEFAULT 0,
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[TimeClassCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalYearCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[FiscalMonthCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[PatientClassID] [int] NOT NULL DEFAULT 0,
			[PatientClassCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[ChargeCodeID] [int] NOT NULL DEFAULT 0,
			[ChargeCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[ServiceLineID] [int] NOT NULL DEFAULT 0,
			[ServiceLine] [nvarchar](100) NOT NULL DEFAULT '''',
			[MedicalSurgicalID] [int] NOT NULL DEFAULT 0,
			[MedSurg] [nvarchar](100) NOT NULL DEFAULT '''',
			[AgeCohortID] [int] NOT NULL DEFAULT 0,
			[AgeCohort] [nvarchar](100) NOT NULL DEFAULT '''',
			[UnitTypeID] [tinyint] NOT NULL DEFAULT 0,
			[UnitType] [nvarchar](100) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NOT NULL DEFAULT 0
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			TimeClassID,
			TimeClassCode,
			FiscalYearID,
			FiscalYearCode,
			FiscalMonthID,
			FiscalMonthCode,
			DepartmentID,
			DepartmentCode,
			PatientClassID,
			PatientClassCode,
			ChargeCodeID,
			ChargeCode,
			ServiceLineID,
			ServiceLine,
			MedicalSurgicalID,
			MedSurg,
			AgeCohortID,
			AgeCohort,
			UnitTypeID,
			UnitType,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID)
		SELECT 
			RowID,
			TimeClassID,
			TimeClassCode,
			FiscalYearID,
			FiscalYearCode,
			FiscalMonthID,
			FiscalMonthCode,
			DepartmentID,
			DepartmentCode,
			PatientClassID,
			PatientClassCode,
			ChargeCodeID,
			ChargeCode,
			ServiceLineID,
			ServiceLine,
			MedicalSurgicalID,
			MedSurg,
			AgeCohortID,
			AgeCohort,
			UnitTypeID,
			UnitType,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID
		FROM [int].[FactCDM];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';
	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactStatistic_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint] NOT NULL DEFAULT 0,
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [varchar](100) NOT NULL DEFAULT '''',
			[AccountID] [int] NOT NULL DEFAULT 0,
			[AccountCode] [varchar](50) NOT NULL DEFAULT '''',
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''',
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[TimeClassCode] [varchar](20) NOT NULL DEFAULT '''',
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[FiscalMonthCode] [varchar](20) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NULL DEFAULT 0 
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			DepartmentID,
			DepartmentCode,
			AccountID,
			AccountCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			FiscalMonthID,
			FiscalMonthCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID)
		SELECT
			RowID,
			DepartmentID,
			DepartmentCode,
			AccountID,
			AccountCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			FiscalMonthID,
			FiscalMonthCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID
		FROM [int].[FactStatistic];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';
	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactGL_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint] NOT NULL DEFAULT 0,
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [varchar](100) NOT NULL DEFAULT '''',
			[AccountID] [int] NOT NULL DEFAULT 0,
			[AccountCode] [varchar](50) NOT NULL DEFAULT '''',
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''',
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[TimeClassCode] [varchar](20) NOT NULL DEFAULT '''',
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[FiscalMonthCode] [varchar](20) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NULL DEFAULT 0
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			DepartmentID,
			DepartmentCode,
			AccountID,
			AccountCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			FiscalMonthID,
			FiscalMonthCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID)
		SELECT 
			RowID,
			DepartmentID,
			DepartmentCode,
			AccountID,
			AccountCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			FiscalMonthID,
			FiscalMonthCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID
		FROM [int].[FactGL];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';
	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactStaffing_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint] NOT NULL DEFAULT 0,
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [varchar](100) NOT NULL DEFAULT '''',
			[JobCodeID] [int] NOT NULL DEFAULT 0,
			[JobCode] [varchar](50) NOT NULL DEFAULT '''',
			[EmployeeID] [int] NOT NULL DEFAULT 0,
			[Employeecode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[PayCodeID] [smallint] NOT NULL DEFAULT 0,
			[PayCode] [varchar](50) NOT NULL DEFAULT '''',
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''',
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[TimeClassCode] [varchar](20) NOT NULL DEFAULT '''',
			[UnitTypeID] [tinyint] NOT NULL DEFAULT 0,
			[UnitType] [varchar](20) NOT NULL DEFAULT '''',
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[FiscalMonthCode] [varchar](20) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NULL DEFAULT 0,
			[GlPostDateID] [int] NOT NULL DEFAULT 0,
			[GlPostDateTime] [datetime] NOT NULL DEFAULT 0
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			DepartmentID,
			DepartmentCode,
			JobCodeID,
			JobCode,
			EmployeeID,
			Employeecode,
			PayCodeID,
			PayCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			UnitTypeID,
			UnitType,
			FiscalMonthID,
			FiscalMonthCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID,
			GlPostDateID,
			GlPostDateTime)
		SELECT 
			RowID,
			DepartmentID,
			DepartmentCode,
			JobCodeID,
			JobCode,
			EmployeeID,
			Employeecode,
			PayCodeID,
			PayCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			UnitTypeID,
			UnitType,
			FiscalMonthID,
			FiscalMonthCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID,
			GlPostDateID,
			GlPostDateTime
		FROM [int].[FactStaffing];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';
	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactProvider_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint] NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NOT NULL DEFAULT 0,
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[PhysicianID] [int] NOT NULL DEFAULT 0,
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[ProviderLineItemID] [int] NOT NULL DEFAULT 0,
			[UnitTypeID] [tinyint] NOT NULL DEFAULT 0,
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[FiscalMonthCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[FiscalYearCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[ProviderCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[TimeClassCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[UnitTypeName] [nvarchar](2000) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID,
			TimeClassID,
			PhysicianID,
			FiscalYearID,
			FiscalMonthID,
			ProviderLineItemID,
			UnitTypeID,
			DepartmentID,
			DepartmentCode,
			FiscalMonthCode,
			FiscalYearCode,
			ProviderCode,
			TimeClassCode,
			UnitTypeName,
			Value)
		SELECT 
			RowID,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID,
			TimeClassID,
			PhysicianID,
			FiscalYearID,
			FiscalMonthID,
			ProviderLineItemID,
			UnitTypeID,
			DepartmentID,
			DepartmentCode,
			FiscalMonthCode,
			FiscalYearCode,
			ProviderCode,
			TimeClassCode,
			UnitTypeName,
			Value
		FROM [int].[FactProvider];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';
	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactImportProvider_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint] NOT NULL DEFAULT 0,
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[ProviderID] [int] NOT NULL DEFAULT 0,
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[OBForecastDetailID] [int] NOT NULL DEFAULT 0,
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[AccountRollup] [nvarchar](2000) NOT NULL DEFAULT '''',
			[DepartmentCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[FiscalMonthCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[FiscalYearCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[ProviderCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[TimeClassCode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NOT NULL DEFAULT 0
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			DepartmentID,
			ProviderID,
			FiscalMonthID,
			FiscalYearID,
			OBForecastDetailID,
			TimeClassID,
			AccountRollup,
			DepartmentCode,
			FiscalMonthCode,
			FiscalYearCode,
			ProviderCode,
			TimeClassCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID)
		SELECT 
			RowID,
			DepartmentID,
			ProviderID,
			FiscalMonthID,
			FiscalYearID,
			OBForecastDetailID,
			TimeClassID,
			AccountRollup,
			DepartmentCode,
			FiscalMonthCode,
			FiscalYearCode,
			ProviderCode,
			TimeClassCode,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID
		FROM [int].[FactImportProvider];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';

	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactStaffingByPayPeriod_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [bigint] NOT NULL DEFAULT 0,
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [varchar](100) NOT NULL DEFAULT '''',
			[JobCodeID] [int] NOT NULL DEFAULT 0,
			[JobCode] [varchar](50) NOT NULL DEFAULT '''',
			[PayCodeID] [smallint] NOT NULL DEFAULT 0,
			[PayCode] [varchar](50) NOT NULL DEFAULT '''',
			[PayPeriodID] [smallint] NOT NULL DEFAULT 0,
			[PayPeriodCode] [varchar](50) NOT NULL DEFAULT '''',
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''',
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[TimeClassCode] [varchar](20) NOT NULL DEFAULT '''',
			[UnitTypeID] [tinyint] NOT NULL DEFAULT 0,
			[UnitType] [varchar](20) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT (''00000000-0000-0000-0000-000000000000''),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[EmployeeID] [int] NOT NULL DEFAULT 0,
			[Employeecode] [nvarchar](2000) NOT NULL DEFAULT '''',
			[TransactionID] [int] NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[GlPostDateID] [int] NOT NULL DEFAULT 0,
			[GlPostDateTime] [datetime] NOT NULL DEFAULT (getdate())
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			DepartmentID,
			DepartmentCode,
			JobCodeID,
			JobCode,
			PayCodeID,
			PayCode,
			PayPeriodID,
			PayPeriodCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			UnitTypeID,
			UnitType,
			Value,
			HistoryItemGUID,
			Version,
			EmployeeID,
			Employeecode,
			TransactionID,
			IsDeleted,
			GlPostDateID,
			GlPostDateTime)
		SELECT 
			RowID,
			DepartmentID,
			DepartmentCode,
			JobCodeID,
			JobCode,
			PayCodeID,
			PayCode,
			PayPeriodID,
			PayPeriodCode,
			FiscalYearID,
			FiscalYearCode,
			TimeClassID,
			TimeClassCode,
			UnitTypeID,
			UnitType,
			Value,
			HistoryItemGUID,
			Version,
			EmployeeID,
			Employeecode,
			TransactionID,
			IsDeleted,
			GlPostDateID,
			GlPostDateTime
		FROM [int].[FactStaffingByPayPeriod];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';

	EXEC (@sqlCreateTable);

	SET @bakTableName = N'[bak].[intFactStatisticsByPayPeriod_System_' + @datePostfix + ']';

	SET @sqlCreateTable = '
		CREATE TABLE ' + @bakTableName + '(
			[RowID] [int] NOT NULL DEFAULT 0,
			[TimeClassID] [tinyint] NOT NULL DEFAULT 0,
			[TimeClassCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[FiscalYearID] [smallint] NOT NULL DEFAULT 0,
			[FiscalYearCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[PayPeriodID] [smallint] NOT NULL DEFAULT 0,
			[PayPeriodCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[FiscalMonthID] [tinyint] NOT NULL DEFAULT 0,
			[EntityID] [int] NOT NULL DEFAULT 0,
			[EntityDescription] [nvarchar](200) NOT NULL DEFAULT '''',
			[DepartmentID] [int] NOT NULL DEFAULT 0,
			[DepartmentCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[DepartmentDescription] [nvarchar](200) NOT NULL,
			[AccountID] [int] NOT NULL DEFAULT 0,
			[AccountCode] [nvarchar](100) NOT NULL DEFAULT '''',
			[AccountDescription] [nvarchar](160) NOT NULL,
			[GLRollup] [nvarchar](100) NOT NULL DEFAULT '''',
			[Value] [decimal](19, 4) NOT NULL DEFAULT 0,
			[IsDeleted] [bit] NOT NULL DEFAULT 0,
			[HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT (''00000000-0000-0000-0000-000000000000''),
			[Version] [varbinary](8) NOT NULL DEFAULT(0x),
			[TransactionID] [int] NOT NULL DEFAULT 0,
		);

		INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) (
			RowID,
			TimeClassID,
			TimeClassCode,
			FiscalYearID,
			FiscalYearCode,
			PayPeriodID,
			PayPeriodCode,
			FiscalMonthID,
			EntityID,
			EntityDescription,
			DepartmentID,
			DepartmentCode,
			DepartmentDescription,
			AccountID,
			AccountCode,
			AccountDescription,
			GLRollup,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID)
		SELECT 
			RowID,
			TimeClassID,
			TimeClassCode,
			FiscalYearID,
			FiscalYearCode,
			PayPeriodID,
			PayPeriodCode,
			FiscalMonthID,
			EntityID,
			EntityDescription,
			DepartmentID,
			DepartmentCode,
			DepartmentDescription,
			AccountID,
			AccountCode,
			AccountDescription,
			GLRollup,
			Value,
			IsDeleted,
			HistoryItemGUID,
			Version,
			TransactionID
		FROM [int].[FactStatisticsbyPayPeriod];

		ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE)
	';

	EXEC (@sqlCreateTable);


END
GO


---------------------------------------------

-- fp.procStatisticAdjustment_SEL_LIST
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2020-06-03  LR  	 JAZZ-134		Now including deleted items to be displayed in the activity pane
 ** 2    2020-07-01  OP  	 JAZZ-635		Added AP Entity Config roles support
 ** 3 	 2020-08-20  OP  	 JAZZ-4123		Fixed import comment
 ** 4    2021-04-23  NT		 JAZZ-18228		Renamed proc (originally StatisticAdjustment_SEL_LIST) and added SubsectionID parameter and related filter
 ** 5	 2021-12-07  MZ		 JAZZ-27414		Added Add provider adjustment
 ** 6	 2022-09-02	 AO		 JAZZ-42931		Fixed search by Adjustment Type
 ** 7	 2023-01-06	 NT		 JAZZ-45457		Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card
 ** 8	 2023-01-04  MZ		 JAZZ-47034		Selected BudgetPhaseID from fp.StatisticsAdjustment instead of casting based on AdjustmentType
 ** 9    2024-02-22  MY      JAZZ-67143		Filters acting unexpectedly post-adjustment - Issue #2
 *************************************************************/
CREATE   PROCEDURE [fp].[procStatisticAdjustment_SEL_LIST]
	@budgetGUID UNIQUEIDENTIFIER,
	@start INT,
	@end INT,
	@search VARCHAR(MAX),
	@filter VARCHAR(MAX),
	@userGUID UNIQUEIDENTIFIER,
	@isDataSecured BIT,
	@dateTimeFormat VARCHAR(30),
	@userTimeZone VARCHAR(50),
	@SubsectionID int
AS 

BEGIN

	CREATE TABLE #departmentsSecurity (
		DepartmentID INT NULL,
		EntityID INT NULL
	)	

	CREATE TABLE #securedAdjustments (
		AdjustmentGUID UNIQUEIDENTIFIER
	)

	DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]()
	DECLARE @pageSize INT = @end - @start;

	SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%'))
	SET @filter = LOWER(NULLIF(@filter, ''))

	SELECT		AdjustmentGUID
				,GroupingHierarchyJSON					
				,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
				,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID
				,AdjustmentType
				,GroupingGUID
	INTO	#adjustments
	FROM	fp.StatisticsAdjustment AS slea WITH (NOLOCK)	
	WHERE	slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14, 15) -- Supported Adjustment types for Statistic Adjustments
		AND slea.BudgetConfigGUID = @budgetGUID
		AND slea.SubsectionID = @SubsectionID

	IF @isDataSecured = 1
	BEGIN
		INSERT INTO #departmentsSecurity
		EXEC fp.DepartmentsSecurity_SEL 
			@userGUID = @userGUID,
			@pageName = 'Statistics'

		CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID)

		SELECT	AdjustmentGUID
				,ahd.ID AS DepartmentID
		INTO	#adjustmentGroupingHierarchyDepartments
		FROM (
				SELECT	adj.AdjustmentGUID
						,adj.GroupingHierarchyJSON
				FROM	#adjustments AS adj
				WHERE	adj.EntityID IS NULL
						AND adj.DepartmentID IS NULL) AS slea
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd
		GROUP BY AdjustmentGUID
				,ahd.ID

		SELECT	adj.AdjustmentGUID,
				ahe.ID AS EntityID
		INTO	#adjustmentGroupingHierarchyEntities
		FROM	#adjustments AS adj
				JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID
																		AND adhd.DepartmentID IS NULL
				OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe
		GROUP BY adj.AdjustmentGUID	
				,ahe.ID
		
		INSERT INTO	#securedAdjustments
		SELECT	res.AdjustmentGUID
		FROM	(
			SELECT	slea.AdjustmentGUID
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID
			GROUP BY slea.AdjustmentGUID 

			UNION ALL

			SELECT	slea.AdjustmentGUID		
			FROM	#adjustments AS slea
					JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID
			WHERE	slea.DepartmentID IS NULL
			GROUP BY slea.AdjustmentGUID

			UNION ALL

			SELECT	aghd.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyDepartments AS aghd
					JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID
			WHERE	dshd.DepartmentID IS NOT NULL
			GROUP BY aghd.AdjustmentGUID

			UNION ALL

			SELECT	aghe.AdjustmentGUID		
			FROM	#adjustmentGroupingHierarchyEntities AS aghe
					JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID
			GROUP BY aghe.AdjustmentGUID

			UNION ALL

			SELECT	adj.AdjustmentGUID
			FROM	#adjustments AS adj
					JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID
					JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID
			WHERE	adj.DepartmentID IS NULL
					AND adj.EntityID IS NULL
					AND aghd.DepartmentID IS NULL
					AND aghe.EntityID IS NULL
					AND adj.AdjustmentType <> 15 -- Add provider adjustment, that has no grouping hierarchy, but has security
			GROUP BY adj.AdjustmentGUID

			UNION ALL
			
			SELECT adj.AdjustmentGUID
			FROM #adjustments AS adj
				JOIN fp.StatisticAddProviderAdjustment AS sleapa ON adj.AdjustmentGUID = sleapa.AdjustmentGUID
				JOIN #departmentsSecurity AS ds ON ds.DepartmentID = sleapa.DepartmentID
			GROUP BY adj.AdjustmentGUID
		) AS res

		-- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2)
		-- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the 
		-- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine.
		-- Essentially what we are doing here is using the child adjustments to find if they fall in security.
		-- In the event we have a child, populate the parent adjustment in the list.
		-- Find all the GroupingGuid's for any child adjustments that fall into security.
		
		SELECT DISTINCT adj.GroupingGUID
		INTO #groupingAdjustments
		FROM #securedAdjustments secured
			INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID
		WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments.

		-- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment.
		INSERT INTO #securedAdjustments
		SELECT adj.AdjustmentGUID
		FROM #adjustments adj
			INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID
			LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID
		WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments
			AND secured.AdjustmentGUID IS NULL

	END
	ELSE 
		BEGIN

			INSERT INTO #securedAdjustments
			SELECT	AdjustmentGUID
			FROM	#adjustments

		END
	
	CREATE CLUSTERED	INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID)
	
	SELECT	iadj.AdjustmentGuid, 
			iadj.UnitTypeID
	INTO	#importAdjustments
	FROM	fp.StatisticsAdjustmentImport AS iadj WITH (NOLOCK)
			JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID
			LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID
	WHERE	ds.DepartmentID IS NOT NULL
			OR @isDataSecured = 0
	GROUP BY iadj.AdjustmentGuid,
			iadj.UnitTypeID

	CREATE CLUSTERED	INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID)

	SELECT res.TotalRowsCount
		,res.AdjustmentGUID
		,res.BudgetConfigGUID
		,res.AdjustmentType
		,res.[Value]
		,res.AdjustmentFilterJSON
		,res.GroupingHierarchyJSON
		,res.AdjustedProperty
		,res.Comment
		,res.AuthorGUID
		,res.AuthorFullName
		,res.LastModifiedDateUtc
		,res.DateCreatedUtc
		,res.GroupingGUID
		,res.TimeClassID
		,res.BudgetPhaseID
		,res.ClassificationGroupID
		,res.ClassificationCategoryID
		,res.JobCode
		,res.JobCodeCount
		,res.DepartmentCode
		,res.DepartmentCount
		,res.UnitTypeID
		,res.ImportUnitTypeIDs
		,res.AddProviderFirstName
		,res.AddProviderLastName
		,res.AddProviderType	
		,res.IsRecordDeleted
		,res.IsErrored
	FROM (
		SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount,
			   *
		FROM (
				SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
				  , slea.AdjustmentGUID
				  ,slea.BudgetConfigGUID
				  ,slea.AdjustmentType
				  ,slea.[Value]
				  ,slea.AdjustmentFilterJSON
				  ,slea.GroupingHierarchyJSON
				  ,slea.AdjustedProperty
				  ,ISNULL(ag.Description, slea.Comment) AS Comment
				  ,slea.AuthorGUID
				  ,slea.AuthorFullName
				  ,slea.LastModifiedDateUtc
				  ,slea.DateCreatedUtc
				  ,slea.GroupingGUID
				  ,slea.TimeClassID
				  ,slea.BudgetPhaseID
				  ,slea.ClassificationGroupID
				  ,slea.ClassificationCategoryID
				  ,slea.UnitTypeID
				  ,NULL AS JobCode
				  ,NULL AS JobCodeCount
				  ,NULL AS DepartmentCode
				  ,NULL AS DepartmentCount
				  ,sai.ImportUnitTypeIDs
				  ,NULL AS AddProviderFirstName
				  ,NULL AS AddProviderLastName
				  ,NULL AS AddProviderType	
				  ,slea.IsRecordDeleted
				  ,slea.IsErrored
			FROM	(	SELECT
							adj.*
							,CAST(140 AS TINYINT) AS UnitTypeID
							,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID
							,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID
						FROM	fp.StatisticsAdjustment AS adj WITH (NOLOCK)
								JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = adj.AdjustmentGUID
						WHERE adj.SubsectionID = @SubsectionID								
						) AS slea										
					LEFT JOIN (
						SELECT	p.AdjustmentGUID, 
								ImportUnitTypeIDs =
									TRIM(STUFF(
										(SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5))
										FROM	#importAdjustments AS p2
										WHERE	p2.AdjustmentGUID = p.AdjustmentGUID
										GROUP BY p2.AdjustmentGUID, 
												p2.UnitTypeID
										FOR XML PATH(N''))
									, 1, 0, N''))
						FROM	#importAdjustments AS p
						GROUP BY p.AdjustmentGUID
					) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID
					LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID
					LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID
					LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID
																	AND slea.ClassificationCategoryID = acc.CategoryID
					LEFT JOIN (
						SELECT	nsa.GroupingGUID
						FROM	fp.StatisticsAdjustment as nsa WITH (NOLOCK)
						WHERE	nsa.AdjustmentType IN (12, 13, 14)
							AND nsa.BudgetConfigGUID = @budgetGUID
							AND nsa.SubsectionID = @SubsectionID
						GROUP BY nsa.GroupingGUID
					) AS ra ON ra.GroupingGUID = slea.GroupingGUID 
			WHERE	(slea.AdjustmentType <> 4 
						OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment
					AND slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14) -- Supported Adjustment types for Statistic Adjustments
					AND (ra.GroupingGUID IS NULL
						OR slea.AdjustmentType IN (12, 13, 14))
					AND (@search IS NULL 
						OR (
								LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
								OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\'
								OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR acc.[Name] LIKE @search ESCAPE '\'
								OR acg.[Name] LIKE @search ESCAPE '\'				
								OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1
								OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\'
								OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1
							)
						)
					AND (@filter IS NULL
						OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (
							SELECT	[value]
							FROM	STRING_SPLIT(@filter, ' ' )
							)
						)

			-- Add Provider adjustments
			UNION ALL			

			SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber
				  , slea.AdjustmentGUID
				  ,slea.BudgetConfigGUID
				  ,slea.AdjustmentType
				  ,slea.[Value]
				  ,slea.AdjustmentFilterJSON
				  ,slea.GroupingHierarchyJSON
				  ,slea.AdjustedProperty
				  ,aps.Comment
				  ,slea.AuthorGUID
				  ,slea.AuthorFullName
				  ,slea.LastModifiedDateUtc
				  ,slea.DateCreatedUtc
				  ,slea.GroupingGUID
				  ,slea.TimeClassID
				  ,2 AS BudgetPhaseID
				  ,aps.ClassificationGroupID
				  ,aps.ClassificationCategoryID
				  ,NULL AS UnitTypeID
				  ,NULL AS JobCode
				  ,NULL AS JobCodeCount
				  ,NULL AS DepartmentCode
				  ,NULL AS DepartmentCount
				  ,NULL AS ImportUnitTypeIDs
				  ,de.NameFirst AS AddProviderFirstName
				  ,de.NameLast AS AddProviderLastName
				  ,aps.EmployeeType AS AddProviderType	
				  ,slea.IsRecordDeleted
				  ,slea.IsErrored
			FROM	fp.StatisticsAdjustment AS slea WITH (NOLOCK)			
					JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID
					JOIN fp.StatisticAddProviderSummary AS aps ON aps.DriverAdjustmentGUID = slea.AdjustmentGUID
					JOIN fw.DimEmployee AS de ON de.EmployeeID = aps.EmployeeID
					LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = aps.ClassificationGroupID
					LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acc.GroupID = acg.GroupID
																	AND aps.ClassificationCategoryID = acc.CategoryID
			WHERE	slea.AdjustmentType = 15 -- add provider adjustments
					AND (@search IS NULL 
						OR (
								LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\'
								OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\'
								OR LOWER(aps.Comment) LIKE @search ESCAPE '\'
								OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1
								OR acc.[Name] LIKE @search ESCAPE '\'
								OR acg.[Name] LIKE @search ESCAPE '\'
								OR de.NameFull LIKE @search ESCAPE '\'
							)
						)
					AND (@filter IS NULL
						OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, 2) IN (
							SELECT	[value]
							FROM	STRING_SPLIT(@filter, ' ' )
							)
						)
			) AS res_inner
		WHERE res_inner.RowNumber = 1 ) AS res
	ORDER BY res.DateCreatedUtc DESC
	OFFSET @start ROWS
	FETCH NEXT @pageSize ROWS ONLY;
END
GO


---------------------------------------------

-- fp.procStatisticBudgetStampOff
CREATE   PROCEDURE [fp].[procStatisticBudgetStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	1-31-2023  MY      JAZZ-48962		Initial Creation
	** 2	01-03-2024 MZ      JAZZ-65385		Added Target TimeClass
	** 3	03-18-2024 MZ	   JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	*************************************************************/

	-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Budgeted Time Class
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) FROM [int].[FactStatistic] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
   
	INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode],
		[TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID])
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		acc.AccountID,
		acc.AccountCode,
		bc.FiscalYearID,
		bc.FiscalYearID AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
		FROM (
			SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.PatientClassID, cv.PayorID, cv.FinancialReportingID, cv.UnitTypeID, 
				bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, 
				bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.FactStatistics cv
				INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID
			WHERE bdgt.BudgetPhaseID = 3
				AND cv.BudgetConfigID = @BudgetConfigID
		) cv
		UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
	WHERE 1=1
		and BudgetedData.Value <> 0
		and bc.BudgetConfigID = @BudgetConfigID
END
GO


---------------------------------------------

-- fp.procStatisticProjectionStampOff
CREATE     PROCEDURE [fp].[procStatisticProjectionStampOff] 
	@BudgetConfigID INT,
	@TargetTimeClassID TINYINT,
	@IsMonthsLoadedIncluded BIT
AS
BEGIN
	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date       Author  WI				Description
	** 1	11-10-2023 AO      JAZZ-62128		Initial Creation
	** 2	01-04-2024 MZ      JAZZ-65385		Added Target TimeClass and IsMonthsLoadedIncluded
	** 3	01-24-2024 MZ      JAZZ-64527		Fix Months Loaded
	** 4	03-18-2024 MZ	      JAZZ-68428		Deleting by Chunks & removed HistoryItemGUID parameter
	** 5	04-03-2024 MZ	JAZZ-70053		Fix Month Loaded excluding logic
	*************************************************************/

	-- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables

	DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID )
	DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID)
	DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID)

	DECLARE @HistoryItemGUID UNIQUEIDENTIFIER
	EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT
	PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36))
	PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID)

	-- Clear out existing records for the selected FiscalYear and Projected Time Class
	-- and all months if months loaded included otherwise only months NOT loaded will be cleared
	DECLARE @ChunkCount INT
	
	SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk';
	IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END

	DECLARE @r INT;
	SET @r = 1;	 

	WHILE @r > 0
	BEGIN
		BEGIN TRANSACTION;			  
		DELETE TOP (@ChunkCount) s FROM [int].[FactStatistic] s
			INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = s.FiscalMonthID
		WHERE s.FiscalYearID = @FiscalYear
			AND s.TimeClassID = @TargetTimeClassID
			AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded)
		SET @r = @@ROWCOUNT;	 
		COMMIT TRANSACTION;
	END
   
	INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode],
		[TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID])
	SELECT
		d.DepartmentID,
		d.DepartmentCode,
		acc.AccountID,
		acc.AccountCode,
		@FiscalYear,
		@FiscalYear AS FiscalYearCode,
		@TargetTimeClassID AS TimeClassID,
		@TimeClassCode AS TimeClassCode,
		fm.FiscalMonthID,
		fm.FiscalMonthCode,
		Value AS Value,
		'0' AS IsDeleted,
		@HistoryItemGUID AS HistoryItemGUID
	FROM (
		SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType
		FROM (
			SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.PatientClassID, cv.PayorID, cv.FinancialReportingID, cv.UnitTypeID, 
				bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, 
				bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12
			FROM fp.FactStatistics cv
				INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID
			WHERE bdgt.BudgetPhaseID = 3
				AND cv.BudgetConfigID = @BudgetConfigID
		) cv
		UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f
		LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')
	) BudgetedData
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID
		INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID
		INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID
		INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID
		INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID
	WHERE 1=1
		AND BudgetedData.Value <> 0
		AND bc.BudgetConfigID = @BudgetConfigID
		AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded)
END
GO


---------------------------------------------

-- fp.procStatisticsAddProviderDependentRecordsSelect
CREATE    PROCEDURE [fp].[procStatisticsAddProviderDependentRecordsSelect]
	@BudgetConfigID INT,
    @SelectedProviders [dbo].[SqlInt32ListTableType] READONLY,
	@DepartmentIds [dbo].[SqlInt32ListTableType] READONLY,
	@AccountIds [dbo].[SqlInt32ListTableType] READONLY
 AS
 BEGIN
   
	SELECT	[value] AS ProviderID
	INTO	#BenchProviders
	FROM	@SelectedProviders

	SELECT	[value] AS DepartmentID
	INTO	#DepartmentSecurity
	FROM	@DepartmentIds

	SELECT	[value] AS AccountID
	INTO	#AccountIds
	FROM	@AccountIds

	SELECT	fs.AccountID,
			fs.FinancialReportingID,
			fs.PayorID,
			fs.PatientClassID,
			fs.ProviderLineItemID
	FROM	fp.FactStatistics fs
			JOIN #DepartmentSecurity ds ON ds.DepartmentID = fs.DepartmentID
			JOIN #BenchProviders bp ON bp.ProviderID = fs.ProviderID
			JOIN #AccountIds acc ON acc.AccountID = fs.AccountID
	WHERE	SubsectionID = 2 -- Dependent
		AND BudgetConfigID = @BudgetConfigID
		AND UnitTypeID = 140 -- Volume
	GROUP BY fs.AccountID,
			fs.FinancialReportingID,
			fs.PayorID,
			fs.PatientClassID,
			fs.ProviderLineItemID
END
GO


---------------------------------------------

-- fp.procStatisticsApplySpread
CREATE   PROCEDURE [fp].[procStatisticsApplySpread]
  @BudgetConfigID INT,
  @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
WITH RECOMPILE
AS
BEGIN

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date         Author    WI          Description
	** 1    03-06-2023   MZ        JAZZ-3698   Added provider dimensions
	** 2    12-26-2023   NH        JAZZ-59204  Remove Use Provider dimensions for Statistics Spreads
	** 3	2024-01-11	 MY		   JAZZ-XXXXX  Re-remove call to procStatisticsApplySpreadsFlexed
	** 4 	2024-01-22	 MY		   JAZZ-64799  History Viewer does not handle Spread Impact for Monthly Values
	** 5 	2024-01-31	 NH		   JAZZ-64064  Move Provider Planning FF as a setting in Plan Config
	** 6 	2024-05-13	 MY		   JAZZ-66920  Fix Feature Flag Check for History Viewer Check and add WITH RECOMPILE
	*************************************************************/
	
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#spreadsChangeHistory') IS NOT NULL DROP TABLE #spreadsChangeHistory;

	DECLARE @volumeUnitType INT = 140;

	/*** added in scope of JAZZ-3698 ***/
	DECLARE @UseProviderDimensions bit 
	SELECT @UseProviderDimensions = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID;
	
	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	CREATE TABLE #filterTable (StatisticsID INT PRIMARY KEY CLUSTERED);

	CREATE TABLE #spreadsChangeHistory (
		StatisticsID INT,
		OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0),
		NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0),
	);

	IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL)
	BEGIN

		IF(@UseProviderDimensions = 1)
		BEGIN
			INSERT INTO #filterTable (StatisticsID)
			SELECT DISTINCT basis.StatisticsID
			FROM [fp].[FactStatistics] basis
				INNER JOIN #FilterByDepartment SD on SD.DepartmentID = basis.DepartmentID
				INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID
					AND spread.ProviderID = basis.ProviderID AND spread.ProviderLineItemID = basis.ProviderLineItemID
				INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID
			WHERE basis.BudgetConfigID = @BudgetConfigID
				AND basis.UnitTypeID = @volumeUnitType
				AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7
		END
		ELSE BEGIN
			INSERT INTO #filterTable (StatisticsID)
			SELECT DISTINCT basis.StatisticsID
			FROM [fp].[FactStatistics] basis
				INNER JOIN #FilterByDepartment SD on SD.DepartmentID = basis.DepartmentID
				INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID
				INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID
			WHERE basis.BudgetConfigID = @BudgetConfigID
				AND basis.UnitTypeID = @volumeUnitType
				AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7
		END	

	END
	ELSE BEGIN

		IF(@UseProviderDimensions = 1)
		BEGIN
			INSERT INTO #filterTable (StatisticsID)
			SELECT DISTINCT basis.StatisticsID
			FROM [fp].[FactStatistics] basis
				INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID
					AND spread.ProviderID = basis.ProviderID AND spread.ProviderLineItemID = basis.ProviderLineItemID
				INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID
			WHERE basis.BudgetConfigID = @BudgetConfigID
				AND basis.UnitTypeID = @volumeUnitType
				AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7
		END
		ELSE BEGIN
			INSERT INTO #filterTable (StatisticsID)
			SELECT DISTINCT basis.StatisticsID
			FROM [fp].[FactStatistics] basis
				INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID
				INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID
			WHERE basis.BudgetConfigID = @BudgetConfigID
				AND basis.UnitTypeID = @volumeUnitType
				AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7
		END

	END

	IF(@UseProviderDimensions = 1)
	BEGIN

		UPDATE fsb
		SET	 LockType = 6, LockFlag = 1
				, AdjustedValue01 = CAST(AdjustedValueTotal * SpreadPercentage01 AS DECIMAL(19,8))
				, AdjustedValue02 = 
					CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
				, AdjustedValue03 = 
					CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
				, AdjustedValue04 = 
					CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
				, AdjustedValue05 = 
					CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
				, AdjustedValue06 = 
					CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
				, AdjustedValue07 = 
					CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
				, AdjustedValue08 = 
					CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
				, AdjustedValue09 = 
					CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
				, AdjustedValue10 = 
					CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
				, AdjustedValue11 = 
					CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
				, AdjustedValue12 = 
					CASE WHEN SpreadPercentage12 != 0
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
		OUTPUT 
			inserted.StatisticsID, 
			deleted.AdjustedValue01, deleted.AdjustedValue02, deleted.AdjustedValue03, deleted.AdjustedValue04, deleted.AdjustedValue05, deleted.AdjustedValue06,
			deleted.AdjustedValue07, deleted.AdjustedValue08, deleted.AdjustedValue09, deleted.AdjustedValue10, deleted.AdjustedValue11, deleted.AdjustedValue12,
			inserted.AdjustedValue01, inserted.AdjustedValue02, inserted.AdjustedValue03, inserted.AdjustedValue04, inserted.AdjustedValue05, inserted.AdjustedValue06,
			inserted.AdjustedValue07, inserted.AdjustedValue08, inserted.AdjustedValue09, inserted.AdjustedValue10, inserted.AdjustedValue11, inserted.AdjustedValue12
		INTO
			#spreadsChangeHistory (StatisticsID,	
		  						   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
								   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
								   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
								   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) 
		FROM [fp].[viewStatisticsSpreads] statsp
			INNER JOIN [fp].[FactStatistics] fs ON statsp.BudgetConfigID = fs.BudgetConfigID AND statsp.DepartmentID = fs.DepartmentID AND statsp.AccountID = fs.AccountID
				AND statsp.ProviderID = fs.ProviderID AND statsp.ProviderLineItemID = fs.ProviderLineItemID
			INNER JOIN #filterTable tmp on fs.StatisticsID = tmp.StatisticsID
			INNER JOIN [fp].[FactStatisticsBudget] fsb on fs.StatisticsID = fsb.StatisticsID 
		WHERE fsb.BudgetPhaseID = 3 AND statsp.IsInactive = 0 AND fs.SubsectionID = 1

	END
	ELSE BEGIN

		UPDATE fsb
		SET	 LockType = 6, LockFlag = 1
				, AdjustedValue01 = CAST(AdjustedValueTotal * SpreadPercentage01 AS DECIMAL(19,8))
				, AdjustedValue02 = 
					CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage02 AS DECIMAL(19,8)) END
				, AdjustedValue03 = 
					CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage03 AS DECIMAL(19,8)) END
				, AdjustedValue04 = 
					CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage04 AS DECIMAL(19,8)) END
				, AdjustedValue05 = 
					CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage05 AS DECIMAL(19,8)) END
				, AdjustedValue06 = 
					CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage06 AS DECIMAL(19,8)) END
				, AdjustedValue07 = 
					CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage07 AS DECIMAL(19,8)) END
				, AdjustedValue08 = 
					CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage08 AS DECIMAL(19,8)) END
				, AdjustedValue09 = 
					CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage09 AS DECIMAL(19,8)) END
				, AdjustedValue10 = 
					CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage10 AS DECIMAL(19,8)) END
				, AdjustedValue11 = 
					CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage11 AS DECIMAL(19,8)) END
				, AdjustedValue12 = 
					CASE WHEN SpreadPercentage12 != 0
					THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage11) AS DECIMAL(19, 8)))
					ELSE CAST(AdjustedValueTotal * SpreadPercentage12 AS DECIMAL(19,8)) END
		OUTPUT 
			inserted.StatisticsID, 
			deleted.AdjustedValue01, deleted.AdjustedValue02, deleted.AdjustedValue03, deleted.AdjustedValue04, deleted.AdjustedValue05, deleted.AdjustedValue06,
			deleted.AdjustedValue07, deleted.AdjustedValue08, deleted.AdjustedValue09, deleted.AdjustedValue10, deleted.AdjustedValue11, deleted.AdjustedValue12,
			inserted.AdjustedValue01, inserted.AdjustedValue02, inserted.AdjustedValue03, inserted.AdjustedValue04, inserted.AdjustedValue05, inserted.AdjustedValue06,
			inserted.AdjustedValue07, inserted.AdjustedValue08, inserted.AdjustedValue09, inserted.AdjustedValue10, inserted.AdjustedValue11, inserted.AdjustedValue12
		INTO
			#spreadsChangeHistory (StatisticsID,	
		  						   OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
								   OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,
								   NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
								   NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) 
		FROM [fp].[viewStatisticsSpreads] statsp
			INNER JOIN [fp].[FactStatistics] fs ON statsp.BudgetConfigID = fs.BudgetConfigID AND statsp.DepartmentID = fs.DepartmentID AND statsp.AccountID = fs.AccountID
			INNER JOIN #filterTable tmp on fs.StatisticsID = tmp.StatisticsID
			INNER JOIN [fp].[FactStatisticsBudget] fsb on fs.StatisticsID = fsb.StatisticsID 
		WHERE fsb.BudgetPhaseID = 3 AND statsp.IsInactive = 0 AND fs.SubsectionID = 1

	END

	-- Populate Change History
	IF EXISTS(SELECT 1 
			  FROM fp.BudgetConfigSetting setting
				INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID
			  WHERE def.Name = 'Spreads Change History Logic Is Enabled'
			  	AND setting.Value = 1
				AND setting.BudgetConfigID = @BudgetConfigID)
	BEGIN
		
		INSERT INTO fp.StatisticsSpreadsChangeHistory (StatisticsID, SubsectionID, BudgetConfigID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06,
						OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12,	NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06,
						NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12)
		SELECT StatisticsID, 1, @BudgetConfigID,
			ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0),
			ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0),
			ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0),
			ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0)
		FROM #spreadsChangeHistory
		WHERE 1 = 1
			AND (
				   OldValue01 != NewValue01
				OR OldValue02 != NewValue02
				OR OldValue03 != NewValue03
				OR OldValue04 != NewValue04
				OR OldValue05 != NewValue05
				OR OldValue06 != NewValue06
				OR OldValue07 != NewValue07
				OR OldValue08 != NewValue08
				OR OldValue09 != NewValue09
				OR OldValue10 != NewValue10
				OR OldValue11 != NewValue11
				OR OldValue12 != NewValue12
			)
	END
	
END
GO


---------------------------------------------

-- fp.procStatsCopyNewItems
CREATE PROCEDURE [fp].[procStatsCopyNewItems]
	@SourceBudgetConfigID INT,
	@SourceEntityGroupConfigID INT,
	@BudgetConfigID INT,
	@EntityGroupConfigID INT
AS 
BEGIN
/**************************************************************
	 ** Change History
	 **************************************************************
	 ** CID  Date        Author  WI   		Description
	 ** 1 	 2021-06-28  NT		 JAZZ-21664 Add missing provider dimensions
	 *************************************************************/	
INSERT INTO [fp].[FactStatistics] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, PayorID, PatientClassID, AddDate,
ProviderLineItemID, ProviderID, ProviderSpecialtyID, ProviderTypeID, SubsectionID,
SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
IsNew)
SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, PayorID, PatientClassID, AddDate,
ProviderLineItemID, ProviderID, ProviderSpecialtyID, ProviderTypeID, SubsectionID,
SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12,
SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12,
InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12,
InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12,
IsNew
FROM [fp].[FactStatistics] 
WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1

END
GO


---------------------------------------------

-- fp.procTogglePreviewMode
create proc fp.procTogglePreviewMode
	@isEnabled bit,
	@isDebug bit = 0
as
	update fp.SystemSetting set Value = @isEnabled where Name = 'AP Preview Enabled'

	--set hangfire overrides to direct AP tasks to the lower priority preview queue
	if (@isDebug = 1 or exists(select 1 from dbo.DBSetting where Name = 'SMC_PRIMARY_DATABASE' and Setting = 'smc prod')) begin
		DELETE FROM dbo.HangfireJobQueueOverride where QueueName = 'advanced_planning_preview';

		if (@isEnabled = 1) begin
			;with apTasks as (
				select 'Strata.CS.Jazz.ABB.Adjustments.TrackableImportTaskBase' as TypeName union all
				select 'Strata.CS.Jazz.ABB.TestingTools.Tasks.RandomAdjustmentEngineTask' as TypeName union all
				select 'Strata.CS.Jazz.ABB.Tasks.ABBFlexingReconciliationSamplingTask' as TypeName union all
				select 'Strata.CS.Jazz.ABB.Tasks.APEngineTask' as TypeName union all
				select 'Strata.CS.Jazz.ABB.Tasks.APReportCacheTask' as TypeName union all
				select 'Strata.CS.Jazz.ABB.Tasks.APSamplingTask' as TypeName union all
				select 'Strata.CS.Jazz.ABB.Tasks.APStartBudgetingTask' as TypeName union all
				select 'Strata.CS.Jazz.ABB.Tasks.ArchiveBudgetTask' as TypeName
			)
			INSERT dbo.HangfireJobQueueOverride (TypeName, MethodName, QueueName)
			SELECT TypeName, 'InvokeWithContext' as MethodName, 'advanced_planning_preview' as QueueName
			FROM apTasks;
		end
	end
GO


---------------------------------------------

-- fp.procTransferRosterToStaffing
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1    2017-07-30  IP          B-20351		Staffing to GL - Performance Improvements and roster targeted thing
** 2    2018-08-10  MY          B-20495		Fixes for flexed value not getting reset and locking unrelated PCGs
** 3    2018-08-14  MY          B-20495		Fixed an issue with the filter filtering out when PCG is at a rollup level
** 4    2018-09-25  GF          E-02313		Simplify source dimensionality to only department
** 5    2018-09-25  BK          D-07796		Fix joins to use filtered table so that InitialBudget not cleared
** 6    2019-01-11  MY          B-19995		Updated Projection Logic to only flow to months not loaded
** 7    2019-01-28  MY          D-08049		Fixed Actual YTD calculation to only apply once
** 8    2019-05-07  BK          D-08084		Fixed problem with duplicate new employees when more than one pcg is in RosterBudgetBasisResult
** 9    2022-09-02  MY          JAZZ-18719	Improved Targeting Performance
** 10   2023-11-30  BK          JAZZ-63467	Update for new data structure
*************************************************************/
CREATE proc [fp].[procTransferRosterToStaffing]
	@BudgetConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS
    exec dbo.procSysDropTempTable '#tmpPaddedStaffingData'
    exec dbo.procSysDropTempTable '#tmpRosterRolledUp'
    exec dbo.procSysDropTempTable '#staffingGrouped'
    exec dbo.procSysDropTempTable '#tmpRosterTotalsForExistingEmployees'
    exec dbo.procSysDropTempTable '#tmpExistingEmployees'
    exec dbo.procSysDropTempTable '#tmpNewRosterEmployees'
    exec dbo.procSysDropTempTable '#tmpHoursRatio'
    exec dbo.procSysDropTempTable '#tmpEntity'
	exec dbo.procSysDropTempTable '#Filter'
 
	SELECT DISTINCT DepartmentID 
	INTO #Filter 
	FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) 
 
	IF EXISTS(SELECT 1 FROM #Filter WHERE DepartmentID IS NULL)
	BEGIN
		INSERT INTO #Filter (DepartmentID) 
		SELECT DISTINCT DepartmentID 
		FROM fw.DimDepartment -- We want to use dim department here instead of fp.Staffing because new departments added to roster need to flow over
	END

	-- Set variables
	DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER
	DECLARE @IsFTEHidden TINYINT
 	DECLARE @MonthsLoaded INT
	DECLARE @BudgetYear SMALLINT
	SELECT @BudgetConfigGUID = BudgetConfigGUID, @IsFTEHidden = IsFTEHidden, @BudgetYear = FiscalYearID, @MonthsLoaded = MonthsLoaded FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID        
	
 	-- Used for projection, we only ever want to update the months NOT loaded.
	DECLARE @MonthsNotLoaded INT = 12 - @MonthsLoaded;	
	DECLARE @ProjectedYear INT = @BudgetYear - 1
 
 	-- Gets the working hours to calculate FTEs
	SELECT WorkWeekID, mnth.FiscalYearID, SUM(VALUE) as TotalHours
	INTO #tmpHoursRatio
	FROM [client].[viewFactWorkingHoursPerMonthUnpivoted] mnth WITH (READUNCOMMITTED)
	WHERE FiscalYearID = @BudgetYear
	GROUP BY WorkWeekID, mnth.FiscalYearID;
	
	INSERT INTO #tmpHoursRatio
	SELECT WorkWeekID, mnth.FiscalYearID, SUM(RemainingAnnualHours) as TotalHours	
	FROM [fp].[viewWorkingHoursPerMonthWithBreakdown] mnth WITH (READUNCOMMITTED)
		INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = mnth.FiscalMonthID AND @MonthsLoaded + 1 = fm.SortOrder
	WHERE FiscalYearID = @ProjectedYear
	GROUP BY WorkWeekID, mnth.FiscalYearID;
		
 	-- Get all of the entities
	SELECT EntityID 
	INTO #tmpEntity
	FROM [fp].[EntityGroupConfig] ec 
		INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON ec.BudgetConfigGUID = bc.BudgetConfigGUID 
		INNER JOIN [fp].[EntityGroupConfigMapping] egcm WITH (READUNCOMMITTED) ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID
	WHERE BudgetConfigID = @BudgetConfigID AND ec.IsRosterUsed = 1;
 
 	-- Get the total YTD actual dollars regardless of variability, we'll use these to caclulate the projection dollars (Roster Projection Dollars - Staffing YTD Actual Dollars)
	SELECT
		ph.BudgetConfigID,
		ph.EntityID,
		ph.DepartmentID,
		ph.JobCodeID,
		ph.PayCodeGroupID,
		SUM(hist.ActualYTDDollarsTotal) AS ActualYTDValueTotal
	INTO #staffingGrouped
	FROM [fp].[Staffing] ph WITH (READUNCOMMITTED)
		INNER JOIN [fp].[StaffingHistory] hist WITH (READUNCOMMITTED) ON ph.StaffingID = hist.StaffingID	
		INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON ph.DepartmentID = dept.DepartmentID
		INNER JOIN #tmpEntity ent WITH (READUNCOMMITTED) on dept.EntityID = ent.EntityID
		INNER JOIN #Filter Filter ON ph.DepartmentID = Filter.DepartmentID
	WHERE ph.BudgetConfigID = @BudgetConfigID
	GROUP BY
		ph.BudgetConfigID,
		ph.EntityID,
		ph.DepartmentID,
		ph.JobCodeID,
		ph.PayCodeGroupID
      			
	-- Get the total in the UI, then for projection for non-new employees
	-- Projection Dollars = (Roster Projection Dollars - Staffing YTD Actual Dollars)
	-- We do this so we can take out the Actual YTD in the next step
	SELECT
		  @BudgetConfigID AS BudgetConfigID
		, dept.EntityID
		, rb.DepartmentID
		, rb.JobCodeID
		, rb.PayCodeGroupID
		, SUM(rb.Dollars) AS Dollars
		, SUM(rb.InitialDollars) AS InitialDollars
		, SUM(rb.ProjectedDollars) AS ProjectedDollars
		, SUM(rb.FTEs) AS FTEs
		, SUM(rb.InitialFTEs) AS InitialFTEs
		, SUM(rb.ProjectedFTEs) AS ProjectedFTEs
	INTO
		#tmpRosterTotalsForExistingEmployees
	FROM [fp].[RosterBudgetBasisResult] rb
		INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rb.DepartmentID = dept.DepartmentID
		INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID
		INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID
		LEFT JOIN [fp].[RosterBudgetNewEmployee] emp ON rb.EmployeeID = emp.EmployeeID AND rb.BudgetConfigGUID = emp.BudgetConfigGUID
		LEFT JOIN #staffingGrouped staffing
			ON dept.EntityID = staffing.EntityID 
			AND rb.DepartmentID = staffing.DepartmentID 
			AND rb.JobCodeID = staffing.JobCodeID
			AND rb.PayCodeGroupID = staffing.PayCodeGroupID
	WHERE 1=1
		AND rb.BudgetConfigGUID = @BudgetConfigGUID
		AND emp.EmployeeID IS NULL
	GROUP BY
		  rb.DepartmentID
		, rb.JobCodeID
		, rb.PayCodeGroupID
		, dept.EntityID;
		
	-- Need to do this seperate for when there are multiple employees, we only want to do this math once.
	UPDATE existing
	SET 
		existing.ProjectedDollars = existing.ProjectedDollars - grp.ActualYTDValueTotal
	FROM #tmpRosterTotalsForExistingEmployees existing
		INNER JOIN #staffingGrouped grp ON 
				existing.BudgetConfigID = grp.BudgetConfigID
			AND existing.EntityID = grp.EntityID
			AND existing.DepartmentID = grp.DepartmentID
			AND existing.JobCodeID = grp.JobCodeID
			AND existing.PayCodeGroupID = grp.PayCodeGroupID

	-- Calculate the values for all existing employees,
	SELECT
		  roster.BudgetConfigID
		, roster.EntityID
		, roster.DepartmentID
		, roster.JobCodeID
		, roster.PayCodeGroupID 
		, SUM(roster.Dollars * (wh.Month01/ NULLIF(hr.TotalHours, 0))) as DollarsMonth01
		, SUM(roster.Dollars * (wh.Month02/ NULLIF(hr.TotalHours, 0))) as DollarsMonth02
		, SUM(roster.Dollars * (wh.Month03/ NULLIF(hr.TotalHours, 0))) as DollarsMonth03
		, SUM(roster.Dollars * (wh.Month04/ NULLIF(hr.TotalHours, 0))) as DollarsMonth04
		, SUM(roster.Dollars * (wh.Month05/ NULLIF(hr.TotalHours, 0))) as DollarsMonth05
		, SUM(roster.Dollars * (wh.Month06/ NULLIF(hr.TotalHours, 0))) as DollarsMonth06
		, SUM(roster.Dollars * (wh.Month07/ NULLIF(hr.TotalHours, 0))) as DollarsMonth07
		, SUM(roster.Dollars * (wh.Month08/ NULLIF(hr.TotalHours, 0))) as DollarsMonth08
		, SUM(roster.Dollars * (wh.Month09/ NULLIF(hr.TotalHours, 0))) as DollarsMonth09
		, SUM(roster.Dollars * (wh.Month10/ NULLIF(hr.TotalHours, 0))) as DollarsMonth10
		, SUM(roster.Dollars * (wh.Month11/ NULLIF(hr.TotalHours, 0))) as DollarsMonth11
		, SUM(roster.Dollars * (wh.Month12/ NULLIF(hr.TotalHours, 0))) as DollarsMonth12
													   												   
		, SUM(roster.FTEs) as FTEsMonth01
		, SUM(roster.FTEs) as FTEsMonth02
		, SUM(roster.FTEs) as FTEsMonth03
		, SUM(roster.FTEs) as FTEsMonth04
		, SUM(roster.FTEs) as FTEsMonth05
		, SUM(roster.FTEs) as FTEsMonth06
		, SUM(roster.FTEs) as FTEsMonth07
		, SUM(roster.FTEs) as FTEsMonth08
		, SUM(roster.FTEs) as FTEsMonth09
		, SUM(roster.FTEs) as FTEsMonth10
		, SUM(roster.FTEs) as FTEsMonth11
		, SUM(roster.FTEs) as FTEsMonth12
													   												   
		, SUM(roster.InitialDollars * (wh.Month01/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth01
		, SUM(roster.InitialDollars * (wh.Month02/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth02
		, SUM(roster.InitialDollars * (wh.Month03/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth03
		, SUM(roster.InitialDollars * (wh.Month04/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth04
		, SUM(roster.InitialDollars * (wh.Month05/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth05
		, SUM(roster.InitialDollars * (wh.Month06/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth06
		, SUM(roster.InitialDollars * (wh.Month07/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth07
		, SUM(roster.InitialDollars * (wh.Month08/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth08
		, SUM(roster.InitialDollars * (wh.Month09/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth09
		, SUM(roster.InitialDollars * (wh.Month10/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth10
		, SUM(roster.InitialDollars * (wh.Month11/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth11
		, SUM(roster.InitialDollars * (wh.Month12/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth12
													   											
		, SUM(roster.InitialFTEs) as InitialFTEsMonth01
		, SUM(roster.InitialFTEs) as InitialFTEsMonth02
		, SUM(roster.InitialFTEs) as InitialFTEsMonth03
		, SUM(roster.InitialFTEs) as InitialFTEsMonth04
		, SUM(roster.InitialFTEs) as InitialFTEsMonth05
		, SUM(roster.InitialFTEs) as InitialFTEsMonth06
		, SUM(roster.InitialFTEs) as InitialFTEsMonth07
		, SUM(roster.InitialFTEs) as InitialFTEsMonth08
		, SUM(roster.InitialFTEs) as InitialFTEsMonth09
		, SUM(roster.InitialFTEs) as InitialFTEsMonth10
		, SUM(roster.InitialFTEs) as InitialFTEsMonth11
		, SUM(roster.InitialFTEs) as InitialFTEsMonth12
		
		, SUM(CASE WHEN @MonthsLoaded <= 1  THEN roster.ProjectedDollars * (whProj.Month01/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth01
		, SUM(CASE WHEN @MonthsLoaded <= 2  THEN roster.ProjectedDollars * (whProj.Month02/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth02
		, SUM(CASE WHEN @MonthsLoaded <= 3  THEN roster.ProjectedDollars * (whProj.Month03/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth03
		, SUM(CASE WHEN @MonthsLoaded <= 4  THEN roster.ProjectedDollars * (whProj.Month04/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth04
		, SUM(CASE WHEN @MonthsLoaded <= 5  THEN roster.ProjectedDollars * (whProj.Month05/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth05
		, SUM(CASE WHEN @MonthsLoaded <= 6  THEN roster.ProjectedDollars * (whProj.Month06/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth06
		, SUM(CASE WHEN @MonthsLoaded <= 7  THEN roster.ProjectedDollars * (whProj.Month07/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth07
		, SUM(CASE WHEN @MonthsLoaded <= 8  THEN roster.ProjectedDollars * (whProj.Month08/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth08
		, SUM(CASE WHEN @MonthsLoaded <= 9  THEN roster.ProjectedDollars * (whProj.Month09/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth09
		, SUM(CASE WHEN @MonthsLoaded <= 10 THEN roster.ProjectedDollars * (whProj.Month10/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth10
		, SUM(CASE WHEN @MonthsLoaded <= 11 THEN roster.ProjectedDollars * (whProj.Month11/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth11
		, SUM(CASE WHEN @MonthsLoaded <= 12 THEN roster.ProjectedDollars * (whProj.Month12/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth12
		
		, SUM(CASE WHEN @MonthsLoaded <= 1  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth01
		, SUM(CASE WHEN @MonthsLoaded <= 2  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth02
		, SUM(CASE WHEN @MonthsLoaded <= 3  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth03
		, SUM(CASE WHEN @MonthsLoaded <= 4  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth04
		, SUM(CASE WHEN @MonthsLoaded <= 5  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth05
		, SUM(CASE WHEN @MonthsLoaded <= 6  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth06
		, SUM(CASE WHEN @MonthsLoaded <= 7  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth07
		, SUM(CASE WHEN @MonthsLoaded <= 8  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth08
		, SUM(CASE WHEN @MonthsLoaded <= 9  THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth09
		, SUM(CASE WHEN @MonthsLoaded <= 10 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth10
		, SUM(CASE WHEN @MonthsLoaded <= 11 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth11
		, SUM(CASE WHEN @MonthsLoaded <= 12 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth12
	INTO #tmpExistingEmployees
	FROM 
		#tmpRosterTotalsForExistingEmployees roster 
		INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON dept.DepartmentID = roster.DepartmentID
		INNER JOIN [client].[FactWorkingHoursPerMonth] wh WITH (READUNCOMMITTED) ON wh.FiscalYearID = @BudgetYear AND wh.WorkWeekID = dept.WorkWeekID
		INNER JOIN [client].[FactWorkingHoursPerMonth] whProj WITH (READUNCOMMITTED) ON whProj.FiscalYearID = @ProjectedYear AND whProj.WorkWeekID = dept.WorkWeekID
		INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID
		INNER JOIN #tmpHoursRatio hr ON wh.FiscalYearID = hr.FiscalYearID AND hr.WorkWeekID = dept.WorkWeekID	 
		INNER JOIN #tmpHoursRatio hrProj ON whProj.FiscalYearID = hrProj.FiscalYearID AND hrProj.WorkWeekID = dept.WorkWeekID  
		INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID
	GROUP BY
		  roster.BudgetConfigID
		, roster.DepartmentID
		, roster.JobCodeID
		, roster.PayCodeGroupID
		, hr.TotalHours
		, hrProj.TotalHours
		, roster.EntityID;
				
	-- rollup roster data (aggregate over employeeID)
	-- We do new employees seperate because of it's unique logic and so that we can accurately take the Projection - Actual YTD accurately
	;WITH NewEmployees as (
		SELECT e.EmployeeID, f.SortOrder as StartMonthSortOrder, e.FiscalYearID, 13 - f.SortOrder AS WorkingMonths, result.DepartmentID, budg.RemainingAnnualHours AS BudgetRemainingAnnualHours, proj.RemainingAnnualHours AS ProjectionRemainingAnnualHours
		FROM [fp].[RosterBudgetNewEmployee] e
			INNER JOIN [fw].[DimFiscalMonth] f WITH (READUNCOMMITTED) ON e.FiscalMonthID = f.FiscalMonthID
			INNER JOIN (SELECT DISTINCT BudgetConfigGUID, DepartmentID, EmployeeID FROM [fp].[RosterBudgetBasisResult]) result ON e.EmployeeID = result.EmployeeID
				AND result.BudgetConfigGUID = e.BudgetConfigGUID  
			INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON result.DepartmentID = dept.DepartmentID
			INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON e.BudgetConfigGUID = bc.BudgetConfigGUID
			INNER JOIN [fp].[viewWorkingHoursPerMonthWithBreakdown] budg WITH (READUNCOMMITTED)
				 ON bc.FiscalYearID = budg.FiscalYearID 
				AND e.FiscalMonthID = budg.FiscalMonthID
				AND dept.WorkWeekID = budg.WorkWeekID
			INNER JOIN [fp].[viewWorkingHoursPerMonthWithBreakdown] proj WITH (READUNCOMMITTED)
				 ON bc.FiscalYearID - 1 = proj.FiscalYearID 
				AND e.FiscalMonthID = proj.FiscalMonthID
				AND dept.WorkWeekID = proj.WorkWeekID
	)
	SELECT
		  @BudgetConfigID AS BudgetConfigID
		, dept.EntityID
		, rb.DepartmentID
		, rb.JobCodeID
		, rb.PayCodeGroupID 
		-- To understand the new employee case, for new employees, if they started in 2018, but the budget was for 2019, spread it for the entire year. 
		-- If they however started in 2019 for the 2019 budget, only spread to the months after they started. It is also important, that for new employees we only spread over the remaining hours and not the total yearly hours.
		
		-- If you enter a year not in the scope of the budget, do not transfer this employee (maybe something we should block on the UI?)
		
		-- For projection, we only want to spread the dollars to the months NOT loaded, if that employee is new, make sure they started in the projected year
		-- If they didn't, don't transfer these dollars. Currently you can still enter a value for these types of employees, but we will need to block that.
		, SUM(CASE WHEN (1  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month01/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth01
		, SUM(CASE WHEN (2  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month02/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth02
		, SUM(CASE WHEN (3  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month03/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth03
		, SUM(CASE WHEN (4  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month04/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth04
		, SUM(CASE WHEN (5  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month05/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth05
		, SUM(CASE WHEN (6  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month06/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth06
		, SUM(CASE WHEN (7  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month07/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth07
		, SUM(CASE WHEN (8  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month08/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth08
		, SUM(CASE WHEN (9  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month09/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth09
		, SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month10/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth10
		, SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month11/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth11
		, SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month12/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth12
													   												   
		, SUM(CASE WHEN (1  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth01
		, SUM(CASE WHEN (2  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth02
		, SUM(CASE WHEN (3  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth03
		, SUM(CASE WHEN (4  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth04
		, SUM(CASE WHEN (5  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth05
		, SUM(CASE WHEN (6  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth06
		, SUM(CASE WHEN (7  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth07
		, SUM(CASE WHEN (8  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth08
		, SUM(CASE WHEN (9  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth09
		, SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth10
		, SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth11
		, SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth12
													   												   
		, SUM(CASE WHEN (1  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month01/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth01
		, SUM(CASE WHEN (2  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month02/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth02
		, SUM(CASE WHEN (3  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month03/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth03
		, SUM(CASE WHEN (4  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month04/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth04
		, SUM(CASE WHEN (5  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month05/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth05
		, SUM(CASE WHEN (6  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month06/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth06
		, SUM(CASE WHEN (7  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month07/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth07
		, SUM(CASE WHEN (8  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month08/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth08
		, SUM(CASE WHEN (9  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month09/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth09
		, SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month10/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth10
		, SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month11/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth11
		, SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month12/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth12
													   										
		, SUM(CASE WHEN (1  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth01
		, SUM(CASE WHEN (2  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth02
		, SUM(CASE WHEN (3  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth03
		, SUM(CASE WHEN (4  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth04
		, SUM(CASE WHEN (5  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth05
		, SUM(CASE WHEN (6  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth06
		, SUM(CASE WHEN (7  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth07
		, SUM(CASE WHEN (8  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth08
		, SUM(CASE WHEN (9  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth09
		, SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth10
		, SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth11
		, SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth12
		
		, SUM(CASE WHEN ((1  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 1  THEN rb.ProjectedDollars * (whProj.Month01/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth01
		, SUM(CASE WHEN ((2  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 2  THEN rb.ProjectedDollars * (whProj.Month02/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth02
		, SUM(CASE WHEN ((3  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 3  THEN rb.ProjectedDollars * (whProj.Month03/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth03
		, SUM(CASE WHEN ((4  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 4  THEN rb.ProjectedDollars * (whProj.Month04/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth04
		, SUM(CASE WHEN ((5  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 5  THEN rb.ProjectedDollars * (whProj.Month05/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth05
		, SUM(CASE WHEN ((6  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 6  THEN rb.ProjectedDollars * (whProj.Month06/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth06
		, SUM(CASE WHEN ((7  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 7  THEN rb.ProjectedDollars * (whProj.Month07/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth07
		, SUM(CASE WHEN ((8  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 8  THEN rb.ProjectedDollars * (whProj.Month08/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth08
		, SUM(CASE WHEN ((9  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 9  THEN rb.ProjectedDollars * (whProj.Month09/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth09
		, SUM(CASE WHEN ((10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 10 THEN rb.ProjectedDollars * (whProj.Month10/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth10
		, SUM(CASE WHEN ((11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 11 THEN rb.ProjectedDollars * (whProj.Month11/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth11
		, SUM(CASE WHEN ((12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 12 THEN rb.ProjectedDollars * (whProj.Month12/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth12
		
		, SUM(CASE WHEN ((1  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 1  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth01
		, SUM(CASE WHEN ((2  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 2  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth02
		, SUM(CASE WHEN ((3  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 3  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth03
		, SUM(CASE WHEN ((4  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 4  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth04
		, SUM(CASE WHEN ((5  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 5  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth05
		, SUM(CASE WHEN ((6  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 6  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth06
		, SUM(CASE WHEN ((7  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 7  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth07
		, SUM(CASE WHEN ((8  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 8  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth08
		, SUM(CASE WHEN ((9  >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 9  THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth09
		, SUM(CASE WHEN ((10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 10 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth10
		, SUM(CASE WHEN ((11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 11 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth11
		, SUM(CASE WHEN ((12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 12 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth12
	INTO
		#tmpNewRosterEmployees
	FROM [fp].[RosterBudgetBasisResult] rb
		INNER JOIN NewEmployees emp ON rb.EmployeeID = emp.EmployeeID AND rb.DepartmentID = emp.DepartmentID
		INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rb.DepartmentID = dept.DepartmentID 
		INNER JOIN [client].[FactWorkingHoursPerMonth] wh WITH (READUNCOMMITTED) ON wh.FiscalYearID = @BudgetYear AND wh.WorkWeekID = dept.WorkWeekID
		INNER JOIN [client].[FactWorkingHoursPerMonth] whProj WITH (READUNCOMMITTED) ON whProj.FiscalYearID = @ProjectedYear AND whProj.WorkWeekID = dept.WorkWeekID
		INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID
		INNER JOIN #tmpHoursRatio hr ON wh.FiscalYearID = hr.FiscalYearID AND hr.WorkWeekID = dept.WorkWeekID	 
		INNER JOIN #tmpHoursRatio hrProj ON whProj.FiscalYearID = hrProj.FiscalYearID AND hrProj.WorkWeekID = dept.WorkWeekID  
		INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID
	WHERE rb.BudgetConfigGUID = @BudgetConfigGUID
	GROUP BY
		  rb.DepartmentID
		, rb.JobCodeID
		, rb.PayCodeGroupID
		, hr.TotalHours
		, hrProj.TotalHours
		, dept.EntityID;

	-- Combine the existing and new employees
	SELECT
		COALESCE(existing.BudgetConfigID, new.BudgetConfigID) AS BudgetConfigID, 
		COALESCE(existing.EntityID, new.EntityID) AS EntityID, 
		COALESCE(existing.DepartmentID, new.DepartmentID) AS DepartmentID, 
		COALESCE(existing.JobCodeID, new.JobCodeID) AS JobCodeID, 
		COALESCE(existing.PayCodeGroupID, new.PayCodeGroupID) AS PayCodeGroupID,
		SUM(ISNULL(existing.DollarsMonth01, 0)) + SUM(ISNULL(new.DollarsMonth01, 0)) AS DollarsMonth01,
		SUM(ISNULL(existing.DollarsMonth02, 0)) + SUM(ISNULL(new.DollarsMonth02, 0)) AS DollarsMonth02,
		SUM(ISNULL(existing.DollarsMonth03, 0)) + SUM(ISNULL(new.DollarsMonth03, 0)) AS DollarsMonth03,
		SUM(ISNULL(existing.DollarsMonth04, 0)) + SUM(ISNULL(new.DollarsMonth04, 0)) AS DollarsMonth04,
		SUM(ISNULL(existing.DollarsMonth05, 0)) + SUM(ISNULL(new.DollarsMonth05, 0)) AS DollarsMonth05,
		SUM(ISNULL(existing.DollarsMonth06, 0)) + SUM(ISNULL(new.DollarsMonth06, 0)) AS DollarsMonth06,
		SUM(ISNULL(existing.DollarsMonth07, 0)) + SUM(ISNULL(new.DollarsMonth07, 0)) AS DollarsMonth07,
		SUM(ISNULL(existing.DollarsMonth08, 0)) + SUM(ISNULL(new.DollarsMonth08, 0)) AS DollarsMonth08,
		SUM(ISNULL(existing.DollarsMonth09, 0)) + SUM(ISNULL(new.DollarsMonth09, 0)) AS DollarsMonth09,
		SUM(ISNULL(existing.DollarsMonth10, 0)) + SUM(ISNULL(new.DollarsMonth10, 0)) AS DollarsMonth10,
		SUM(ISNULL(existing.DollarsMonth11, 0)) + SUM(ISNULL(new.DollarsMonth11, 0)) AS DollarsMonth11,
		SUM(ISNULL(existing.DollarsMonth12, 0)) + SUM(ISNULL(new.DollarsMonth12, 0)) AS DollarsMonth12,

		SUM(ISNULL(existing.FTEsMonth01, 0)) + SUM(ISNULL(new.FTEsMonth01, 0)) AS FTEsMonth01,
		SUM(ISNULL(existing.FTEsMonth02, 0)) + SUM(ISNULL(new.FTEsMonth02, 0)) AS FTEsMonth02,
		SUM(ISNULL(existing.FTEsMonth03, 0)) + SUM(ISNULL(new.FTEsMonth03, 0)) AS FTEsMonth03,
		SUM(ISNULL(existing.FTEsMonth04, 0)) + SUM(ISNULL(new.FTEsMonth04, 0)) AS FTEsMonth04,
		SUM(ISNULL(existing.FTEsMonth05, 0)) + SUM(ISNULL(new.FTEsMonth05, 0)) AS FTEsMonth05,
		SUM(ISNULL(existing.FTEsMonth06, 0)) + SUM(ISNULL(new.FTEsMonth06, 0)) AS FTEsMonth06,
		SUM(ISNULL(existing.FTEsMonth07, 0)) + SUM(ISNULL(new.FTEsMonth07, 0)) AS FTEsMonth07,
		SUM(ISNULL(existing.FTEsMonth08, 0)) + SUM(ISNULL(new.FTEsMonth08, 0)) AS FTEsMonth08,
		SUM(ISNULL(existing.FTEsMonth09, 0)) + SUM(ISNULL(new.FTEsMonth09, 0)) AS FTEsMonth09,
		SUM(ISNULL(existing.FTEsMonth10, 0)) + SUM(ISNULL(new.FTEsMonth10, 0)) AS FTEsMonth10,
		SUM(ISNULL(existing.FTEsMonth11, 0)) + SUM(ISNULL(new.FTEsMonth11, 0)) AS FTEsMonth11,
		SUM(ISNULL(existing.FTEsMonth12, 0)) + SUM(ISNULL(new.FTEsMonth12, 0)) AS FTEsMonth12,

		SUM(ISNULL(existing.InitialDollarsMonth01, 0)) + SUM(ISNULL(new.InitialDollarsMonth01, 0)) AS InitialDollarsMonth01,
		SUM(ISNULL(existing.InitialDollarsMonth02, 0)) + SUM(ISNULL(new.InitialDollarsMonth02, 0)) AS InitialDollarsMonth02,
		SUM(ISNULL(existing.InitialDollarsMonth03, 0)) + SUM(ISNULL(new.InitialDollarsMonth03, 0)) AS InitialDollarsMonth03,
		SUM(ISNULL(existing.InitialDollarsMonth04, 0)) + SUM(ISNULL(new.InitialDollarsMonth04, 0)) AS InitialDollarsMonth04,
		SUM(ISNULL(existing.InitialDollarsMonth05, 0)) + SUM(ISNULL(new.InitialDollarsMonth05, 0)) AS InitialDollarsMonth05,
		SUM(ISNULL(existing.InitialDollarsMonth06, 0)) + SUM(ISNULL(new.InitialDollarsMonth06, 0)) AS InitialDollarsMonth06,
		SUM(ISNULL(existing.InitialDollarsMonth07, 0)) + SUM(ISNULL(new.InitialDollarsMonth07, 0)) AS InitialDollarsMonth07,
		SUM(ISNULL(existing.InitialDollarsMonth08, 0)) + SUM(ISNULL(new.InitialDollarsMonth08, 0)) AS InitialDollarsMonth08,
		SUM(ISNULL(existing.InitialDollarsMonth09, 0)) + SUM(ISNULL(new.InitialDollarsMonth09, 0)) AS InitialDollarsMonth09,
		SUM(ISNULL(existing.InitialDollarsMonth10, 0)) + SUM(ISNULL(new.InitialDollarsMonth10, 0)) AS InitialDollarsMonth10,
		SUM(ISNULL(existing.InitialDollarsMonth11, 0)) + SUM(ISNULL(new.InitialDollarsMonth11, 0)) AS InitialDollarsMonth11,
		SUM(ISNULL(existing.InitialDollarsMonth12, 0)) + SUM(ISNULL(new.InitialDollarsMonth12, 0)) AS InitialDollarsMonth12,

		SUM(ISNULL(existing.InitialFTEsMonth01, 0)) + SUM(ISNULL(new.InitialFTEsMonth01, 0)) AS InitialFTEsMonth01,
		SUM(ISNULL(existing.InitialFTEsMonth02, 0)) + SUM(ISNULL(new.InitialFTEsMonth02, 0)) AS InitialFTEsMonth02,
		SUM(ISNULL(existing.InitialFTEsMonth03, 0)) + SUM(ISNULL(new.InitialFTEsMonth03, 0)) AS InitialFTEsMonth03,
		SUM(ISNULL(existing.InitialFTEsMonth04, 0)) + SUM(ISNULL(new.InitialFTEsMonth04, 0)) AS InitialFTEsMonth04,
		SUM(ISNULL(existing.InitialFTEsMonth05, 0)) + SUM(ISNULL(new.InitialFTEsMonth05, 0)) AS InitialFTEsMonth05,
		SUM(ISNULL(existing.InitialFTEsMonth06, 0)) + SUM(ISNULL(new.InitialFTEsMonth06, 0)) AS InitialFTEsMonth06,
		SUM(ISNULL(existing.InitialFTEsMonth07, 0)) + SUM(ISNULL(new.InitialFTEsMonth07, 0)) AS InitialFTEsMonth07,
		SUM(ISNULL(existing.InitialFTEsMonth08, 0)) + SUM(ISNULL(new.InitialFTEsMonth08, 0)) AS InitialFTEsMonth08,
		SUM(ISNULL(existing.InitialFTEsMonth09, 0)) + SUM(ISNULL(new.InitialFTEsMonth09, 0)) AS InitialFTEsMonth09,
		SUM(ISNULL(existing.InitialFTEsMonth10, 0)) + SUM(ISNULL(new.InitialFTEsMonth10, 0)) AS InitialFTEsMonth10,
		SUM(ISNULL(existing.InitialFTEsMonth11, 0)) + SUM(ISNULL(new.InitialFTEsMonth11, 0)) AS InitialFTEsMonth11,
		SUM(ISNULL(existing.InitialFTEsMonth12, 0)) + SUM(ISNULL(new.InitialFTEsMonth12, 0)) AS InitialFTEsMonth12,

		SUM(ISNULL(existing.ProjectedDollarsMonth01, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth01, 0)) AS ProjectedDollarsMonth01,
		SUM(ISNULL(existing.ProjectedDollarsMonth02, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth02, 0)) AS ProjectedDollarsMonth02,
		SUM(ISNULL(existing.ProjectedDollarsMonth03, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth03, 0)) AS ProjectedDollarsMonth03,
		SUM(ISNULL(existing.ProjectedDollarsMonth04, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth04, 0)) AS ProjectedDollarsMonth04,
		SUM(ISNULL(existing.ProjectedDollarsMonth05, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth05, 0)) AS ProjectedDollarsMonth05,
		SUM(ISNULL(existing.ProjectedDollarsMonth06, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth06, 0)) AS ProjectedDollarsMonth06,
		SUM(ISNULL(existing.ProjectedDollarsMonth07, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth07, 0)) AS ProjectedDollarsMonth07,
		SUM(ISNULL(existing.ProjectedDollarsMonth08, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth08, 0)) AS ProjectedDollarsMonth08,
		SUM(ISNULL(existing.ProjectedDollarsMonth09, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth09, 0)) AS ProjectedDollarsMonth09,
		SUM(ISNULL(existing.ProjectedDollarsMonth10, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth10, 0)) AS ProjectedDollarsMonth10,
		SUM(ISNULL(existing.ProjectedDollarsMonth11, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth11, 0)) AS ProjectedDollarsMonth11,
		SUM(ISNULL(existing.ProjectedDollarsMonth12, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth12, 0)) AS ProjectedDollarsMonth12,

		SUM(ISNULL(existing.ProjectedFTEsMonth01, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth01, 0)) AS ProjectedFTEsMonth01,
		SUM(ISNULL(existing.ProjectedFTEsMonth02, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth02, 0)) AS ProjectedFTEsMonth02,
		SUM(ISNULL(existing.ProjectedFTEsMonth03, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth03, 0)) AS ProjectedFTEsMonth03,
		SUM(ISNULL(existing.ProjectedFTEsMonth04, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth04, 0)) AS ProjectedFTEsMonth04,
		SUM(ISNULL(existing.ProjectedFTEsMonth05, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth05, 0)) AS ProjectedFTEsMonth05,
		SUM(ISNULL(existing.ProjectedFTEsMonth06, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth06, 0)) AS ProjectedFTEsMonth06,
		SUM(ISNULL(existing.ProjectedFTEsMonth07, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth07, 0)) AS ProjectedFTEsMonth07,
		SUM(ISNULL(existing.ProjectedFTEsMonth08, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth08, 0)) AS ProjectedFTEsMonth08,
		SUM(ISNULL(existing.ProjectedFTEsMonth09, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth09, 0)) AS ProjectedFTEsMonth09,
		SUM(ISNULL(existing.ProjectedFTEsMonth10, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth10, 0)) AS ProjectedFTEsMonth10,
		SUM(ISNULL(existing.ProjectedFTEsMonth11, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth11, 0)) AS ProjectedFTEsMonth11,
		SUM(ISNULL(existing.ProjectedFTEsMonth12, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth12, 0)) AS ProjectedFTEsMonth12
	INTO #tmpRosterRolledUp
	FROM #tmpExistingEmployees existing
		FULL OUTER JOIN #tmpNewRosterEmployees new ON existing.BudgetConfigID = new.BudgetConfigID
			AND existing.EntityID = new.EntityID
			AND existing.DepartmentID = new.DepartmentID
			AND existing.JobCodeID = new.JobCodeID
			AND existing.PayCodeGroupID = new.PayCodeGroupID
	GROUP BY existing.BudgetConfigID,
		existing.EntityID,
		existing.DepartmentID,
		existing.JobCodeID,
		existing.PayCodeGroupID,
		new.BudgetConfigID,
		new.EntityID,
		new.DepartmentID,
		new.JobCodeID,
		new.PayCodeGroupID
				
	------------------
	-- Padding Data --
	------------------
		
	-- Create temp table for all dimensionality that might need to be padded. Only Pad dollars, hours, and FTEs
	SELECT DISTINCT
		@BudgetConfigID as BudgetConfigID, egc.EntityGroupConfigID, dept.EntityID, rb.DepartmentID, rb.JobCodeID, rb.PayCodeGroupID, pcg.ProductiveClassID, vrb.VariabilityID 
	INTO #tmpPaddedStaffingData
	FROM #tmpRosterRolledUp rb
		INNER JOIN [fw].[DimDepartment] dept ON rb.DepartmentID = dept.DepartmentID
		INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID
		INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID
		INNER JOIN [fp].[EntityGroupConfigMapping] map ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID AND map.EntityID = dept.EntityID
		INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID
		INNER JOIN [fw].[DimPayCodeGroup] pcg ON pcg.PayCodeGroupID = rb.PayCodeGroupID		
		CROSS APPLY (VALUES (1),(2)) vrb(VariabilityID)
		LEFT JOIN [fp].[Staffing] ph 
			ON rb.EntityID = ph.EntityID 
			AND rb.DepartmentID = ph.DepartmentID 
			AND rb.JobCodeID = ph.JobCodeID
			AND rb.PayCodeGroupID = ph.PayCodeGroupID
			AND ph.BudgetConfigID = rb.BudgetConfigID
			AND ph.VariabilityID = vrb.VariabilityID
	WHERE ph.StaffingID IS NULL 	
	 
	-- Pad data
	INSERT INTO [fp].[Staffing] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID) 
	SELECT DISTINCT
		b.BudgetConfigID, b.EntityGroupConfigID, b.EntityID, b.DepartmentID, b.JobCodeID, b.PayCodeGroupID, b.ProductiveClassID, b.VariabilityID
	FROM #tmpPaddedStaffingData b
		LEFT JOIN [fp].[Staffing] ph ON 
			b.JobCodeID = ph.JobCodeID 
			AND b.PayCodeGroupID = ph.PayCodeGroupID 
			and b.EntityID = ph.EntityID 
			and b.DepartmentID = ph.DepartmentID 
			and b.BudgetConfigID = ph.BudgetConfigID
			and b.VariabilityID = ph.VariabilityID
	WHERE ph.StaffingID IS NULL
 
	-- Pad the wage rate and history tables
	EXEC [fp].[procPadStaffing] @BudgetConfigID, @SourceDimensionality
 
	-----------------
	-- Update FTEs --
	-----------------
	IF @IsFTEHidden = 1 BEGIN -- Typically a U of IA only setting
	
		-- When FTE's are hidden, we don't care about transferring the FTEs, only the dollars
		UPDATE fs
		SET InitialBudgetFTEs01 = 0, InitialBudgetFTEs02 = 0, InitialBudgetFTEs03 = 0, InitialBudgetFTEs04 = 0,	InitialBudgetFTEs05 = 0, InitialBudgetFTEs06 = 0,
			InitialBudgetFTEs07 = 0, InitialBudgetFTEs08 = 0, InitialBudgetFTEs09 = 0, InitialBudgetFTEs10 = 0,	InitialBudgetFTEs11 = 0, InitialBudgetFTEs12 = 0,
			InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >=  1 THEN InitialProjectionFTEs01 ELSE 0 END, 
			InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >=  2 THEN InitialProjectionFTEs02 ELSE 0 END, 
			InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >=  3 THEN InitialProjectionFTEs03 ELSE 0 END, 
			InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >=  4 THEN InitialProjectionFTEs04 ELSE 0 END,	
			InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >=  5 THEN InitialProjectionFTEs05 ELSE 0 END, 
			InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >=  6 THEN InitialProjectionFTEs06 ELSE 0 END,
			InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >=  7 THEN InitialProjectionFTEs07 ELSE 0 END, 
			InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >=  8 THEN InitialProjectionFTEs08 ELSE 0 END, 
			InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >=  9 THEN InitialProjectionFTEs09 ELSE 0 END, 
			InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionFTEs10 ELSE 0 END,	
			InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionFTEs11 ELSE 0 END, 
			InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionFTEs12 ELSE 0 END,
			TargetAdjustedFTEs01 = 0, TargetAdjustedFTEs02 = 0, TargetAdjustedFTEs03 = 0, TargetAdjustedFTEs04 = 0,	TargetAdjustedFTEs05 = 0, TargetAdjustedFTEs06 = 0,
			TargetAdjustedFTEs07 = 0, TargetAdjustedFTEs08 = 0, TargetAdjustedFTEs09 = 0, TargetAdjustedFTEs10 = 0,	TargetAdjustedFTEs11 = 0, TargetAdjustedFTEs12 = 0,
			BudgetAdjustedFTEs01 = 0, BudgetAdjustedFTEs02 = 0, BudgetAdjustedFTEs03 = 0, BudgetAdjustedFTEs04 = 0,	BudgetAdjustedFTEs05 = 0, BudgetAdjustedFTEs06 = 0,
			BudgetAdjustedFTEs07 = 0, BudgetAdjustedFTEs08 = 0, BudgetAdjustedFTEs09 = 0, BudgetAdjustedFTEs10 = 0,	BudgetAdjustedFTEs11 = 0, BudgetAdjustedFTEs12 = 0,
			ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded >=  1 THEN ProjectionAdjustedFTEs01 ELSE 0 END, 
			ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded >=  2 THEN ProjectionAdjustedFTEs02 ELSE 0 END, 
			ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded >=  3 THEN ProjectionAdjustedFTEs03 ELSE 0 END, 
			ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded >=  4 THEN ProjectionAdjustedFTEs04 ELSE 0 END,	
			ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded >=  5 THEN ProjectionAdjustedFTEs05 ELSE 0 END, 
			ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded >=  6 THEN ProjectionAdjustedFTEs06 ELSE 0 END,
			ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded >=  7 THEN ProjectionAdjustedFTEs07 ELSE 0 END, 
			ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded >=  8 THEN ProjectionAdjustedFTEs08 ELSE 0 END, 
			ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded >=  9 THEN ProjectionAdjustedFTEs09 ELSE 0 END, 
			ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE 0 END,	
			ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE 0 END, 
			ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE 0 END,
			TargetFTEsLockFlag = 1,
			TargetFTEsLockType = 4,
			BudgetFTEsLockFlag = 1,
			BudgetFTEsLockType = 4,
			ProjectionFTEsLockFlag = 1,
			ProjectionFTEsLockType = 4
		FROM [fp].[Staffing] fs 
			INNER JOIN #tmpRosterRolledUp rb
				ON fs.JobCodeID = rb.JobCodeID 
				AND fs.DepartmentID = rb.DepartmentID 
				AND fs.PayCodeGroupID = rb.PayCodeGroupID 
				AND fs.EntityID = rb.EntityID
		WHERE  fs.BudgetConfigID = @BudgetConfigID 
			AND fs.VariabilityID = 1
			AND (
				TargetAdjustedFTEs01 != 0 OR TargetAdjustedFTEs02 != 0 OR TargetAdjustedFTEs03 != 0 OR TargetAdjustedFTEs04 != 0 OR TargetAdjustedFTEs05 != 0 OR TargetAdjustedFTEs06 != 0 OR
				TargetAdjustedFTEs07 != 0 OR TargetAdjustedFTEs08 != 0 OR TargetAdjustedFTEs09 != 0 OR TargetAdjustedFTEs10 != 0 OR TargetAdjustedFTEs11 != 0 OR TargetAdjustedFTEs12 != 0 OR
				BudgetAdjustedFTEs01 != 0 OR BudgetAdjustedFTEs02 != 0 OR BudgetAdjustedFTEs03 != 0 OR BudgetAdjustedFTEs04 != 0 OR BudgetAdjustedFTEs05 != 0 OR BudgetAdjustedFTEs06 != 0 OR
				BudgetAdjustedFTEs07 != 0 OR BudgetAdjustedFTEs08 != 0 OR BudgetAdjustedFTEs09 != 0 OR BudgetAdjustedFTEs10 != 0 OR BudgetAdjustedFTEs11 != 0 OR BudgetAdjustedFTEs12 != 0 OR
				TargetFTEsLockType != 4 OR 
				BudgetFTEsLockType != 4 
			OR
				(@MonthsLoaded < 1  AND ProjectionAdjustedFTEs01 != 0) OR
				(@MonthsLoaded < 2  AND ProjectionAdjustedFTEs02 != 0) OR
				(@MonthsLoaded < 3  AND ProjectionAdjustedFTEs03 != 0) OR
				(@MonthsLoaded < 4  AND ProjectionAdjustedFTEs04 != 0) OR	
				(@MonthsLoaded < 5  AND ProjectionAdjustedFTEs05 != 0) OR
				(@MonthsLoaded < 6  AND ProjectionAdjustedFTEs06 != 0) OR
				(@MonthsLoaded < 7  AND ProjectionAdjustedFTEs07 != 0) OR
				(@MonthsLoaded < 8  AND ProjectionAdjustedFTEs08 != 0) OR
				(@MonthsLoaded < 9  AND ProjectionAdjustedFTEs09 != 0) OR
				(@MonthsLoaded < 10 AND ProjectionAdjustedFTEs10 != 0) OR	
				(@MonthsLoaded < 11 AND ProjectionAdjustedFTEs11 != 0) OR
				(@MonthsLoaded < 12 AND ProjectionAdjustedFTEs12 != 0) OR
				ProjectionFTEsLockType != 4
			OR
				InitialBudgetFTEs01 != 0 OR InitialBudgetFTEs02 != 0 OR InitialBudgetFTEs03 != 0 OR InitialBudgetFTEs04 != 0 OR InitialBudgetFTEs05 != 0 OR InitialBudgetFTEs06 != 0 OR
				InitialBudgetFTEs07 != 0 OR InitialBudgetFTEs08 != 0 OR InitialBudgetFTEs09 != 0 OR InitialBudgetFTEs10 != 0 OR InitialBudgetFTEs11 != 0 OR InitialBudgetFTEs12 != 0 OR
				(@MonthsLoaded < 1  AND InitialProjectionFTEs01 != 0) OR
				(@MonthsLoaded < 2  AND InitialProjectionFTEs02 != 0) OR
				(@MonthsLoaded < 3  AND InitialProjectionFTEs03 != 0) OR
				(@MonthsLoaded < 4  AND InitialProjectionFTEs04 != 0) OR	
				(@MonthsLoaded < 5  AND InitialProjectionFTEs05 != 0) OR
				(@MonthsLoaded < 6  AND InitialProjectionFTEs06 != 0) OR
				(@MonthsLoaded < 7  AND InitialProjectionFTEs07 != 0) OR
				(@MonthsLoaded < 8  AND InitialProjectionFTEs08 != 0) OR
				(@MonthsLoaded < 9  AND InitialProjectionFTEs09 != 0) OR
				(@MonthsLoaded < 10 AND InitialProjectionFTEs10 != 0) OR	
				(@MonthsLoaded < 11 AND InitialProjectionFTEs11 != 0) OR
				(@MonthsLoaded < 12 AND InitialProjectionFTEs12 != 0)
			
			)
	  END 
	ELSE
	  BEGIN
	  	
		-- When FTEs aren't hidden we need to populate them normally.		
		-- It's important to note that the way FTE's are done currently for Projection are wrong. <-- The old note said they'd be updated at another time but that person was lying
		UPDATE fs 
		SET 
		    InitialBudgetFTEs01 = InitialFTEsMonth01, InitialBudgetFTEs02 = InitialFTEsMonth02, InitialBudgetFTEs03 = InitialFTEsMonth03, InitialBudgetFTEs04 = InitialFTEsMonth04,	
			InitialBudgetFTEs05 = InitialFTEsMonth05, InitialBudgetFTEs06 = InitialFTEsMonth06,	InitialBudgetFTEs07 = InitialFTEsMonth07, InitialBudgetFTEs08 = InitialFTEsMonth08, 
			InitialBudgetFTEs09 = InitialFTEsMonth09, InitialBudgetFTEs10 = InitialFTEsMonth10,	InitialBudgetFTEs11 = InitialFTEsMonth11, InitialBudgetFTEs12 = InitialFTEsMonth12,
			InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >=  1 THEN InitialProjectionFTEs01 ELSE ProjectedFTEsMonth01 END, 
			InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >=  2 THEN InitialProjectionFTEs02 ELSE ProjectedFTEsMonth02 END, 
			InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >=  3 THEN InitialProjectionFTEs03 ELSE ProjectedFTEsMonth03 END, 
			InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >=  4 THEN InitialProjectionFTEs04 ELSE ProjectedFTEsMonth04 END,	
			InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >=  5 THEN InitialProjectionFTEs05 ELSE ProjectedFTEsMonth05 END, 
			InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >=  6 THEN InitialProjectionFTEs06 ELSE ProjectedFTEsMonth06 END,
			InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >=  7 THEN InitialProjectionFTEs07 ELSE ProjectedFTEsMonth07 END, 
			InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >=  8 THEN InitialProjectionFTEs08 ELSE ProjectedFTEsMonth08 END, 
			InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >=  9 THEN InitialProjectionFTEs09 ELSE ProjectedFTEsMonth09 END, 
			InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionFTEs10 ELSE ProjectedFTEsMonth10 END,	
			InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionFTEs11 ELSE ProjectedFTEsMonth11 END, 
			InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionFTEs12 ELSE ProjectedFTEsMonth12 END,
			TargetAdjustedFTEs01 = FTEsMonth01, TargetAdjustedFTEs02 = FTEsMonth02, TargetAdjustedFTEs03 = FTEsMonth03, TargetAdjustedFTEs04 = FTEsMonth04,	TargetAdjustedFTEs05 = FTEsMonth05, TargetAdjustedFTEs06 = FTEsMonth06,
			TargetAdjustedFTEs07 = FTEsMonth07, TargetAdjustedFTEs08 = FTEsMonth08, TargetAdjustedFTEs09 = FTEsMonth09, TargetAdjustedFTEs10 = FTEsMonth10,	TargetAdjustedFTEs11 = FTEsMonth11, TargetAdjustedFTEs12 = FTEsMonth12,
			BudgetAdjustedFTEs01 = FTEsMonth01, BudgetAdjustedFTEs02 = FTEsMonth02, BudgetAdjustedFTEs03 = FTEsMonth03, BudgetAdjustedFTEs04 = FTEsMonth04,	BudgetAdjustedFTEs05 = FTEsMonth05, BudgetAdjustedFTEs06 = FTEsMonth06,
			BudgetAdjustedFTEs07 = FTEsMonth07, BudgetAdjustedFTEs08 = FTEsMonth08, BudgetAdjustedFTEs09 = FTEsMonth09, BudgetAdjustedFTEs10 = FTEsMonth10,	BudgetAdjustedFTEs11 = FTEsMonth11, BudgetAdjustedFTEs12 = FTEsMonth12,
			ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded >=  1 THEN ProjectionAdjustedFTEs01 ELSE ProjectedFTEsMonth01 END, 
			ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded >=  2 THEN ProjectionAdjustedFTEs02 ELSE ProjectedFTEsMonth02 END, 
			ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded >=  3 THEN ProjectionAdjustedFTEs03 ELSE ProjectedFTEsMonth03 END, 
			ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded >=  4 THEN ProjectionAdjustedFTEs04 ELSE ProjectedFTEsMonth04 END,	
			ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded >=  5 THEN ProjectionAdjustedFTEs05 ELSE ProjectedFTEsMonth05 END, 
			ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded >=  6 THEN ProjectionAdjustedFTEs06 ELSE ProjectedFTEsMonth06 END,
			ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded >=  7 THEN ProjectionAdjustedFTEs07 ELSE ProjectedFTEsMonth07 END, 
			ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded >=  8 THEN ProjectionAdjustedFTEs08 ELSE ProjectedFTEsMonth08 END, 
			ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded >=  9 THEN ProjectionAdjustedFTEs09 ELSE ProjectedFTEsMonth09 END, 
			ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE ProjectedFTEsMonth10 END,	
			ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE ProjectedFTEsMonth11 END, 
			ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE ProjectedFTEsMonth12 END,
			TargetFTEsLockFlag = 1,
			TargetFTEsLockType = 4,
			BudgetFTEsLockFlag = 1,
			BudgetFTEsLockType = 4,
			ProjectionFTEsLockFlag = 1,
			ProjectionFTEsLockType = 4
		FROM [fp].[Staffing] fs 
			INNER JOIN #tmpRosterRolledUp rb
				ON fs.JobCodeID = rb.JobCodeID 
				AND fs.DepartmentID = rb.DepartmentID 
				AND fs.PayCodeGroupID = rb.PayCodeGroupID 
				AND fs.EntityID = rb.EntityID
		WHERE fs.BudgetConfigID = @BudgetConfigID 
			AND fs.VariabilityID = 1
			AND (
			    InitialBudgetFTEs01 != InitialFTEsMonth01 OR 
				InitialBudgetFTEs02 != InitialFTEsMonth02 OR 
				InitialBudgetFTEs03 != InitialFTEsMonth03 OR 
				InitialBudgetFTEs04 != InitialFTEsMonth04 OR 
				InitialBudgetFTEs05 != InitialFTEsMonth05 OR 
				InitialBudgetFTEs06 != InitialFTEsMonth06 OR
				InitialBudgetFTEs07 != InitialFTEsMonth07 OR 
				InitialBudgetFTEs08 != InitialFTEsMonth08 OR 
				InitialBudgetFTEs09 != InitialFTEsMonth09 OR 
				InitialBudgetFTEs10 != InitialFTEsMonth10 OR 
				InitialBudgetFTEs11 != InitialFTEsMonth11 OR 
				InitialBudgetFTEs12 != InitialFTEsMonth12 OR
				TargetAdjustedFTEs01 != FTEsMonth01 OR TargetAdjustedFTEs02 != FTEsMonth02 OR TargetAdjustedFTEs03 != FTEsMonth03 OR TargetAdjustedFTEs04 != FTEsMonth04 OR	
				TargetAdjustedFTEs05 != FTEsMonth05 OR TargetAdjustedFTEs06 != FTEsMonth06 OR TargetAdjustedFTEs07 != FTEsMonth07 OR TargetAdjustedFTEs08 != FTEsMonth08 OR	
				TargetAdjustedFTEs09 != FTEsMonth09 OR TargetAdjustedFTEs10 != FTEsMonth10 OR	TargetAdjustedFTEs11 != FTEsMonth11 OR TargetAdjustedFTEs12 != FTEsMonth12 OR
				BudgetAdjustedFTEs01 != FTEsMonth01 OR BudgetAdjustedFTEs02 != FTEsMonth02 OR BudgetAdjustedFTEs03 != FTEsMonth03 OR BudgetAdjustedFTEs04 != FTEsMonth04 OR	
				BudgetAdjustedFTEs05 != FTEsMonth05 OR BudgetAdjustedFTEs06 != FTEsMonth06 OR BudgetAdjustedFTEs07 != FTEsMonth07 OR BudgetAdjustedFTEs08 != FTEsMonth08 OR	
				BudgetAdjustedFTEs09 != FTEsMonth09 OR BudgetAdjustedFTEs10 != FTEsMonth10 OR	BudgetAdjustedFTEs11 != FTEsMonth11 OR BudgetAdjustedFTEs12 != FTEsMonth12 OR
				TargetFTEsLockType != 4 OR
				BudgetFTEsLockType != 4 
			OR
				(@MonthsLoaded < 1  AND ProjectionAdjustedFTEs01 != CASE WHEN @MonthsLoaded >=  1 THEN ProjectionAdjustedFTEs01 ELSE ProjectedFTEsMonth01 END) OR
				(@MonthsLoaded < 2  AND ProjectionAdjustedFTEs02 != CASE WHEN @MonthsLoaded >=  2 THEN ProjectionAdjustedFTEs02 ELSE ProjectedFTEsMonth02 END) OR
				(@MonthsLoaded < 3  AND ProjectionAdjustedFTEs03 != CASE WHEN @MonthsLoaded >=  3 THEN ProjectionAdjustedFTEs03 ELSE ProjectedFTEsMonth03 END) OR
				(@MonthsLoaded < 4  AND ProjectionAdjustedFTEs04 != CASE WHEN @MonthsLoaded >=  4 THEN ProjectionAdjustedFTEs04 ELSE ProjectedFTEsMonth04 END) OR	
				(@MonthsLoaded < 5  AND ProjectionAdjustedFTEs05 != CASE WHEN @MonthsLoaded >=  5 THEN ProjectionAdjustedFTEs05 ELSE ProjectedFTEsMonth05 END) OR
				(@MonthsLoaded < 6  AND ProjectionAdjustedFTEs06 != CASE WHEN @MonthsLoaded >=  6 THEN ProjectionAdjustedFTEs06 ELSE ProjectedFTEsMonth06 END) OR
				(@MonthsLoaded < 7  AND ProjectionAdjustedFTEs07 != CASE WHEN @MonthsLoaded >=  7 THEN ProjectionAdjustedFTEs07 ELSE ProjectedFTEsMonth07 END) OR
				(@MonthsLoaded < 8  AND ProjectionAdjustedFTEs08 != CASE WHEN @MonthsLoaded >=  8 THEN ProjectionAdjustedFTEs08 ELSE ProjectedFTEsMonth08 END) OR
				(@MonthsLoaded < 9  AND ProjectionAdjustedFTEs09 != CASE WHEN @MonthsLoaded >=  9 THEN ProjectionAdjustedFTEs09 ELSE ProjectedFTEsMonth09 END) OR
				(@MonthsLoaded < 10 AND ProjectionAdjustedFTEs10 != CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE ProjectedFTEsMonth10 END) OR	
				(@MonthsLoaded < 11 AND ProjectionAdjustedFTEs11 != CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE ProjectedFTEsMonth11 END) OR
				(@MonthsLoaded < 12 AND ProjectionAdjustedFTEs12 != CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE ProjectedFTEsMonth12 END) OR
				ProjectionFTEsLockType != 4
			OR
				(@MonthsLoaded < 1  AND InitialProjectionFTEs01 != ProjectedFTEsMonth01) OR
				(@MonthsLoaded < 2  AND InitialProjectionFTEs02 != ProjectedFTEsMonth02) OR
				(@MonthsLoaded < 3  AND InitialProjectionFTEs03 != ProjectedFTEsMonth03) OR
				(@MonthsLoaded < 4  AND InitialProjectionFTEs04 != ProjectedFTEsMonth04) OR	
				(@MonthsLoaded < 5  AND InitialProjectionFTEs05 != ProjectedFTEsMonth05) OR
				(@MonthsLoaded < 6  AND InitialProjectionFTEs06 != ProjectedFTEsMonth06) OR
				(@MonthsLoaded < 7  AND InitialProjectionFTEs07 != ProjectedFTEsMonth07) OR
				(@MonthsLoaded < 8  AND InitialProjectionFTEs08 != ProjectedFTEsMonth08) OR
				(@MonthsLoaded < 9  AND InitialProjectionFTEs09 != ProjectedFTEsMonth09) OR
				(@MonthsLoaded < 10 AND InitialProjectionFTEs10 != ProjectedFTEsMonth10) OR	
				(@MonthsLoaded < 11 AND InitialProjectionFTEs11 != ProjectedFTEsMonth11) OR
				(@MonthsLoaded < 12 AND InitialProjectionFTEs12 != ProjectedFTEsMonth12)
			)
		
	  END
 
 
	-----------------------
	-- Recalculate Hours --
	-----------------------
	UPDATE fsHour 
	SET 
	    InitialBudgetHours01 = InitialBudgetFTEs01 * wh.Month01, 
		InitialBudgetHours02 = InitialBudgetFTEs02 * wh.Month02, 
		InitialBudgetHours03 = InitialBudgetFTEs03 * wh.Month03, 
		InitialBudgetHours04 = InitialBudgetFTEs04 * wh.Month04,	
		InitialBudgetHours05 = InitialBudgetFTEs05 * wh.Month05, 
		InitialBudgetHours06 = InitialBudgetFTEs06 * wh.Month06,
		InitialBudgetHours07 = InitialBudgetFTEs07 * wh.Month07, 
		InitialBudgetHours08 = InitialBudgetFTEs08 * wh.Month08, 
		InitialBudgetHours09 = InitialBudgetFTEs09 * wh.Month09, 
		InitialBudgetHours10 = InitialBudgetFTEs10 * wh.Month10,	
		InitialBudgetHours11 = InitialBudgetFTEs11 * wh.Month11, 
		InitialBudgetHours12 = InitialBudgetFTEs12 * wh.Month12,	
		InitialProjectionHours01 = CASE WHEN @MonthsLoaded >=  1 THEN InitialProjectionHours01 ELSE InitialProjectionFTEs01 * pwh.Month01 END, 
		InitialProjectionHours02 = CASE WHEN @MonthsLoaded >=  2 THEN InitialProjectionHours02 ELSE InitialProjectionFTEs02 * pwh.Month02 END, 
		InitialProjectionHours03 = CASE WHEN @MonthsLoaded >=  3 THEN InitialProjectionHours03 ELSE InitialProjectionFTEs03 * pwh.Month03 END, 
		InitialProjectionHours04 = CASE WHEN @MonthsLoaded >=  4 THEN InitialProjectionHours04 ELSE InitialProjectionFTEs04 * pwh.Month04 END,	
		InitialProjectionHours05 = CASE WHEN @MonthsLoaded >=  5 THEN InitialProjectionHours05 ELSE InitialProjectionFTEs05 * pwh.Month05 END, 
		InitialProjectionHours06 = CASE WHEN @MonthsLoaded >=  6 THEN InitialProjectionHours06 ELSE InitialProjectionFTEs06 * pwh.Month06 END,
		InitialProjectionHours07 = CASE WHEN @MonthsLoaded >=  7 THEN InitialProjectionHours07 ELSE InitialProjectionFTEs07 * pwh.Month07 END, 
		InitialProjectionHours08 = CASE WHEN @MonthsLoaded >=  8 THEN InitialProjectionHours08 ELSE InitialProjectionFTEs08 * pwh.Month08 END, 
		InitialProjectionHours09 = CASE WHEN @MonthsLoaded >=  9 THEN InitialProjectionHours09 ELSE InitialProjectionFTEs09 * pwh.Month09 END, 
		InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionHours10 ELSE InitialProjectionFTEs10 * pwh.Month10 END,	
		InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionHours11 ELSE InitialProjectionFTEs11 * pwh.Month11 END, 
		InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionHours12 ELSE InitialProjectionFTEs12 * pwh.Month12 END,
		TargetAdjustedHours01 = TargetAdjustedFTEs01 * wh.Month01, 
		TargetAdjustedHours02 = TargetAdjustedFTEs02 * wh.Month02, 
		TargetAdjustedHours03 = TargetAdjustedFTEs03 * wh.Month03, 
		TargetAdjustedHours04 = TargetAdjustedFTEs04 * wh.Month04,	
		TargetAdjustedHours05 = TargetAdjustedFTEs05 * wh.Month05, 
		TargetAdjustedHours06 = TargetAdjustedFTEs06 * wh.Month06,
		TargetAdjustedHours07 = TargetAdjustedFTEs07 * wh.Month07, 
		TargetAdjustedHours08 = TargetAdjustedFTEs08 * wh.Month08, 
		TargetAdjustedHours09 = TargetAdjustedFTEs09 * wh.Month09, 
		TargetAdjustedHours10 = TargetAdjustedFTEs10 * wh.Month10,	
		TargetAdjustedHours11 = TargetAdjustedFTEs11 * wh.Month11, 
		TargetAdjustedHours12 = TargetAdjustedFTEs12 * wh.Month12,	
		BudgetAdjustedHours01 = BudgetAdjustedFTEs01 * wh.Month01, 
		BudgetAdjustedHours02 = BudgetAdjustedFTEs02 * wh.Month02, 
		BudgetAdjustedHours03 = BudgetAdjustedFTEs03 * wh.Month03, 
		BudgetAdjustedHours04 = BudgetAdjustedFTEs04 * wh.Month04,	
		BudgetAdjustedHours05 = BudgetAdjustedFTEs05 * wh.Month05, 
		BudgetAdjustedHours06 = BudgetAdjustedFTEs06 * wh.Month06,
		BudgetAdjustedHours07 = BudgetAdjustedFTEs07 * wh.Month07, 
		BudgetAdjustedHours08 = BudgetAdjustedFTEs08 * wh.Month08, 
		BudgetAdjustedHours09 = BudgetAdjustedFTEs09 * wh.Month09, 
		BudgetAdjustedHours10 = BudgetAdjustedFTEs10 * wh.Month10,	
		BudgetAdjustedHours11 = BudgetAdjustedFTEs11 * wh.Month11, 
		BudgetAdjustedHours12 = BudgetAdjustedFTEs12 * wh.Month12,
		ProjectionAdjustedHours01 = CASE WHEN @MonthsLoaded >=  1 THEN ProjectionAdjustedHours01 ELSE ProjectionAdjustedFTEs01 * pwh.Month01 END, 
		ProjectionAdjustedHours02 = CASE WHEN @MonthsLoaded >=  2 THEN ProjectionAdjustedHours02 ELSE ProjectionAdjustedFTEs02 * pwh.Month02 END, 
		ProjectionAdjustedHours03 = CASE WHEN @MonthsLoaded >=  3 THEN ProjectionAdjustedHours03 ELSE ProjectionAdjustedFTEs03 * pwh.Month03 END, 
		ProjectionAdjustedHours04 = CASE WHEN @MonthsLoaded >=  4 THEN ProjectionAdjustedHours04 ELSE ProjectionAdjustedFTEs04 * pwh.Month04 END,	
		ProjectionAdjustedHours05 = CASE WHEN @MonthsLoaded >=  5 THEN ProjectionAdjustedHours05 ELSE ProjectionAdjustedFTEs05 * pwh.Month05 END, 
		ProjectionAdjustedHours06 = CASE WHEN @MonthsLoaded >=  6 THEN ProjectionAdjustedHours06 ELSE ProjectionAdjustedFTEs06 * pwh.Month06 END,
		ProjectionAdjustedHours07 = CASE WHEN @MonthsLoaded >=  7 THEN ProjectionAdjustedHours07 ELSE ProjectionAdjustedFTEs07 * pwh.Month07 END, 
		ProjectionAdjustedHours08 = CASE WHEN @MonthsLoaded >=  8 THEN ProjectionAdjustedHours08 ELSE ProjectionAdjustedFTEs08 * pwh.Month08 END, 
		ProjectionAdjustedHours09 = CASE WHEN @MonthsLoaded >=  9 THEN ProjectionAdjustedHours09 ELSE ProjectionAdjustedFTEs09 * pwh.Month09 END, 
		ProjectionAdjustedHours10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedHours10 ELSE ProjectionAdjustedFTEs10 * pwh.Month10 END,	
		ProjectionAdjustedHours11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedHours11 ELSE ProjectionAdjustedFTEs11 * pwh.Month11 END, 
		ProjectionAdjustedHours12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedHours12 ELSE ProjectionAdjustedFTEs12 * pwh.Month12 END,	
		ProjectionHoursLockType = 4,
		ProjectionHoursLockFlag = 1,
		TargetHoursLockType = 4,
		TargetHoursLockFlag = 1,		
		BudgetHoursLockType = 4,
		BudgetHoursLockFlag = 1
	FROM [fp].[Staffing] fsHour
		INNER JOIN [fw].[DimDepartment] dept ON fsHour.DepartmentID = dept.DepartmentID
		INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = @BudgetYear AND wh.WorkWeekID = dept.WorkWeekID
		INNER JOIN [client].[FactWorkingHoursPerMonth] pwh ON pwh.FiscalYearID = @ProjectedYear AND pwh.WorkWeekID = dept.WorkWeekID
		INNER JOIN #tmpRosterRolledUp Filter ON
					fsHour.DepartmentID = Filter.DepartmentID 
					AND fsHour.JobCodeID = Filter.JobCodeID
					AND fsHour.PayCodeGroupID = Filter.PayCodeGroupID
					AND fsHour.EntityID = Filter.EntityID				
	WHERE fsHour.BudgetConfigID = @BudgetConfigID 
        AND fsHour.VariabilityID = 1 
		AND (
				TargetAdjustedHours01 != TargetAdjustedFTEs01 * wh.Month01 OR 
				TargetAdjustedHours02 != TargetAdjustedFTEs02 * wh.Month02 OR 
				TargetAdjustedHours03 != TargetAdjustedFTEs03 * wh.Month03 OR 
				TargetAdjustedHours04 != TargetAdjustedFTEs04 * wh.Month04 OR	
				TargetAdjustedHours05 != TargetAdjustedFTEs05 * wh.Month05 OR 
				TargetAdjustedHours06 != TargetAdjustedFTEs06 * wh.Month06 OR 
				TargetAdjustedHours07 != TargetAdjustedFTEs07 * wh.Month07 OR 
				TargetAdjustedHours08 != TargetAdjustedFTEs08 * wh.Month08 OR	
				TargetAdjustedHours09 != TargetAdjustedFTEs09 * wh.Month09 OR 
				TargetAdjustedHours10 != TargetAdjustedFTEs10 * wh.Month10 OR	
				TargetAdjustedHours11 != TargetAdjustedFTEs11 * wh.Month11 OR 
				TargetAdjustedHours12 != TargetAdjustedFTEs12 * wh.Month12 OR
				BudgetAdjustedHours01 != BudgetAdjustedFTEs01 * wh.Month01 OR 
				BudgetAdjustedHours02 != BudgetAdjustedFTEs02 * wh.Month02 OR 
				BudgetAdjustedHours03 != BudgetAdjustedFTEs03 * wh.Month03 OR 
				BudgetAdjustedHours04 != BudgetAdjustedFTEs04 * wh.Month04 OR	
				BudgetAdjustedHours05 != BudgetAdjustedFTEs05 * wh.Month05 OR 
				BudgetAdjustedHours06 != BudgetAdjustedFTEs06 * wh.Month06 OR 
				BudgetAdjustedHours07 != BudgetAdjustedFTEs07 * wh.Month07 OR 
				BudgetAdjustedHours08 != BudgetAdjustedFTEs08 * wh.Month08 OR	
				BudgetAdjustedHours09 != BudgetAdjustedFTEs09 * wh.Month09 OR 
				BudgetAdjustedHours10 != BudgetAdjustedFTEs10 * wh.Month10 OR	
				BudgetAdjustedHours11 != BudgetAdjustedFTEs11 * wh.Month11 OR 
				BudgetAdjustedHours12 != BudgetAdjustedFTEs12 * wh.Month12 OR
				TargetHoursLockType != 4 OR
				BudgetHoursLockType != 4
			OR
				(@MonthsLoaded < 1  AND ProjectionAdjustedHours01 != ProjectionAdjustedFTEs01 * pwh.Month01) OR
				(@MonthsLoaded < 2  AND ProjectionAdjustedHours02 != ProjectionAdjustedFTEs02 * pwh.Month02) OR
				(@MonthsLoaded < 3  AND ProjectionAdjustedHours03 != ProjectionAdjustedFTEs03 * pwh.Month03) OR
				(@MonthsLoaded < 4  AND ProjectionAdjustedHours04 != ProjectionAdjustedFTEs04 * pwh.Month04) OR	
				(@MonthsLoaded < 5  AND ProjectionAdjustedHours05 != ProjectionAdjustedFTEs05 * pwh.Month05) OR
				(@MonthsLoaded < 6  AND ProjectionAdjustedHours06 != ProjectionAdjustedFTEs06 * pwh.Month06) OR
				(@MonthsLoaded < 7  AND ProjectionAdjustedHours07 != ProjectionAdjustedFTEs07 * pwh.Month07) OR
				(@MonthsLoaded < 8  AND ProjectionAdjustedHours08 != ProjectionAdjustedFTEs08 * pwh.Month08) OR
				(@MonthsLoaded < 9  AND ProjectionAdjustedHours09 != ProjectionAdjustedFTEs09 * pwh.Month09) OR
				(@MonthsLoaded < 10 AND ProjectionAdjustedHours10 != ProjectionAdjustedFTEs10 * pwh.Month10) OR	
				(@MonthsLoaded < 11 AND ProjectionAdjustedHours11 != ProjectionAdjustedFTEs11 * pwh.Month11) OR
				(@MonthsLoaded < 12 AND ProjectionAdjustedHours12 != ProjectionAdjustedFTEs12 * pwh.Month12) OR
				ProjectionHoursLockType != 4
			OR
				InitialBudgetHours01 != InitialBudgetFTEs01 * wh.Month01 OR 
				InitialBudgetHours02 != InitialBudgetFTEs02 * wh.Month02 OR 
				InitialBudgetHours03 != InitialBudgetFTEs03 * wh.Month03 OR 
				InitialBudgetHours04 != InitialBudgetFTEs04 * wh.Month04 OR	
				InitialBudgetHours05 != InitialBudgetFTEs05 * wh.Month05 OR 
				InitialBudgetHours06 != InitialBudgetFTEs06 * wh.Month06 OR 
				InitialBudgetHours07 != InitialBudgetFTEs07 * wh.Month07 OR 
				InitialBudgetHours08 != InitialBudgetFTEs08 * wh.Month08 OR	
				InitialBudgetHours09 != InitialBudgetFTEs09 * wh.Month09 OR 
				InitialBudgetHours10 != InitialBudgetFTEs10 * wh.Month10 OR	
				InitialBudgetHours11 != InitialBudgetFTEs11 * wh.Month11 OR 
				InitialBudgetHours12 != InitialBudgetFTEs12 * wh.Month12 OR
				(@MonthsLoaded < 1  AND InitialProjectionHours01 != InitialProjectionFTEs01 * pwh.Month01) OR
				(@MonthsLoaded < 2  AND InitialProjectionHours02 != InitialProjectionFTEs02 * pwh.Month02) OR
				(@MonthsLoaded < 3  AND InitialProjectionHours03 != InitialProjectionFTEs03 * pwh.Month03) OR
				(@MonthsLoaded < 4  AND InitialProjectionHours04 != InitialProjectionFTEs04 * pwh.Month04) OR	
				(@MonthsLoaded < 5  AND InitialProjectionHours05 != InitialProjectionFTEs05 * pwh.Month05) OR
				(@MonthsLoaded < 6  AND InitialProjectionHours06 != InitialProjectionFTEs06 * pwh.Month06) OR
				(@MonthsLoaded < 7  AND InitialProjectionHours07 != InitialProjectionFTEs07 * pwh.Month07) OR
				(@MonthsLoaded < 8  AND InitialProjectionHours08 != InitialProjectionFTEs08 * pwh.Month08) OR
				(@MonthsLoaded < 9  AND InitialProjectionHours09 != InitialProjectionFTEs09 * pwh.Month09) OR
				(@MonthsLoaded < 10 AND InitialProjectionHours10 != InitialProjectionFTEs10 * pwh.Month10) OR	
				(@MonthsLoaded < 11 AND InitialProjectionHours11 != InitialProjectionFTEs11 * pwh.Month11) OR
				(@MonthsLoaded < 12 AND InitialProjectionHours12 != InitialProjectionFTEs12 * pwh.Month12)
			)
 
	
 
	--------------------
	-- Update Dollars --
	--------------------
	UPDATE fs 
	SET 
	    InitialBudgetDollars01 = InitialDollarsMonth01, InitialBudgetDollars02 = InitialDollarsMonth02, InitialBudgetDollars03 = InitialDollarsMonth03, InitialBudgetDollars04 = InitialDollarsMonth04,	
		InitialBudgetDollars05 = InitialDollarsMonth05, InitialBudgetDollars06 = InitialDollarsMonth06, InitialBudgetDollars07 = InitialDollarsMonth07, InitialBudgetDollars08 = InitialDollarsMonth08, 
		InitialBudgetDollars09 = InitialDollarsMonth09, InitialBudgetDollars10 = InitialDollarsMonth10, InitialBudgetDollars11 = InitialDollarsMonth11, InitialBudgetDollars12 = InitialDollarsMonth12,
		InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN InitialProjectionDollars01  ELSE ProjectedDollarsMonth01 END, 
		InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionDollars02  ELSE ProjectedDollarsMonth02 END, 
		InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionDollars03  ELSE ProjectedDollarsMonth03 END, 
		InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionDollars04  ELSE ProjectedDollarsMonth04 END,	
		InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionDollars05  ELSE ProjectedDollarsMonth05 END, 
		InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionDollars06  ELSE ProjectedDollarsMonth06 END, 
		InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionDollars07  ELSE ProjectedDollarsMonth07 END, 
		InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionDollars08  ELSE ProjectedDollarsMonth08 END, 
		InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionDollars09  ELSE ProjectedDollarsMonth09 END, 
		InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionDollars10 ELSE ProjectedDollarsMonth10 END,	
		InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionDollars11 ELSE ProjectedDollarsMonth11 END, 
		InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionDollars12 ELSE ProjectedDollarsMonth12 END,
		TargetAdjustedDollars01 = DollarsMonth01, TargetAdjustedDollars02 = DollarsMonth02, TargetAdjustedDollars03 = DollarsMonth03, TargetAdjustedDollars04 = DollarsMonth04,	TargetAdjustedDollars05 = DollarsMonth05, TargetAdjustedDollars06 = DollarsMonth06,
		TargetAdjustedDollars07 = DollarsMonth07, TargetAdjustedDollars08 = DollarsMonth08, TargetAdjustedDollars09 = DollarsMonth09, TargetAdjustedDollars10 = DollarsMonth10,	TargetAdjustedDollars11 = DollarsMonth11, TargetAdjustedDollars12 = DollarsMonth12,
		BudgetAdjustedDollars01 = DollarsMonth01, BudgetAdjustedDollars02 = DollarsMonth02, BudgetAdjustedDollars03 = DollarsMonth03, BudgetAdjustedDollars04 = DollarsMonth04,	BudgetAdjustedDollars05 = DollarsMonth05, BudgetAdjustedDollars06 = DollarsMonth06,
		BudgetAdjustedDollars07 = DollarsMonth07, BudgetAdjustedDollars08 = DollarsMonth08, BudgetAdjustedDollars09 = DollarsMonth09, BudgetAdjustedDollars10 = DollarsMonth10,	BudgetAdjustedDollars11 = DollarsMonth11, BudgetAdjustedDollars12 = DollarsMonth12,
		ProjectionAdjustedDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedDollars01 ELSE ProjectedDollarsMonth01 END, 
		ProjectionAdjustedDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedDollars02 ELSE ProjectedDollarsMonth02 END, 
		ProjectionAdjustedDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedDollars03 ELSE ProjectedDollarsMonth03 END, 
		ProjectionAdjustedDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedDollars04 ELSE ProjectedDollarsMonth04 END,	
		ProjectionAdjustedDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedDollars05 ELSE ProjectedDollarsMonth05 END, 
		ProjectionAdjustedDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedDollars06 ELSE ProjectedDollarsMonth06 END,
		ProjectionAdjustedDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedDollars07 ELSE ProjectedDollarsMonth07 END, 
		ProjectionAdjustedDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedDollars08 ELSE ProjectedDollarsMonth08 END, 
		ProjectionAdjustedDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedDollars09 ELSE ProjectedDollarsMonth09 END, 
		ProjectionAdjustedDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedDollars10 ELSE ProjectedDollarsMonth10 END,	
		ProjectionAdjustedDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedDollars11 ELSE ProjectedDollarsMonth11 END, 
		ProjectionAdjustedDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedDollars12 ELSE ProjectedDollarsMonth12 END,
		ProjectionDollarsLockFlag = 1,
		ProjectionDollarsLockType = 4,
		TargetDollarsLockFlag = 1,
		TargetDollarsLockType = 4,
		BudgetDollarsLockFlag = 1,
		BudgetDollarsLockType = 4
	FROM [fp].[Staffing] fs
		INNER JOIN #tmpRosterRolledUp rb
			ON fs.JobCodeID = rb.JobCodeID 
			AND fs.DepartmentID = rb.DepartmentID 
			AND fs.PayCodeGroupID = rb.PayCodeGroupID 
			AND fs.EntityID = rb.EntityID
	WHERE fs.BudgetConfigID = @BudgetConfigID 
		AND fs.VariabilityID = 1
		AND (
				TargetAdjustedDollars01 != DollarsMonth01 OR 
				TargetAdjustedDollars02 != DollarsMonth02 OR 
				TargetAdjustedDollars03 != DollarsMonth03 OR 
				TargetAdjustedDollars04 != DollarsMonth04 OR	
				TargetAdjustedDollars05 != DollarsMonth05 OR 
				TargetAdjustedDollars06 != DollarsMonth06 OR 
				TargetAdjustedDollars07 != DollarsMonth07 OR 
				TargetAdjustedDollars08 != DollarsMonth08 OR	
				TargetAdjustedDollars09 != DollarsMonth09 OR 
				TargetAdjustedDollars10 != DollarsMonth10 OR	
				TargetAdjustedDollars11 != DollarsMonth11 OR 
				TargetAdjustedDollars12 != DollarsMonth12 OR
				BudgetAdjustedDollars01 != DollarsMonth01 OR 
				BudgetAdjustedDollars02 != DollarsMonth02 OR 
				BudgetAdjustedDollars03 != DollarsMonth03 OR 
				BudgetAdjustedDollars04 != DollarsMonth04 OR	
				BudgetAdjustedDollars05 != DollarsMonth05 OR 
				BudgetAdjustedDollars06 != DollarsMonth06 OR 
				BudgetAdjustedDollars07 != DollarsMonth07 OR 
				BudgetAdjustedDollars08 != DollarsMonth08 OR	
				BudgetAdjustedDollars09 != DollarsMonth09 OR 
				BudgetAdjustedDollars10 != DollarsMonth10 OR	
				BudgetAdjustedDollars11 != DollarsMonth11 OR 
				BudgetAdjustedDollars12 != DollarsMonth12 OR
				TargetDollarsLockType != 4 OR
				BudgetDollarsLockType != 4
			OR
				(@MonthsLoaded < 1  AND ProjectionAdjustedDollars01 != ProjectedDollarsMonth01) OR
				(@MonthsLoaded < 2  AND ProjectionAdjustedDollars02 != ProjectedDollarsMonth02) OR
				(@MonthsLoaded < 3  AND ProjectionAdjustedDollars03 != ProjectedDollarsMonth03) OR
				(@MonthsLoaded < 4  AND ProjectionAdjustedDollars04 != ProjectedDollarsMonth04) OR	
				(@MonthsLoaded < 5  AND ProjectionAdjustedDollars05 != ProjectedDollarsMonth05) OR
				(@MonthsLoaded < 6  AND ProjectionAdjustedDollars06 != ProjectedDollarsMonth06) OR
				(@MonthsLoaded < 7  AND ProjectionAdjustedDollars07 != ProjectedDollarsMonth07) OR
				(@MonthsLoaded < 8  AND ProjectionAdjustedDollars08 != ProjectedDollarsMonth08) OR
				(@MonthsLoaded < 9  AND ProjectionAdjustedDollars09 != ProjectedDollarsMonth09) OR
				(@MonthsLoaded < 10 AND ProjectionAdjustedDollars10 != ProjectedDollarsMonth10) OR	
				(@MonthsLoaded < 11 AND ProjectionAdjustedDollars11 != ProjectedDollarsMonth11) OR
				(@MonthsLoaded < 12 AND ProjectionAdjustedDollars12 != ProjectedDollarsMonth12) OR
				ProjectionDollarsLockType != 4
			OR
				InitialBudgetDollars01 != InitialDollarsMonth01 OR 
				InitialBudgetDollars02 != InitialDollarsMonth02 OR 
				InitialBudgetDollars03 != InitialDollarsMonth03 OR 
				InitialBudgetDollars04 != InitialDollarsMonth04 OR	
				InitialBudgetDollars05 != InitialDollarsMonth05 OR 
				InitialBudgetDollars06 != InitialDollarsMonth06 OR 
				InitialBudgetDollars07 != InitialDollarsMonth07 OR 
				InitialBudgetDollars08 != InitialDollarsMonth08 OR	
				InitialBudgetDollars09 != InitialDollarsMonth09 OR 
				InitialBudgetDollars10 != InitialDollarsMonth10 OR	
				InitialBudgetDollars11 != InitialDollarsMonth11 OR 
				InitialBudgetDollars12 != InitialDollarsMonth12 OR
				(@MonthsLoaded < 1  AND InitialProjectionDollars01 != ProjectedDollarsMonth01) OR
				(@MonthsLoaded < 2  AND InitialProjectionDollars02 != ProjectedDollarsMonth02) OR
				(@MonthsLoaded < 3  AND InitialProjectionDollars03 != ProjectedDollarsMonth03) OR
				(@MonthsLoaded < 4  AND InitialProjectionDollars04 != ProjectedDollarsMonth04) OR	
				(@MonthsLoaded < 5  AND InitialProjectionDollars05 != ProjectedDollarsMonth05) OR
				(@MonthsLoaded < 6  AND InitialProjectionDollars06 != ProjectedDollarsMonth06) OR
				(@MonthsLoaded < 7  AND InitialProjectionDollars07 != ProjectedDollarsMonth07) OR
				(@MonthsLoaded < 8  AND InitialProjectionDollars08 != ProjectedDollarsMonth08) OR
				(@MonthsLoaded < 9  AND InitialProjectionDollars09 != ProjectedDollarsMonth09) OR
				(@MonthsLoaded < 10 AND InitialProjectionDollars10 != ProjectedDollarsMonth10) OR	
				(@MonthsLoaded < 11 AND InitialProjectionDollars11 != ProjectedDollarsMonth11) OR
				(@MonthsLoaded < 12 AND InitialProjectionDollars12 != ProjectedDollarsMonth12)
		)
	
	
	----------------------
	-- Update Wage Rate --  (corresponds to line 1144 in rollback)
	----------------------
	UPDATE wageRate
	SET
	    wageRate.InitialBudget01 = fs.InitialBudget01,
		wageRate.InitialBudget02 = fs.InitialBudget02,
		wageRate.InitialBudget03 = fs.InitialBudget03,
		wageRate.InitialBudget04 = fs.InitialBudget04,
		wageRate.InitialBudget05 = fs.InitialBudget05,
		wageRate.InitialBudget06 = fs.InitialBudget06,
		wageRate.InitialBudget07 = fs.InitialBudget07,
		wageRate.InitialBudget08 = fs.InitialBudget08,
		wageRate.InitialBudget09 = fs.InitialBudget09,
		wageRate.InitialBudget10 = fs.InitialBudget10,
		wageRate.InitialBudget11 = fs.InitialBudget11,
		wageRate.InitialBudget12 = fs.InitialBudget12,
		
		wageRate.InitialProjection01 = CASE WHEN @MonthsLoaded >=  1 THEN WageRate.InitialProjection01 ELSE fs.InitialProjection01 END, 
		wageRate.InitialProjection02 = CASE WHEN @MonthsLoaded >=  2 THEN WageRate.InitialProjection02 ELSE fs.InitialProjection02 END, 
		wageRate.InitialProjection03 = CASE WHEN @MonthsLoaded >=  3 THEN WageRate.InitialProjection03 ELSE fs.InitialProjection03 END, 
		wageRate.InitialProjection04 = CASE WHEN @MonthsLoaded >=  4 THEN WageRate.InitialProjection04 ELSE fs.InitialProjection04 END,	
		wageRate.InitialProjection05 = CASE WHEN @MonthsLoaded >=  5 THEN WageRate.InitialProjection05 ELSE fs.InitialProjection05 END, 
		wageRate.InitialProjection06 = CASE WHEN @MonthsLoaded >=  6 THEN WageRate.InitialProjection06 ELSE fs.InitialProjection06 END,
		wageRate.InitialProjection07 = CASE WHEN @MonthsLoaded >=  7 THEN WageRate.InitialProjection07 ELSE fs.InitialProjection07 END, 
		wageRate.InitialProjection08 = CASE WHEN @MonthsLoaded >=  8 THEN WageRate.InitialProjection08 ELSE fs.InitialProjection08 END, 
		wageRate.InitialProjection09 = CASE WHEN @MonthsLoaded >=  9 THEN WageRate.InitialProjection09 ELSE fs.InitialProjection09 END, 
		wageRate.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN WageRate.InitialProjection10 ELSE fs.InitialProjection10 END,	
		wageRate.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN WageRate.InitialProjection11 ELSE fs.InitialProjection11 END, 
		wageRate.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN WageRate.InitialProjection12 ELSE fs.InitialProjection12 END,	
	

		TargetAdjusted01 = fs.TargetAdjusted01,
		TargetAdjusted02 = fs.TargetAdjusted02,
		TargetAdjusted03 = fs.TargetAdjusted03,
		TargetAdjusted04 = fs.TargetAdjusted04,
		TargetAdjusted05 = fs.TargetAdjusted05,
		TargetAdjusted06 = fs.TargetAdjusted06,
		TargetAdjusted07 = fs.TargetAdjusted07,
		TargetAdjusted08 = fs.TargetAdjusted08,
		TargetAdjusted09 = fs.TargetAdjusted09,
		TargetAdjusted10 = fs.TargetAdjusted10,
		TargetAdjusted11 = fs.TargetAdjusted11,
		TargetAdjusted12 = fs.TargetAdjusted12,

		BudgetAdjusted01 = fs.BudgetAdjusted01,
		BudgetAdjusted02 = fs.BudgetAdjusted02,
		BudgetAdjusted03 = fs.BudgetAdjusted03,
		BudgetAdjusted04 = fs.BudgetAdjusted04,
		BudgetAdjusted05 = fs.BudgetAdjusted05,
		BudgetAdjusted06 = fs.BudgetAdjusted06,
		BudgetAdjusted07 = fs.BudgetAdjusted07,
		BudgetAdjusted08 = fs.BudgetAdjusted08,
		BudgetAdjusted09 = fs.BudgetAdjusted09,
		BudgetAdjusted10 = fs.BudgetAdjusted10,
		BudgetAdjusted11 = fs.BudgetAdjusted11,
		BudgetAdjusted12 = fs.BudgetAdjusted12,

		ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >=  1 THEN wageRate.ProjectionAdjusted01 ELSE fs.ProjectionAdjusted01 END, 
		ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >=  2 THEN WageRate.ProjectionAdjusted02 ELSE fs.ProjectionAdjusted02 END, 
		ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >=  3 THEN WageRate.ProjectionAdjusted03 ELSE fs.ProjectionAdjusted03 END, 
		ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >=  4 THEN WageRate.ProjectionAdjusted04 ELSE fs.ProjectionAdjusted04 END,	
		ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >=  5 THEN WageRate.ProjectionAdjusted05 ELSE fs.ProjectionAdjusted05 END, 
		ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >=  6 THEN WageRate.ProjectionAdjusted06 ELSE fs.ProjectionAdjusted06 END,
		ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >=  7 THEN WageRate.ProjectionAdjusted07 ELSE fs.ProjectionAdjusted07 END, 
		ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >=  8 THEN WageRate.ProjectionAdjusted08 ELSE fs.ProjectionAdjusted08 END, 
		ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >=  9 THEN WageRate.ProjectionAdjusted09 ELSE fs.ProjectionAdjusted09 END, 
		ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN WageRate.ProjectionAdjusted10 ELSE fs.ProjectionAdjusted10 END,	
		ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN WageRate.ProjectionAdjusted11 ELSE fs.ProjectionAdjusted11 END, 
		ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN WageRate.ProjectionAdjusted12 ELSE fs.ProjectionAdjusted12 END,		
		
		TargetWageRateLockFlag = 1,
		TargetWageRateLockType = 4,
		BudgetWageRateLockFlag = 1,
		BudgetWageRateLockType = 4,
		ProjectionWageRateLockFlag = 1,
		ProjectionWageRateLockType = 4
	FROM [fp].[StaffingWageRate] wageRate
	INNER JOIN (
		SELECT StaffingWageRateID, -- doing this here so we don't have to run the calcs twice, once in the set above, and once in the where below
		
		COALESCE((InitialBudgetDollars01) / (NULLIF(InitialBudgetHours01, 0)), 0) as InitialBudget01, COALESCE((InitialBudgetDollars02) / (NULLIF(InitialBudgetHours02, 0)), 0) as InitialBudget02, COALESCE((InitialBudgetDollars03) / (NULLIF(InitialBudgetHours03, 0)), 0) as InitialBudget03, COALESCE((InitialBudgetDollars04) / (NULLIF(InitialBudgetHours04, 0)), 0) as InitialBudget04,
		COALESCE((InitialBudgetDollars05) / (NULLIF(InitialBudgetHours05, 0)), 0) as InitialBudget05, COALESCE((InitialBudgetDollars06) / (NULLIF(InitialBudgetHours06, 0)), 0) as InitialBudget06, COALESCE((InitialBudgetDollars07) / (NULLIF(InitialBudgetHours07, 0)), 0) as InitialBudget07, COALESCE((InitialBudgetDollars08) / (NULLIF(InitialBudgetHours08, 0)), 0) as InitialBudget08,
		COALESCE((InitialBudgetDollars09) / (NULLIF(InitialBudgetHours09, 0)), 0) as InitialBudget09, COALESCE((InitialBudgetDollars10) / (NULLIF(InitialBudgetHours10, 0)), 0) as InitialBudget10, COALESCE((InitialBudgetDollars11) / (NULLIF(InitialBudgetHours11, 0)), 0) as InitialBudget11, COALESCE((InitialBudgetDollars12) / (NULLIF(InitialBudgetHours12, 0)), 0) as InitialBudget12,
		
		COALESCE((InitialProjectionDollars01) / (NULLIF(InitialProjectionHours01, 0)), 0) as InitialProjection01, COALESCE((InitialProjectionDollars02) / (NULLIF(InitialProjectionHours02, 0)), 0) as InitialProjection02, COALESCE((InitialProjectionDollars03) / (NULLIF(InitialProjectionHours03, 0)), 0) as InitialProjection03, COALESCE((InitialProjectionDollars04) / (NULLIF(InitialProjectionHours04, 0)), 0) as InitialProjection04,
		COALESCE((InitialProjectionDollars05) / (NULLIF(InitialProjectionHours05, 0)), 0) as InitialProjection05, COALESCE((InitialProjectionDollars06) / (NULLIF(InitialProjectionHours06, 0)), 0) as InitialProjection06, COALESCE((InitialProjectionDollars07) / (NULLIF(InitialProjectionHours07, 0)), 0) as InitialProjection07, COALESCE((InitialProjectionDollars08) / (NULLIF(InitialProjectionHours08, 0)), 0) as InitialProjection08,
		COALESCE((InitialProjectionDollars09) / (NULLIF(InitialProjectionHours09, 0)), 0) as InitialProjection09, COALESCE((InitialProjectionDollars10) / (NULLIF(InitialProjectionHours10, 0)), 0) as InitialProjection10, COALESCE((InitialProjectionDollars11) / (NULLIF(InitialProjectionHours11, 0)), 0) as InitialProjection11, COALESCE((InitialProjectionDollars12) / (NULLIF(InitialProjectionHours12, 0)), 0) as InitialProjection12,
	
	    COALESCE((TargetAdjustedDollars01) / (NULLIF(TargetAdjustedHours01, 0)), 0) as TargetAdjusted01, COALESCE((TargetAdjustedDollars02 / NULLIF(TargetAdjustedHours02, 0)), 0) as TargetAdjusted02, COALESCE((TargetAdjustedDollars03 / NULLIF(TargetAdjustedHours03, 0)), 0) as TargetAdjusted03, COALESCE((TargetAdjustedDollars04 / NULLIF(TargetAdjustedHours04, 0)), 0) as TargetAdjusted04,
		COALESCE((TargetAdjustedDollars05) / (NULLIF(TargetAdjustedHours05, 0)), 0) as TargetAdjusted05, COALESCE((TargetAdjustedDollars06 / NULLIF(TargetAdjustedHours06, 0)), 0) as TargetAdjusted06, COALESCE((TargetAdjustedDollars07 / NULLIF(TargetAdjustedHours07, 0)), 0) as TargetAdjusted07, COALESCE((TargetAdjustedDollars08 / NULLIF(TargetAdjustedHours08, 0)), 0) as TargetAdjusted08,
		COALESCE((TargetAdjustedDollars09) / (NULLIF(TargetAdjustedHours09, 0)), 0) as TargetAdjusted09, COALESCE((TargetAdjustedDollars10 / NULLIF(TargetAdjustedHours10, 0)), 0) as TargetAdjusted10, COALESCE((TargetAdjustedDollars11 / NULLIF(TargetAdjustedHours11, 0)), 0) as TargetAdjusted11, COALESCE((TargetAdjustedDollars12 / NULLIF(TargetAdjustedHours12, 0)), 0) as TargetAdjusted12,
	
	    COALESCE((BudgetAdjustedDollars01) / (NULLIF(BudgetAdjustedHours01, 0)), 0) as BudgetAdjusted01, COALESCE((BudgetAdjustedDollars02 / NULLIF(BudgetAdjustedHours02, 0)), 0) as BudgetAdjusted02, COALESCE((BudgetAdjustedDollars03 / NULLIF(BudgetAdjustedHours03, 0)), 0) as BudgetAdjusted03, COALESCE((BudgetAdjustedDollars04 / NULLIF(BudgetAdjustedHours04, 0)), 0) as BudgetAdjusted04,
		COALESCE((BudgetAdjustedDollars05) / (NULLIF(BudgetAdjustedHours05, 0)), 0) as BudgetAdjusted05, COALESCE((BudgetAdjustedDollars06 / NULLIF(BudgetAdjustedHours06, 0)), 0) as BudgetAdjusted06, COALESCE((BudgetAdjustedDollars07 / NULLIF(BudgetAdjustedHours07, 0)), 0) as BudgetAdjusted07, COALESCE((BudgetAdjustedDollars08 / NULLIF(BudgetAdjustedHours08, 0)), 0) as BudgetAdjusted08,
		COALESCE((BudgetAdjustedDollars09) / (NULLIF(BudgetAdjustedHours09, 0)), 0) as BudgetAdjusted09, COALESCE((BudgetAdjustedDollars10 / NULLIF(BudgetAdjustedHours10, 0)), 0) as BudgetAdjusted10, COALESCE((BudgetAdjustedDollars11 / NULLIF(BudgetAdjustedHours11, 0)), 0) as BudgetAdjusted11, COALESCE((BudgetAdjustedDollars12 / NULLIF(BudgetAdjustedHours12, 0)), 0) as BudgetAdjusted12,
	
	    COALESCE((ProjectionAdjustedDollars01) / (NULLIF(ProjectionAdjustedHours01, 0)), 0) as ProjectionAdjusted01, COALESCE((ProjectionAdjustedDollars02 / NULLIF(ProjectionAdjustedHours02, 0)), 0) as ProjectionAdjusted02, COALESCE((ProjectionAdjustedDollars03 / NULLIF(ProjectionAdjustedHours03, 0)), 0) as ProjectionAdjusted03, COALESCE((ProjectionAdjustedDollars04 / NULLIF(ProjectionAdjustedHours04, 0)), 0) as ProjectionAdjusted04,
		COALESCE((ProjectionAdjustedDollars05) / (NULLIF(ProjectionAdjustedHours05, 0)), 0) as ProjectionAdjusted05, COALESCE((ProjectionAdjustedDollars06 / NULLIF(ProjectionAdjustedHours06, 0)), 0) as ProjectionAdjusted06, COALESCE((ProjectionAdjustedDollars07 / NULLIF(ProjectionAdjustedHours07, 0)), 0) as ProjectionAdjusted07, COALESCE((ProjectionAdjustedDollars08 / NULLIF(ProjectionAdjustedHours08, 0)), 0) as ProjectionAdjusted08,
		COALESCE((ProjectionAdjustedDollars09) / (NULLIF(ProjectionAdjustedHours09, 0)), 0) as ProjectionAdjusted09, COALESCE((ProjectionAdjustedDollars10 / NULLIF(ProjectionAdjustedHours10, 0)), 0) as ProjectionAdjusted10, COALESCE((ProjectionAdjustedDollars11 / NULLIF(ProjectionAdjustedHours11, 0)), 0) as ProjectionAdjusted11, COALESCE((ProjectionAdjustedDollars12 / NULLIF(ProjectionAdjustedHours12, 0)), 0) as ProjectionAdjusted12
	
		FROM [fp].[Staffing] fs
				INNER JOIN #tmpRosterRolledUp rb  -- keep this here to make sure we only update wage rates related to roster
					ON fs.JobCodeID = rb.JobCodeID 
					AND fs.DepartmentID = rb.DepartmentID 
					AND fs.PayCodeGroupID = rb.PayCodeGroupID 
					AND fs.EntityID = rb.EntityID
			 WHERE fs.BudgetConfigID = @BudgetConfigID AND fs.VariabilityID = 1
	 ) fs ON wageRate.StaffingWageRateID = fs.StaffingWageRateID	
	WHERE  
				wageRate.TargetAdjusted01 != fs.TargetAdjusted01 OR 
				wageRate.TargetAdjusted02 != fs.TargetAdjusted02 OR 
				wageRate.TargetAdjusted03 != fs.TargetAdjusted03 OR 
				wageRate.TargetAdjusted04 != fs.TargetAdjusted04 OR	
				wageRate.TargetAdjusted05 != fs.TargetAdjusted05 OR 
				wageRate.TargetAdjusted06 != fs.TargetAdjusted06 OR 
				wageRate.TargetAdjusted07 != fs.TargetAdjusted07 OR 
				wageRate.TargetAdjusted01 != fs.TargetAdjusted01 OR 
				wageRate.TargetAdjusted08 != fs.TargetAdjusted08 OR	
				wageRate.TargetAdjusted09 != fs.TargetAdjusted09 OR 
				wageRate.TargetAdjusted10 != fs.TargetAdjusted10 OR	
				wageRate.TargetAdjusted11 != fs.TargetAdjusted11 OR 
				wageRate.TargetAdjusted12 != fs.TargetAdjusted12 OR
				wageRate.BudgetAdjusted01 != fs.BudgetAdjusted01 OR 
				wageRate.BudgetAdjusted02 != fs.BudgetAdjusted02 OR 
				wageRate.BudgetAdjusted03 != fs.BudgetAdjusted03 OR 
				wageRate.BudgetAdjusted04 != fs.BudgetAdjusted04 OR	
				wageRate.BudgetAdjusted05 != fs.BudgetAdjusted05 OR 
				wageRate.BudgetAdjusted06 != fs.BudgetAdjusted06 OR 
				wageRate.BudgetAdjusted07 != fs.BudgetAdjusted07 OR 
				wageRate.BudgetAdjusted01 != fs.BudgetAdjusted01 OR 
				wageRate.BudgetAdjusted08 != fs.BudgetAdjusted08 OR	
				wageRate.BudgetAdjusted09 != fs.BudgetAdjusted09 OR 
				wageRate.BudgetAdjusted10 != fs.BudgetAdjusted10 OR	
				wageRate.BudgetAdjusted11 != fs.BudgetAdjusted11 OR 
				wageRate.BudgetAdjusted12 != fs.BudgetAdjusted12 OR
				wageRate.TargetWageRateLockType != 4 OR
				wageRate.BudgetWageRateLockType != 4
			OR
				(@MonthsLoaded < 1  AND wageRate.ProjectionAdjusted01 != fs.ProjectionAdjusted01) OR
				(@MonthsLoaded < 2  AND wageRate.ProjectionAdjusted02 != fs.ProjectionAdjusted02) OR
				(@MonthsLoaded < 3  AND wageRate.ProjectionAdjusted03 != fs.ProjectionAdjusted03) OR
				(@MonthsLoaded < 4  AND wageRate.ProjectionAdjusted04 != fs.ProjectionAdjusted04) OR	
				(@MonthsLoaded < 5  AND wageRate.ProjectionAdjusted05 != fs.ProjectionAdjusted05) OR
				(@MonthsLoaded < 6  AND wageRate.ProjectionAdjusted06 != fs.ProjectionAdjusted06) OR
				(@MonthsLoaded < 7  AND wageRate.ProjectionAdjusted07 != fs.ProjectionAdjusted07) OR
				(@MonthsLoaded < 8  AND wageRate.ProjectionAdjusted08 != fs.ProjectionAdjusted08) OR
				(@MonthsLoaded < 9  AND wageRate.ProjectionAdjusted09 != fs.ProjectionAdjusted09) OR
				(@MonthsLoaded < 10 AND wageRate.ProjectionAdjusted10 != fs.ProjectionAdjusted10) OR	
				(@MonthsLoaded < 11 AND wageRate.ProjectionAdjusted11 != fs.ProjectionAdjusted11) OR
				(@MonthsLoaded < 12 AND wageRate.ProjectionAdjusted12 != fs.ProjectionAdjusted12) OR
				wageRate.ProjectionWageRateLockType != 4
			OR		
				wageRate.InitialBudget01 != fs.InitialBudget01 OR 
				wageRate.InitialBudget02 != fs.InitialBudget02 OR 
				wageRate.InitialBudget03 != fs.InitialBudget03 OR 
				wageRate.InitialBudget04 != fs.InitialBudget04 OR	
				wageRate.InitialBudget05 != fs.InitialBudget05 OR 
				wageRate.InitialBudget06 != fs.InitialBudget06 OR 
				wageRate.InitialBudget07 != fs.InitialBudget07 OR 
				wageRate.InitialBudget08 != fs.InitialBudget08 OR	
				wageRate.InitialBudget09 != fs.InitialBudget09 OR 
				wageRate.InitialBudget10 != fs.InitialBudget10 OR	
				wageRate.InitialBudget11 != fs.InitialBudget11 OR 
				wageRate.InitialBudget12 != fs.InitialBudget12 OR
				(@MonthsLoaded < 1  AND wageRate.InitialProjection01 != fs.InitialProjection01) OR
				(@MonthsLoaded < 2  AND wageRate.InitialProjection02 != fs.InitialProjection02) OR
				(@MonthsLoaded < 3  AND wageRate.InitialProjection03 != fs.InitialProjection03) OR
				(@MonthsLoaded < 4  AND wageRate.InitialProjection04 != fs.InitialProjection04) OR	
				(@MonthsLoaded < 5  AND wageRate.InitialProjection05 != fs.InitialProjection05) OR
				(@MonthsLoaded < 6  AND wageRate.InitialProjection06 != fs.InitialProjection06) OR
				(@MonthsLoaded < 7  AND wageRate.InitialProjection07 != fs.InitialProjection07) OR
				(@MonthsLoaded < 8  AND wageRate.InitialProjection08 != fs.InitialProjection08) OR
				(@MonthsLoaded < 9  AND wageRate.InitialProjection09 != fs.InitialProjection09) OR
				(@MonthsLoaded < 10 AND wageRate.InitialProjection10 != fs.InitialProjection10) OR	
				(@MonthsLoaded < 11 AND wageRate.InitialProjection11 != fs.InitialProjection11) OR
				(@MonthsLoaded < 12 AND wageRate.InitialProjection12 != fs.InitialProjection12)
			
	
	
	------------------------------------------------------------------------   
	-- Update all variable records to 0 where department and jobcode is in Roster -- (corresponds to line 1382 in rollback - was 3 updates before)
	------------------------------------------------------------------------
	UPDATE fs
	SET 
		InitialBudgetHours01 = 0, InitialBudgetHours02 = 0, InitialBudgetHours03 = 0, InitialBudgetHours04 = 0, InitialBudgetHours05 = 0, InitialBudgetHours06 = 0,
		InitialBudgetHours07 = 0, InitialBudgetHours08 = 0, InitialBudgetHours09 = 0, InitialBudgetHours10 = 0, InitialBudgetHours11 = 0, InitialBudgetHours12 = 0,
		InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionHours01  ELSE 0 END, 
		InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionHours02  ELSE 0 END, 
		InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionHours03  ELSE 0 END, 
		InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionHours04  ELSE 0 END,	
		InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionHours05  ELSE 0 END, 
		InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionHours06  ELSE 0 END, 
		InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionHours07  ELSE 0 END, 
		InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionHours08  ELSE 0 END, 
		InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionHours09  ELSE 0 END, 
		InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionHours10 ELSE 0 END,	
		InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionHours11 ELSE 0 END, 
		InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionHours12 ELSE 0 END,
		TargetAdjustedHours01 = 0, TargetAdjustedHours02 = 0, TargetAdjustedHours03 = 0, TargetAdjustedHours04 = 0,	TargetAdjustedHours05 = 0, TargetAdjustedHours06 = 0, 
		TargetAdjustedHours07 = 0, TargetAdjustedHours08 = 0, TargetAdjustedHours09 = 0, TargetAdjustedHours10 = 0, TargetAdjustedHours11 = 0, TargetAdjustedHours12 = 0,	
		BudgetAdjustedHours01 = 0, BudgetAdjustedHours02 = 0, BudgetAdjustedHours03 = 0, BudgetAdjustedHours04 = 0,	BudgetAdjustedHours05 = 0, BudgetAdjustedHours06 = 0, 
		BudgetAdjustedHours07 = 0, BudgetAdjustedHours08 = 0, BudgetAdjustedHours09 = 0, BudgetAdjustedHours10 = 0, BudgetAdjustedHours11 = 0, BudgetAdjustedHours12 = 0,
		ProjectionAdjustedHours01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedHours01  ELSE 0 END, 
		ProjectionAdjustedHours02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedHours02  ELSE 0 END, 
		ProjectionAdjustedHours03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedHours03  ELSE 0 END, 
		ProjectionAdjustedHours04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedHours04  ELSE 0 END,	
		ProjectionAdjustedHours05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedHours05  ELSE 0 END, 
		ProjectionAdjustedHours06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedHours06  ELSE 0 END,
		ProjectionAdjustedHours07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedHours07  ELSE 0 END, 
		ProjectionAdjustedHours08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedHours08  ELSE 0 END, 
		ProjectionAdjustedHours09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedHours09  ELSE 0 END, 
		ProjectionAdjustedHours10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedHours10 ELSE 0 END,	
		ProjectionAdjustedHours11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedHours11 ELSE 0 END, 
		ProjectionAdjustedHours12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedHours12 ELSE 0 END,
		TargetHoursLockFlag = 1,
		TargetHoursLockType = 4,
		BudgetHoursLockFlag = 1,
		BudgetHoursLockType = 4,
		ProjectionHoursLockFlag = 1,
		ProjectionHoursLockType = 4,

		InitialBudgetDollars01 = 0, InitialBudgetDollars02 = 0, InitialBudgetDollars03 = 0, InitialBudgetDollars04 = 0, InitialBudgetDollars05 = 0, InitialBudgetDollars06 = 0,
		InitialBudgetDollars07 = 0, InitialBudgetDollars08 = 0, InitialBudgetDollars09 = 0, InitialBudgetDollars10 = 0, InitialBudgetDollars11 = 0, InitialBudgetDollars12 = 0,
		InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionDollars01  ELSE 0 END, 
		InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionDollars02  ELSE 0 END, 
		InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionDollars03  ELSE 0 END, 
		InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionDollars04  ELSE 0 END,	
		InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionDollars05  ELSE 0 END, 
		InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionDollars06  ELSE 0 END, 
		InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionDollars07  ELSE 0 END, 
		InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionDollars08  ELSE 0 END, 
		InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionDollars09  ELSE 0 END, 
		InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionDollars10 ELSE 0 END,	
		InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionDollars11 ELSE 0 END, 
		InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionDollars12 ELSE 0 END,
		TargetAdjustedDollars01 = 0, TargetAdjustedDollars02 = 0, TargetAdjustedDollars03 = 0, TargetAdjustedDollars04 = 0,	TargetAdjustedDollars05 = 0, TargetAdjustedDollars06 = 0, 
		TargetAdjustedDollars07 = 0, TargetAdjustedDollars08 = 0, TargetAdjustedDollars09 = 0, TargetAdjustedDollars10 = 0, TargetAdjustedDollars11 = 0, TargetAdjustedDollars12 = 0,	
		BudgetAdjustedDollars01 = 0, BudgetAdjustedDollars02 = 0, BudgetAdjustedDollars03 = 0, BudgetAdjustedDollars04 = 0,	BudgetAdjustedDollars05 = 0, BudgetAdjustedDollars06 = 0, 
		BudgetAdjustedDollars07 = 0, BudgetAdjustedDollars08 = 0, BudgetAdjustedDollars09 = 0, BudgetAdjustedDollars10 = 0, BudgetAdjustedDollars11 = 0, BudgetAdjustedDollars12 = 0,
		ProjectionAdjustedDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedDollars01  ELSE 0 END, 
		ProjectionAdjustedDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedDollars02  ELSE 0 END, 
		ProjectionAdjustedDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedDollars03  ELSE 0 END, 
		ProjectionAdjustedDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedDollars04  ELSE 0 END,	
		ProjectionAdjustedDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedDollars05  ELSE 0 END, 
		ProjectionAdjustedDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedDollars06  ELSE 0 END,
		ProjectionAdjustedDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedDollars07  ELSE 0 END, 
		ProjectionAdjustedDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedDollars08  ELSE 0 END, 
		ProjectionAdjustedDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedDollars09  ELSE 0 END, 
		ProjectionAdjustedDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedDollars10 ELSE 0 END,	
		ProjectionAdjustedDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedDollars11 ELSE 0 END, 
		ProjectionAdjustedDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedDollars12 ELSE 0 END,
		TargetDollarsLockFlag = 1,
		TargetDollarsLockType = 4,
		BudgetDollarsLockFlag = 1,
		BudgetDollarsLockType = 4,
		ProjectionDollarsLockFlag = 1,
		ProjectionDollarsLockType = 4,

		InitialBudgetFTEs01 = 0, InitialBudgetFTEs02 = 0, InitialBudgetFTEs03 = 0, InitialBudgetFTEs04 = 0, InitialBudgetFTEs05 = 0, InitialBudgetFTEs06 = 0,
		InitialBudgetFTEs07 = 0, InitialBudgetFTEs08 = 0, InitialBudgetFTEs09 = 0, InitialBudgetFTEs10 = 0, InitialBudgetFTEs11 = 0, InitialBudgetFTEs12 = 0,
		InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionFTEs01  ELSE 0 END, 
		InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionFTEs02  ELSE 0 END, 
		InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionFTEs03  ELSE 0 END, 
		InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionFTEs04  ELSE 0 END,	
		InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionFTEs05  ELSE 0 END, 
		InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionFTEs06  ELSE 0 END, 
		InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionFTEs07  ELSE 0 END, 
		InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionFTEs08  ELSE 0 END, 
		InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionFTEs09  ELSE 0 END, 
		InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionFTEs10 ELSE 0 END,	
		InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionFTEs11 ELSE 0 END, 
		InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionFTEs12 ELSE 0 END,
		TargetAdjustedFTEs01 = 0, TargetAdjustedFTEs02 = 0, TargetAdjustedFTEs03 = 0, TargetAdjustedFTEs04 = 0,	TargetAdjustedFTEs05 = 0, TargetAdjustedFTEs06 = 0, 
		TargetAdjustedFTEs07 = 0, TargetAdjustedFTEs08 = 0, TargetAdjustedFTEs09 = 0, TargetAdjustedFTEs10 = 0, TargetAdjustedFTEs11 = 0, TargetAdjustedFTEs12 = 0,	
		BudgetAdjustedFTEs01 = 0, BudgetAdjustedFTEs02 = 0, BudgetAdjustedFTEs03 = 0, BudgetAdjustedFTEs04 = 0,	BudgetAdjustedFTEs05 = 0, BudgetAdjustedFTEs06 = 0, 
		BudgetAdjustedFTEs07 = 0, BudgetAdjustedFTEs08 = 0, BudgetAdjustedFTEs09 = 0, BudgetAdjustedFTEs10 = 0, BudgetAdjustedFTEs11 = 0, BudgetAdjustedFTEs12 = 0,
		ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedFTEs01  ELSE 0 END, 
		ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedFTEs02  ELSE 0 END, 
		ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedFTEs03  ELSE 0 END, 
		ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedFTEs04  ELSE 0 END,	
		ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedFTEs05  ELSE 0 END, 
		ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedFTEs06  ELSE 0 END,
		ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedFTEs07  ELSE 0 END, 
		ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedFTEs08  ELSE 0 END, 
		ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedFTEs09  ELSE 0 END, 
		ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE 0 END,	
		ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE 0 END, 
		ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE 0 END,
		TargetFTEsLockFlag = 1,
		TargetFTEsLockType = 4,
		BudgetFTEsLockFlag = 1,
		BudgetFTEsLockType = 4,
		ProjectionFTEsLockFlag = 1,
		ProjectionFTEsLockType = 4
	FROM [fp].[Staffing] fs 
		INNER JOIN #tmpRosterRolledUp rb ON 
				fs.JobCodeID = rb.JobCodeID 
			AND fs.DepartmentID = rb.DepartmentID 
			AND fs.EntityID = rb.EntityID
	WHERE fs.BudgetConfigID = @BudgetConfigID 
        AND fs.VariabilityID = 2
		AND (
		InitialBudgetHours01 != 0 OR  InitialBudgetHours02 != 0 OR  InitialBudgetHours03 != 0 OR  InitialBudgetHours04 != 0 OR  InitialBudgetHours05 != 0 OR  InitialBudgetHours06 != 0 OR 
		InitialBudgetHours07 != 0 OR  InitialBudgetHours08 != 0 OR  InitialBudgetHours09 != 0 OR  InitialBudgetHours10 != 0 OR  InitialBudgetHours11 != 0 OR  InitialBudgetHours12 != 0 OR 
		(@MonthsLoaded >= 1  AND InitialProjectionHours01 != 0) OR  
		(@MonthsLoaded >= 2  AND InitialProjectionHours02 != 0) OR  
		(@MonthsLoaded >= 3  AND InitialProjectionHours03 != 0) OR  
		(@MonthsLoaded >= 4  AND InitialProjectionHours04 != 0) OR 	
		(@MonthsLoaded >= 5  AND InitialProjectionHours05 != 0) OR  
		(@MonthsLoaded >= 6  AND InitialProjectionHours06 != 0) OR  
		(@MonthsLoaded >= 7  AND InitialProjectionHours07 != 0) OR  
		(@MonthsLoaded >= 8  AND InitialProjectionHours08 != 0) OR  
		(@MonthsLoaded >= 9  AND InitialProjectionHours09 != 0) OR  
		(@MonthsLoaded >= 10 AND InitialProjectionHours10 != 0) OR 	
		(@MonthsLoaded >= 11 AND InitialProjectionHours11 != 0) OR  
		(@MonthsLoaded >= 12 AND InitialProjectionHours12 != 0) OR 
		TargetAdjustedHours01 != 0 OR  TargetAdjustedHours02 != 0 OR  TargetAdjustedHours03 != 0 OR  TargetAdjustedHours04 != 0 OR 	TargetAdjustedHours05 != 0 OR  TargetAdjustedHours06 != 0 OR  
		TargetAdjustedHours07 != 0 OR  TargetAdjustedHours08 != 0 OR  TargetAdjustedHours09 != 0 OR  TargetAdjustedHours10 != 0 OR  TargetAdjustedHours11 != 0 OR  TargetAdjustedHours12 != 0 OR 	
		BudgetAdjustedHours01 != 0 OR  BudgetAdjustedHours02 != 0 OR  BudgetAdjustedHours03 != 0 OR  BudgetAdjustedHours04 != 0 OR 	BudgetAdjustedHours05 != 0 OR  BudgetAdjustedHours06 != 0 OR  
		BudgetAdjustedHours07 != 0 OR  BudgetAdjustedHours08 != 0 OR  BudgetAdjustedHours09 != 0 OR  BudgetAdjustedHours10 != 0 OR  BudgetAdjustedHours11 != 0 OR  BudgetAdjustedHours12 != 0 OR 
		(@MonthsLoaded >= 1  AND ProjectionAdjustedHours01 != 0) OR  
		(@MonthsLoaded >= 2  AND ProjectionAdjustedHours02 != 0) OR  
		(@MonthsLoaded >= 3  AND ProjectionAdjustedHours03 != 0) OR  
		(@MonthsLoaded >= 4  AND ProjectionAdjustedHours04 != 0) OR 	
		(@MonthsLoaded >= 5  AND ProjectionAdjustedHours05 != 0) OR  
		(@MonthsLoaded >= 6  AND ProjectionAdjustedHours06 != 0) OR 
		(@MonthsLoaded >= 7  AND ProjectionAdjustedHours07 != 0) OR  
		(@MonthsLoaded >= 8  AND ProjectionAdjustedHours08 != 0) OR  
		(@MonthsLoaded >= 9  AND ProjectionAdjustedHours09 != 0) OR  
		(@MonthsLoaded >= 10 AND ProjectionAdjustedHours10 != 0) OR 	
		(@MonthsLoaded >= 11 AND ProjectionAdjustedHours11 != 0) OR  
		(@MonthsLoaded >= 12 AND ProjectionAdjustedHours12 != 0) OR 
		TargetHoursLockFlag != 1 OR 
		TargetHoursLockType != 4 OR 
		BudgetHoursLockFlag != 1 OR 
		BudgetHoursLockType != 4 OR 
		ProjectionHoursLockFlag != 1 OR 
		ProjectionHoursLockType != 4
		)
		

	------------------------------------------------------------
	-- Update original values and manager values where needed -- (corresponds to line 1488 in rollback)
	------------------------------------------------------------
	-- I separated hours/dollars/ftes out into separate statements rather than have a big giant WHERE AND OR clause, feel free to doubt my choices
	-- Update the baseline if it hasn't been yet. 
	UPDATE fs
	SET
		fs.InitialBudgetHours01 = fs.TargetAdjustedHours01, fs.InitialBudgetHours02 = fs.TargetAdjustedHours02,	fs.InitialBudgetHours03 = fs.TargetAdjustedHours03,
		fs.InitialBudgetHours04 = fs.TargetAdjustedHours04, fs.InitialBudgetHours05 = fs.TargetAdjustedHours05,	fs.InitialBudgetHours06 = fs.TargetAdjustedHours06,
		fs.InitialBudgetHours07 = fs.TargetAdjustedHours07, fs.InitialBudgetHours08 = fs.TargetAdjustedHours08,	fs.InitialBudgetHours09 = fs.TargetAdjustedHours09,
		fs.InitialBudgetHours10 = fs.TargetAdjustedHours10, fs.InitialBudgetHours11 = fs.TargetAdjustedHours11,	fs.InitialBudgetHours12 = fs.TargetAdjustedHours12,
		InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionHours01  ELSE fs.ProjectionAdjustedHours01 END, 
		InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionHours02  ELSE fs.ProjectionAdjustedHours02 END, 
		InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionHours03  ELSE fs.ProjectionAdjustedHours03 END, 
		InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionHours04  ELSE fs.ProjectionAdjustedHours04 END,	
		InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionHours05  ELSE fs.ProjectionAdjustedHours05 END, 
		InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionHours06  ELSE fs.ProjectionAdjustedHours06 END, 
		InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionHours07  ELSE fs.ProjectionAdjustedHours07 END, 
		InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionHours08  ELSE fs.ProjectionAdjustedHours08 END, 
		InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionHours09  ELSE fs.ProjectionAdjustedHours09 END, 
		InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionHours10 ELSE fs.ProjectionAdjustedHours10 END,	
		InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionHours11 ELSE fs.ProjectionAdjustedHours11 END, 
		InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionHours12 ELSE fs.ProjectionAdjustedHours12 END
	FROM [fp].[Staffing] fs
		INNER JOIN #tmpRosterRolledUp Filter ON
					fs.DepartmentID = Filter.DepartmentID 
					AND fs.JobCodeID = Filter.JobCodeID
					AND fs.PayCodeGroupID = Filter.PayCodeGroupID
					AND fs.EntityID = Filter.EntityID
	WHERE TargetHoursLockFlag = 4
		AND ProjectionHoursLockFlag = 4
		-- Check to see if there's an initial budget already defined, if there's not, set it, if there is, ignore it.
		AND (InitialBudgetHours01 = 0 AND InitialBudgetHours02 = 0 AND InitialBudgetHours03 = 0 AND InitialBudgetHours04 = 0 AND InitialBudgetHours05 = 0 AND InitialBudgetHours06 = 0 AND
			InitialBudgetHours07 = 0 AND	InitialBudgetHours08 = 0 AND InitialBudgetHours09 = 0 AND InitialBudgetHours10 = 0 AND InitialBudgetHours11 = 0 AND	InitialBudgetHours12 = 0 )
		AND (
					(@MonthsLoaded < 1  AND InitialProjectionHours01 = 0) 
				AND (@MonthsLoaded < 2  AND InitialProjectionHours02 = 0) 
				AND (@MonthsLoaded < 3  AND InitialProjectionHours03 = 0) 
				AND (@MonthsLoaded < 4  AND InitialProjectionHours04 = 0) 
				AND (@MonthsLoaded < 5  AND InitialProjectionHours05 = 0) 
				AND (@MonthsLoaded < 6  AND InitialProjectionHours06 = 0) 
				AND (@MonthsLoaded < 7  AND InitialProjectionHours07 = 0) 
				AND (@MonthsLoaded < 8  AND InitialProjectionHours08 = 0) 
				AND (@MonthsLoaded < 9  AND InitialProjectionHours09 = 0) 
				AND (@MonthsLoaded < 10 AND InitialProjectionHours10 = 0) 
				AND	(@MonthsLoaded < 11 AND InitialProjectionHours11 = 0) 
				AND	(@MonthsLoaded < 12 AND InitialProjectionHours12 = 0) 
		   ) AND (
       		(@MonthsLoaded < 1  AND ProjectionAdjustedHours01 != 0) OR 
				(@MonthsLoaded < 2  AND ProjectionAdjustedHours02 != 0) OR 
				(@MonthsLoaded < 3  AND ProjectionAdjustedHours03 != 0) OR 
				(@MonthsLoaded < 4  AND ProjectionAdjustedHours04 != 0) OR 
				(@MonthsLoaded < 5  AND ProjectionAdjustedHours05 != 0) OR 
			 	(@MonthsLoaded < 6  AND ProjectionAdjustedHours06 != 0) OR 
				(@MonthsLoaded < 7  AND ProjectionAdjustedHours07 != 0) OR 
				(@MonthsLoaded < 8  AND ProjectionAdjustedHours08 != 0) OR 
				(@MonthsLoaded < 9  AND ProjectionAdjustedHours09 != 0) OR 
				(@MonthsLoaded < 10 AND ProjectionAdjustedHours10 != 0) OR 
			 	(@MonthsLoaded < 11 AND ProjectionAdjustedHours11 != 0) OR 
				(@MonthsLoaded < 12 AND ProjectionAdjustedHours12 != 0) OR		 
			   BudgetAdjustedHours01 != 0 OR BudgetAdjustedHours02 != 0 OR BudgetAdjustedHours03 != 0 OR BudgetAdjustedHours04 != 0 OR BudgetAdjustedHours05 != 0 OR 
			   BudgetAdjustedHours06 != 0 OR BudgetAdjustedHours07 != 0 OR BudgetAdjustedHours08 != 0 OR BudgetAdjustedHours09 != 0 OR BudgetAdjustedHours10 != 0 OR 
			   BudgetAdjustedHours11 != 0 OR BudgetAdjustedHours12 != 0
			 )	

        AND fs.BudgetConfigID = @BudgetConfigID

	-- Update the Dollar baseline if it hasn't been yet. 
	UPDATE fs
	SET
		fs.InitialBudgetDollars01 = fs.TargetAdjustedDollars01, fs.InitialBudgetDollars02 = fs.TargetAdjustedDollars02,	fs.InitialBudgetDollars03 = fs.TargetAdjustedDollars03,
		fs.InitialBudgetDollars04 = fs.TargetAdjustedDollars04, fs.InitialBudgetDollars05 = fs.TargetAdjustedDollars05,	fs.InitialBudgetDollars06 = fs.TargetAdjustedDollars06,
		fs.InitialBudgetDollars07 = fs.TargetAdjustedDollars07, fs.InitialBudgetDollars08 = fs.TargetAdjustedDollars08,	fs.InitialBudgetDollars09 = fs.TargetAdjustedDollars09,
		fs.InitialBudgetDollars10 = fs.TargetAdjustedDollars10, fs.InitialBudgetDollars11 = fs.TargetAdjustedDollars11,	fs.InitialBudgetDollars12 = fs.TargetAdjustedDollars12,
		InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionDollars01  ELSE fs.ProjectionAdjustedDollars01 END, 
		InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionDollars02  ELSE fs.ProjectionAdjustedDollars02 END, 
		InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionDollars03  ELSE fs.ProjectionAdjustedDollars03 END, 
		InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionDollars04  ELSE fs.ProjectionAdjustedDollars04 END,	
		InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionDollars05  ELSE fs.ProjectionAdjustedDollars05 END, 
		InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionDollars06  ELSE fs.ProjectionAdjustedDollars06 END, 
		InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionDollars07  ELSE fs.ProjectionAdjustedDollars07 END, 
		InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionDollars08  ELSE fs.ProjectionAdjustedDollars08 END, 
		InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionDollars09  ELSE fs.ProjectionAdjustedDollars09 END, 
		InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionDollars10 ELSE fs.ProjectionAdjustedDollars10 END,	
		InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionDollars11 ELSE fs.ProjectionAdjustedDollars11 END, 
		InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionDollars12 ELSE fs.ProjectionAdjustedDollars12 END
	FROM [fp].[Staffing] fs
		INNER JOIN #tmpRosterRolledUp Filter ON
					fs.DepartmentID = Filter.DepartmentID 
					AND fs.JobCodeID = Filter.JobCodeID
					AND fs.PayCodeGroupID = Filter.PayCodeGroupID
					AND fs.EntityID = Filter.EntityID
	WHERE TargetDollarsLockFlag = 4
		AND ProjectionDollarsLockFlag = 4
		-- Check to see if there's an initial budget already defined, if there's not, set it, if there is, ignore it.
		AND (InitialBudgetDollars01 = 0 AND InitialBudgetDollars02 = 0 AND InitialBudgetDollars03 = 0 AND InitialBudgetDollars04 = 0 AND InitialBudgetDollars05 = 0 AND InitialBudgetDollars06 = 0 AND
			InitialBudgetDollars07 = 0 AND	InitialBudgetDollars08 = 0 AND InitialBudgetDollars09 = 0 AND InitialBudgetDollars10 = 0 AND InitialBudgetDollars11 = 0 AND	InitialBudgetDollars12 = 0 )
		AND (
					(@MonthsLoaded < 1  AND InitialProjectionDollars01 = 0) 
				AND (@MonthsLoaded < 2  AND InitialProjectionDollars02 = 0) 
				AND (@MonthsLoaded < 3  AND InitialProjectionDollars03 = 0) 
				AND (@MonthsLoaded < 4  AND InitialProjectionDollars04 = 0) 
				AND (@MonthsLoaded < 5  AND InitialProjectionDollars05 = 0) 
				AND (@MonthsLoaded < 6  AND InitialProjectionDollars06 = 0) 
				AND (@MonthsLoaded < 7  AND InitialProjectionDollars07 = 0) 
				AND (@MonthsLoaded < 8  AND InitialProjectionDollars08 = 0) 
				AND (@MonthsLoaded < 9  AND InitialProjectionDollars09 = 0) 
				AND (@MonthsLoaded < 10 AND InitialProjectionDollars10 = 0) 
				AND	(@MonthsLoaded < 11 AND InitialProjectionDollars11 = 0) 
				AND	(@MonthsLoaded < 12 AND InitialProjectionDollars12 = 0) 
			) AND (
  			   (@MonthsLoaded < 1  AND ProjectionAdjustedDollars01 != 0) OR 
				(@MonthsLoaded < 2  AND ProjectionAdjustedDollars02 != 0) OR 
				(@MonthsLoaded < 3  AND ProjectionAdjustedDollars03 != 0) OR 
				(@MonthsLoaded < 4  AND ProjectionAdjustedDollars04 != 0) OR 
				(@MonthsLoaded < 5  AND ProjectionAdjustedDollars05 != 0) OR 
			 	(@MonthsLoaded < 6  AND ProjectionAdjustedDollars06 != 0) OR 
				(@MonthsLoaded < 7  AND ProjectionAdjustedDollars07 != 0) OR 
				(@MonthsLoaded < 8  AND ProjectionAdjustedDollars08 != 0) OR 
				(@MonthsLoaded < 9  AND ProjectionAdjustedDollars09 != 0) OR 
				(@MonthsLoaded < 10 AND ProjectionAdjustedDollars10 != 0) OR 
			 	(@MonthsLoaded < 11 AND ProjectionAdjustedDollars11 != 0) OR 
				(@MonthsLoaded < 12 AND ProjectionAdjustedDollars12 != 0) OR		 
			   BudgetAdjustedDollars01 != 0 OR BudgetAdjustedDollars02 != 0 OR BudgetAdjustedDollars03 != 0 OR BudgetAdjustedDollars04 != 0 OR BudgetAdjustedDollars05 != 0 OR 
			   BudgetAdjustedDollars06 != 0 OR BudgetAdjustedDollars07 != 0 OR BudgetAdjustedDollars08 != 0 OR BudgetAdjustedDollars09 != 0 OR BudgetAdjustedDollars10 != 0 OR 
			   BudgetAdjustedDollars11 != 0 OR BudgetAdjustedDollars12 != 0
			 )	
        AND fs.BudgetConfigID = @BudgetConfigID

	-- Update the FTE baseline if it hasn't been yet. 
	UPDATE fs
	SET
		fs.InitialBudgetFTEs01 = fs.TargetAdjustedFTEs01, fs.InitialBudgetFTEs02 = fs.TargetAdjustedFTEs02,	fs.InitialBudgetFTEs03 = fs.TargetAdjustedFTEs03,
		fs.InitialBudgetFTEs04 = fs.TargetAdjustedFTEs04, fs.InitialBudgetFTEs05 = fs.TargetAdjustedFTEs05,	fs.InitialBudgetFTEs06 = fs.TargetAdjustedFTEs06,
		fs.InitialBudgetFTEs07 = fs.TargetAdjustedFTEs07, fs.InitialBudgetFTEs08 = fs.TargetAdjustedFTEs08,	fs.InitialBudgetFTEs09 = fs.TargetAdjustedFTEs09,
		fs.InitialBudgetFTEs10 = fs.TargetAdjustedFTEs10, fs.InitialBudgetFTEs11 = fs.TargetAdjustedFTEs11,	fs.InitialBudgetFTEs12 = fs.TargetAdjustedFTEs12,
		InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionFTEs01  ELSE fs.ProjectionAdjustedFTEs01 END, 
		InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionFTEs02  ELSE fs.ProjectionAdjustedFTEs02 END, 
		InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionFTEs03  ELSE fs.ProjectionAdjustedFTEs03 END, 
		InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionFTEs04  ELSE fs.ProjectionAdjustedFTEs04 END,	
		InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionFTEs05  ELSE fs.ProjectionAdjustedFTEs05 END, 
		InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionFTEs06  ELSE fs.ProjectionAdjustedFTEs06 END, 
		InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionFTEs07  ELSE fs.ProjectionAdjustedFTEs07 END, 
		InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionFTEs08  ELSE fs.ProjectionAdjustedFTEs08 END, 
		InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionFTEs09  ELSE fs.ProjectionAdjustedFTEs09 END, 
		InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionFTEs10 ELSE fs.ProjectionAdjustedFTEs10 END,	
		InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionFTEs11 ELSE fs.ProjectionAdjustedFTEs11 END, 
		InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionFTEs12 ELSE fs.ProjectionAdjustedFTEs12 END

	FROM [fp].[Staffing] fs
		INNER JOIN #tmpRosterRolledUp Filter ON
					fs.DepartmentID = Filter.DepartmentID 
					AND fs.JobCodeID = Filter.JobCodeID
					AND fs.PayCodeGroupID = Filter.PayCodeGroupID
					AND fs.EntityID = Filter.EntityID
	WHERE TargetFTEsLockFlag = 4
		AND ProjectionFTEsLockFlag = 4
		-- Check to see if there's an initial budget already defined, if there's not, set it, if there is, ignore it.
		AND (InitialBudgetFTEs01 = 0 AND InitialBudgetFTEs02 = 0 AND InitialBudgetFTEs03 = 0 AND InitialBudgetFTEs04 = 0 AND InitialBudgetFTEs05 = 0 AND InitialBudgetFTEs06 = 0 AND
			InitialBudgetFTEs07 = 0 AND	InitialBudgetFTEs08 = 0 AND InitialBudgetFTEs09 = 0 AND InitialBudgetFTEs10 = 0 AND InitialBudgetFTEs11 = 0 AND	InitialBudgetFTEs12 = 0 )
		AND (
					(@MonthsLoaded < 1  AND InitialProjectionFTEs01 = 0) 
				AND (@MonthsLoaded < 2  AND InitialProjectionFTEs02 = 0) 
				AND (@MonthsLoaded < 3  AND InitialProjectionFTEs03 = 0) 
				AND (@MonthsLoaded < 4  AND InitialProjectionFTEs04 = 0) 
				AND (@MonthsLoaded < 5  AND InitialProjectionFTEs05 = 0) 
				AND (@MonthsLoaded < 6  AND InitialProjectionFTEs06 = 0) 
				AND (@MonthsLoaded < 7  AND InitialProjectionFTEs07 = 0) 
				AND (@MonthsLoaded < 8  AND InitialProjectionFTEs08 = 0) 
				AND (@MonthsLoaded < 9  AND InitialProjectionFTEs09 = 0) 
				AND (@MonthsLoaded < 10 AND InitialProjectionFTEs10 = 0) 
				AND	(@MonthsLoaded < 11 AND InitialProjectionFTEs11 = 0) 
				AND	(@MonthsLoaded < 12 AND InitialProjectionFTEs12 = 0) 
			)
		AND (	(@MonthsLoaded < 1  AND ProjectionAdjustedFTEs01 != 0) OR 
				(@MonthsLoaded < 2  AND ProjectionAdjustedFTEs02 != 0) OR 
				(@MonthsLoaded < 3  AND ProjectionAdjustedFTEs03 != 0) OR 
				(@MonthsLoaded < 4  AND ProjectionAdjustedFTEs04 != 0) OR 
				(@MonthsLoaded < 5  AND ProjectionAdjustedFTEs05 != 0) OR 
			 	(@MonthsLoaded < 6  AND ProjectionAdjustedFTEs06 != 0) OR 
				(@MonthsLoaded < 7  AND ProjectionAdjustedFTEs07 != 0) OR 
				(@MonthsLoaded < 8  AND ProjectionAdjustedFTEs08 != 0) OR 
				(@MonthsLoaded < 9  AND ProjectionAdjustedFTEs09 != 0) OR 
				(@MonthsLoaded < 10 AND ProjectionAdjustedFTEs10 != 0) OR 
			 	(@MonthsLoaded < 11 AND ProjectionAdjustedFTEs11 != 0) OR 
				(@MonthsLoaded < 12 AND ProjectionAdjustedFTEs12 != 0) OR		 
			 BudgetAdjustedFTEs01 != 0 OR BudgetAdjustedFTEs02 != 0 OR BudgetAdjustedFTEs03 != 0 OR BudgetAdjustedFTEs04 != 0 OR BudgetAdjustedFTEs05 != 0 OR 
			 BudgetAdjustedFTEs06 != 0 OR BudgetAdjustedFTEs07 != 0 OR BudgetAdjustedFTEs08 != 0 OR BudgetAdjustedFTEs09 != 0 OR BudgetAdjustedFTEs10 != 0 OR 
			 BudgetAdjustedFTEs11 != 0 OR BudgetAdjustedFTEs12 != 0)	

        AND fs.BudgetConfigID = @BudgetConfigID
 
    --------------------------------------------------------------------------------------------------------------------------------
    -- corresponds to line 1555 in rollback
    --------------------------------------------------------------------------------------------------------------------------------
	UPDATE fs
    SET
        BudgetAdjustedHours01 = TargetAdjustedHours01,
        BudgetAdjustedHours02 = TargetAdjustedHours02,
        BudgetAdjustedHours03 = TargetAdjustedHours03,
        BudgetAdjustedHours04 = TargetAdjustedHours04,
        BudgetAdjustedHours05 = TargetAdjustedHours05,
        BudgetAdjustedHours06 = TargetAdjustedHours06,
        BudgetAdjustedHours07 = TargetAdjustedHours07,
        BudgetAdjustedHours08 = TargetAdjustedHours08,
        BudgetAdjustedHours09 = TargetAdjustedHours09,
        BudgetAdjustedHours10 = TargetAdjustedHours10,
        BudgetAdjustedHours11 = TargetAdjustedHours11,
        BudgetAdjustedHours12 = TargetAdjustedHours12,

		BudgetAdjustedDollars01 = TargetAdjustedDollars01,
        BudgetAdjustedDollars02 = TargetAdjustedDollars02,
        BudgetAdjustedDollars03 = TargetAdjustedDollars03,
        BudgetAdjustedDollars04 = TargetAdjustedDollars04,
        BudgetAdjustedDollars05 = TargetAdjustedDollars05,
        BudgetAdjustedDollars06 = TargetAdjustedDollars06,
        BudgetAdjustedDollars07 = TargetAdjustedDollars07,
        BudgetAdjustedDollars08 = TargetAdjustedDollars08,
        BudgetAdjustedDollars09 = TargetAdjustedDollars09,
        BudgetAdjustedDollars10 = TargetAdjustedDollars10,
        BudgetAdjustedDollars11 = TargetAdjustedDollars11,
        BudgetAdjustedDollars12 = TargetAdjustedDollars12,

		BudgetAdjustedFTEs01 = TargetAdjustedFTEs01,
        BudgetAdjustedFTEs02 = TargetAdjustedFTEs02,
        BudgetAdjustedFTEs03 = TargetAdjustedFTEs03,
        BudgetAdjustedFTEs04 = TargetAdjustedFTEs04,
        BudgetAdjustedFTEs05 = TargetAdjustedFTEs05,
        BudgetAdjustedFTEs06 = TargetAdjustedFTEs06,
        BudgetAdjustedFTEs07 = TargetAdjustedFTEs07,
        BudgetAdjustedFTEs08 = TargetAdjustedFTEs08,
        BudgetAdjustedFTEs09 = TargetAdjustedFTEs09,
        BudgetAdjustedFTEs10 = TargetAdjustedFTEs10,
        BudgetAdjustedFTEs11 = TargetAdjustedFTEs11,
        BudgetAdjustedFTEs12 = TargetAdjustedFTEs12
    FROM [fp].[Staffing] fs 
		INNER JOIN #tmpRosterRolledUp Filter ON
					fs.DepartmentID = Filter.DepartmentID 
					AND fs.JobCodeID = Filter.JobCodeID
					AND fs.PayCodeGroupID = Filter.PayCodeGroupID
					AND fs.EntityID = Filter.EntityID
    WHERE fs.BudgetConfigID = @BudgetConfigID
        AND (
		(TargetHoursLockType = 4
        AND (
            BudgetAdjustedHours01 != TargetAdjustedHours01 OR 
            BudgetAdjustedHours02 != TargetAdjustedHours02 OR 
            BudgetAdjustedHours03 != TargetAdjustedHours03 OR 
            BudgetAdjustedHours04 != TargetAdjustedHours04 OR 
            BudgetAdjustedHours05 != TargetAdjustedHours05 OR 
            BudgetAdjustedHours06 != TargetAdjustedHours06 OR 
            BudgetAdjustedHours07 != TargetAdjustedHours07 OR 
            BudgetAdjustedHours08 != TargetAdjustedHours08 OR 
            BudgetAdjustedHours09 != TargetAdjustedHours09 OR 
            BudgetAdjustedHours10 != TargetAdjustedHours10 OR 
            BudgetAdjustedHours11 != TargetAdjustedHours11 OR 
            BudgetAdjustedHours12 != TargetAdjustedHours12))
		OR
		(TargetDollarsLockType = 4
        AND (
            BudgetAdjustedDollars01 != TargetAdjustedDollars01 OR 
            BudgetAdjustedDollars02 != TargetAdjustedDollars02 OR 
            BudgetAdjustedDollars03 != TargetAdjustedDollars03 OR 
            BudgetAdjustedDollars04 != TargetAdjustedDollars04 OR 
            BudgetAdjustedDollars05 != TargetAdjustedDollars05 OR 
            BudgetAdjustedDollars06 != TargetAdjustedDollars06 OR 
            BudgetAdjustedDollars07 != TargetAdjustedDollars07 OR 
            BudgetAdjustedDollars08 != TargetAdjustedDollars08 OR 
            BudgetAdjustedDollars09 != TargetAdjustedDollars09 OR 
            BudgetAdjustedDollars10 != TargetAdjustedDollars10 OR 
            BudgetAdjustedDollars11 != TargetAdjustedDollars11 OR 
            BudgetAdjustedDollars12 != TargetAdjustedDollars12))
		OR
		(TargetFTEsLockType = 4
        AND (
            BudgetAdjustedFTEs01 != TargetAdjustedFTEs01 OR 
            BudgetAdjustedFTEs02 != TargetAdjustedFTEs02 OR 
            BudgetAdjustedFTEs03 != TargetAdjustedFTEs03 OR 
            BudgetAdjustedFTEs04 != TargetAdjustedFTEs04 OR 
            BudgetAdjustedFTEs05 != TargetAdjustedFTEs05 OR 
            BudgetAdjustedFTEs06 != TargetAdjustedFTEs06 OR 
            BudgetAdjustedFTEs07 != TargetAdjustedFTEs07 OR 
            BudgetAdjustedFTEs08 != TargetAdjustedFTEs08 OR 
            BudgetAdjustedFTEs09 != TargetAdjustedFTEs09 OR 
            BudgetAdjustedFTEs10 != TargetAdjustedFTEs10 OR 
            BudgetAdjustedFTEs11 != TargetAdjustedFTEs11 OR 
            BudgetAdjustedFTEs12 != TargetAdjustedFTEs12))
		)
            
  
	-- Lock any related PCG's that aren't in Roster, but contains a job code managed by roster
	UPDATE fs
	SET 
		TargetHoursLockFlag = 1,
		TargetHoursLockType = 4,
		TargetDollarsLockFlag = 1,
		TargetDollarsLockType = 4,
		TargetFTEsLockFlag = 1,
		TargetFTEsLockType = 4,
		ProjectionHoursLockFlag = 1,
		ProjectionHoursLockType = 4,
		ProjectionDollarsLockFlag = 1,
		ProjectionDollarsLockType = 4,
		ProjectionFTEsLockFlag = 1,
		ProjectionFTEsLockType = 4
	FROM [fp].[Staffing]  fs
		INNER JOIN #tmpRosterRolledUp rb ON 
				fs.JobCodeID = rb.JobCodeID 
			AND fs.DepartmentID = rb.DepartmentID
			AND fs.EntityID = rb.EntityID
	WHERE fs.BudgetConfigID = @BudgetConfigID
		AND (
		fs.TargetHoursLockFlag = 0 OR
		fs.TargetDollarsLockFlag = 0 OR
		fs.TargetFTEsLockFlag = 0 OR
		fs.ProjectionHoursLockFlag = 0 OR
		fs.ProjectionDollarsLockFlag = 0 OR
		fs.ProjectionFTEsLockFlag = 0 
		)

		
	--------------
	-- Clean Up --
	--------------
	DROP TABLE #tmpPaddedStaffingData
	DROP TABLE #tmpRosterRolledUp
	DROP TABLE #tmpHoursRatio
	DROP TABLE #tmpEntity
	DROP TABLE #Filter
GO


---------------------------------------------

-- fp.procUpdateBenefitRatesTrailing12
CREATE PROCEDURE [fp].[procUpdateBenefitRatesTrailing12]
	@EntityGroupConfigID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS 
BEGIN
    DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER;
    DECLARE @MonthsLoaded INT;

    SELECT @MonthsLoaded = MonthsLoaded,
           @EntityGroupConfigGUID = EntityGroupConfigGUID
    FROM [fp].[BudgetConfig] b 
    INNER JOIN [fp].[EntityGroupConfig] e ON b.BudgetConfigGUID = e.BudgetConfigGUID 
    WHERE e.EntityGroupConfigID = @EntityGroupConfigID
        
    CREATE TABLE #FilterByDepartment (DepartmentID int)
    INSERT INTO #FilterByDepartment (DepartmentID)
    SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality);

    SELECT
        BenefitsID = fb.BenefitsID,
        PriorYearActualValue01	= bh.PriorYearActualValue01,
        PriorYearActualValue02	= bh.PriorYearActualValue02,
        PriorYearActualValue03	= bh.PriorYearActualValue03,
        PriorYearActualValue04	= bh.PriorYearActualValue04,
        PriorYearActualValue05	= bh.PriorYearActualValue05,
        PriorYearActualValue06	= bh.PriorYearActualValue06,
        PriorYearActualValue07	= bh.PriorYearActualValue07,
        PriorYearActualValue08	= bh.PriorYearActualValue08,
        PriorYearActualValue09	= bh.PriorYearActualValue09,
        PriorYearActualValue10	= bh.PriorYearActualValue10,
        PriorYearActualValue11	= bh.PriorYearActualValue11,
        PriorYearActualValue12	= bh.PriorYearActualValue12,
        ActualYTDValue01	= bh.ActualYTDValue01,
        ActualYTDValue02	= bh.ActualYTDValue02,
        ActualYTDValue03	= bh.ActualYTDValue03,
        ActualYTDValue04	= bh.ActualYTDValue04,
        ActualYTDValue05	= bh.ActualYTDValue05,
        ActualYTDValue06	= bh.ActualYTDValue06,
        ActualYTDValue07	= bh.ActualYTDValue07,
        ActualYTDValue08	= bh.ActualYTDValue08,
        ActualYTDValue09	= bh.ActualYTDValue09,
        ActualYTDValue10	= bh.ActualYTDValue10,
        ActualYTDValue11	= bh.ActualYTDValue11,
        ActualYTDValue12	= bh.ActualYTDValue12
    INTO #YearValues
    FROM [fp].[FactBenefitsHistory] bh
    INNER JOIN [fp].[FactBenefits] fb on bh.BenefitsID = fb.BenefitsID
    INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fb.DepartmentID or ft.DepartmentID is null)
    INNER JOIN [fp].[AccountFlexConfig] fc on fb.AccountID = fc.AccountID and fc.EntityGroupConfigGUID = @EntityGroupConfigGUID
    WHERE 1=1
      AND fc.IsUsingTrailing12 = 1
      AND fb.EntityGroupConfigID = @EntityGroupConfigID
      AND fb.UnitTypeID in
          (
           171, --Dollars per FTE
           170  --Percent of Salaries
              )
      AND fc.FlexMethodClassName in ('FlexAccountBySalaries','FlexAccountByFTEs')
      AND (
                bh.PriorYearActualValue01 <> 0 OR
                bh.PriorYearActualValue02 <> 0 OR
                bh.PriorYearActualValue03 <> 0 OR
                bh.PriorYearActualValue04 <> 0 OR
                bh.PriorYearActualValue05 <> 0 OR
                bh.PriorYearActualValue06 <> 0 OR
                bh.PriorYearActualValue07 <> 0 OR
                bh.PriorYearActualValue08 <> 0 OR
                bh.PriorYearActualValue09 <> 0 OR
                bh.PriorYearActualValue10 <> 0 OR
                bh.PriorYearActualValue11 <> 0 OR
                bh.PriorYearActualValue12 <> 0
        )

    UPDATE fb
    SET 
        InitialBudget01     = CASE WHEN @MonthsLoaded < 1  THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END,
        InitialBudget02     = CASE WHEN @MonthsLoaded < 2  THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END,
        InitialBudget03     = CASE WHEN @MonthsLoaded < 3  THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END,
        InitialBudget04     = CASE WHEN @MonthsLoaded < 4  THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END,
        InitialBudget05     = CASE WHEN @MonthsLoaded < 5  THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END,
        InitialBudget06     = CASE WHEN @MonthsLoaded < 6  THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END,
        InitialBudget07     = CASE WHEN @MonthsLoaded < 7  THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END,
        InitialBudget08     = CASE WHEN @MonthsLoaded < 8  THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END,
        InitialBudget09     = CASE WHEN @MonthsLoaded < 9  THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END,
        InitialBudget10     = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END,
        InitialBudget11     = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END,
        InitialBudget12     = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END,
        SampledBudget01     = CASE WHEN @MonthsLoaded < 1  THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END,
        SampledBudget02     = CASE WHEN @MonthsLoaded < 2  THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END,
        SampledBudget03     = CASE WHEN @MonthsLoaded < 3  THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END,
        SampledBudget04     = CASE WHEN @MonthsLoaded < 4  THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END,
        SampledBudget05     = CASE WHEN @MonthsLoaded < 5  THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END,
        SampledBudget06     = CASE WHEN @MonthsLoaded < 6  THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END,
        SampledBudget07     = CASE WHEN @MonthsLoaded < 7  THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END,
        SampledBudget08     = CASE WHEN @MonthsLoaded < 8  THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END,
        SampledBudget09     = CASE WHEN @MonthsLoaded < 9  THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END,
        SampledBudget10     = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END,
        SampledBudget11     = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END,
        SampledBudget12     = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END,
        InitialProjection01 = CASE WHEN @MonthsLoaded < 1  THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END,
        InitialProjection02 = CASE WHEN @MonthsLoaded < 2  THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END,
        InitialProjection03 = CASE WHEN @MonthsLoaded < 3  THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END,
        InitialProjection04 = CASE WHEN @MonthsLoaded < 4  THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END,
        InitialProjection05 = CASE WHEN @MonthsLoaded < 5  THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END,
        InitialProjection06 = CASE WHEN @MonthsLoaded < 6  THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END,
        InitialProjection07 = CASE WHEN @MonthsLoaded < 7  THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END,
        InitialProjection08 = CASE WHEN @MonthsLoaded < 8  THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END,
        InitialProjection09 = CASE WHEN @MonthsLoaded < 9  THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END,
        InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END,
        InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END,
        InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END,
        SampledProjection01 = CASE WHEN @MonthsLoaded < 1  THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END,
        SampledProjection02 = CASE WHEN @MonthsLoaded < 2  THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END,
        SampledProjection03 = CASE WHEN @MonthsLoaded < 3  THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END,
        SampledProjection04 = CASE WHEN @MonthsLoaded < 4  THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END,
        SampledProjection05 = CASE WHEN @MonthsLoaded < 5  THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END,
        SampledProjection06 = CASE WHEN @MonthsLoaded < 6  THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END,
        SampledProjection07 = CASE WHEN @MonthsLoaded < 7  THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END,
        SampledProjection08 = CASE WHEN @MonthsLoaded < 8  THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END,
        SampledProjection09 = CASE WHEN @MonthsLoaded < 9  THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END,
        SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END,
        SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END,
        SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END
    FROM [fp].[FactBenefits] fb
    INNER JOIN #YearValues v ON fb.BenefitsID = v.BenefitsID
    
    UPDATE fbb
    SET 
        AdjustedValue01 = fb.InitialBudget01,
        AdjustedValue02 = fb.InitialBudget02,
        AdjustedValue03 = fb.InitialBudget03,
        AdjustedValue04 = fb.InitialBudget04,
        AdjustedValue05 = fb.InitialBudget05,
        AdjustedValue06 = fb.InitialBudget06,
        AdjustedValue07 = fb.InitialBudget07,
        AdjustedValue08 = fb.InitialBudget08,
        AdjustedValue09 = fb.InitialBudget09,
        AdjustedValue10 = fb.InitialBudget10,
        AdjustedValue11 = fb.InitialBudget11,
        AdjustedValue12 = fb.InitialBudget12,
        FlexedValue01   = fb.InitialBudget01,
        FlexedValue02   = fb.InitialBudget02,
        FlexedValue03   = fb.InitialBudget03,
        FlexedValue04   = fb.InitialBudget04,
        FlexedValue05   = fb.InitialBudget05,
        FlexedValue06   = fb.InitialBudget06,
        FlexedValue07   = fb.InitialBudget07,
        FlexedValue08   = fb.InitialBudget08,
        FlexedValue09   = fb.InitialBudget09,
        FlexedValue10   = fb.InitialBudget10,
        FlexedValue11   = fb.InitialBudget11,
        FlexedValue12   = fb.InitialBudget12
    FROM [fp].[FactBenefitsBudget] fbb
    INNER JOIN [fp].[FactBenefits] fb ON fbb.BenefitsID = fb.BenefitsID
    INNER JOIN #YearValues v ON v.BenefitsID = fb.BenefitsID
    
    UPDATE fbb
    SET 
        AdjustedValue01 = CASE WHEN @MonthsLoaded < 1  THEN fb.InitialProjection01 ELSE ActualYTDValue01 END,
        AdjustedValue02 = CASE WHEN @MonthsLoaded < 2  THEN fb.InitialProjection02 ELSE ActualYTDValue02 END,
        AdjustedValue03 = CASE WHEN @MonthsLoaded < 3  THEN fb.InitialProjection03 ELSE ActualYTDValue03 END,
        AdjustedValue04 = CASE WHEN @MonthsLoaded < 4  THEN fb.InitialProjection04 ELSE ActualYTDValue04 END,
        AdjustedValue05 = CASE WHEN @MonthsLoaded < 5  THEN fb.InitialProjection05 ELSE ActualYTDValue05 END,
        AdjustedValue06 = CASE WHEN @MonthsLoaded < 6  THEN fb.InitialProjection06 ELSE ActualYTDValue06 END,
        AdjustedValue07 = CASE WHEN @MonthsLoaded < 7  THEN fb.InitialProjection07 ELSE ActualYTDValue07 END,
        AdjustedValue08 = CASE WHEN @MonthsLoaded < 8  THEN fb.InitialProjection08 ELSE ActualYTDValue08 END,
        AdjustedValue09 = CASE WHEN @MonthsLoaded < 9  THEN fb.InitialProjection09 ELSE ActualYTDValue09 END,
        AdjustedValue10 = CASE WHEN @MonthsLoaded < 10 THEN fb.InitialProjection10 ELSE ActualYTDValue10 END,
        AdjustedValue11 = CASE WHEN @MonthsLoaded < 11 THEN fb.InitialProjection11 ELSE ActualYTDValue11 END,
        AdjustedValue12 = CASE WHEN @MonthsLoaded < 12 THEN fb.InitialProjection12 ELSE ActualYTDValue12 END,
        FlexedValue01   = CASE WHEN @MonthsLoaded < 1  THEN fb.InitialProjection01 ELSE ActualYTDValue01 END,
        FlexedValue02   = CASE WHEN @MonthsLoaded < 2  THEN fb.InitialProjection02 ELSE ActualYTDValue02 END,
        FlexedValue03   = CASE WHEN @MonthsLoaded < 3  THEN fb.InitialProjection03 ELSE ActualYTDValue03 END,
        FlexedValue04   = CASE WHEN @MonthsLoaded < 4  THEN fb.InitialProjection04 ELSE ActualYTDValue04 END,
        FlexedValue05   = CASE WHEN @MonthsLoaded < 5  THEN fb.InitialProjection05 ELSE ActualYTDValue05 END,
        FlexedValue06   = CASE WHEN @MonthsLoaded < 6  THEN fb.InitialProjection06 ELSE ActualYTDValue06 END,
        FlexedValue07   = CASE WHEN @MonthsLoaded < 7  THEN fb.InitialProjection07 ELSE ActualYTDValue07 END,
        FlexedValue08   = CASE WHEN @MonthsLoaded < 8  THEN fb.InitialProjection08 ELSE ActualYTDValue08 END,
        FlexedValue09   = CASE WHEN @MonthsLoaded < 9  THEN fb.InitialProjection09 ELSE ActualYTDValue09 END,
        FlexedValue10   = CASE WHEN @MonthsLoaded < 10 THEN fb.InitialProjection10 ELSE ActualYTDValue10 END,
        FlexedValue11   = CASE WHEN @MonthsLoaded < 11 THEN fb.InitialProjection11 ELSE ActualYTDValue11 END,
        FlexedValue12   = CASE WHEN @MonthsLoaded < 12 THEN fb.InitialProjection12 ELSE ActualYTDValue12 END
    FROM [fp].[FactBenefitsProjection] fbb
    INNER JOIN [fp].[FactBenefits] fb ON fbb.BenefitsID = fb.BenefitsID
    INNER JOIN #YearValues v ON v.BenefitsID = fb.BenefitsID
END
GO


---------------------------------------------

-- fp.procUpdateProductivityTargets
/*************************************************************************************************************************
** Change History
**************************************************************************************************************************
** CID		Date		  Author  WI          Description
** 1	 	10/30/17	  MY	  B-17281	  Updates Productivity Targets If used
** 2	 	12/04/17	  MY	  B-18098	  Populate the Original Value at Sampling
** 3	 	01/17/18	  MY	  B-18464	  Add Projection Logic
** 4	 	05/17/18	  apukii  B-19131     Replace FixVar sqlgen with a FixVar table
** 5	 	07/09/18	  BK      B-19488     Update for new structure
** 6	 	10/22/18	  ipetriv B-19488     added source dimensionality
** 7	 	11/15/18	  PA 	  B-21059     filter by IsHoursIgnored=0
** 8	 	2019-03-26    IP      B-22466	  Switch usages of funcGetSourceDimensionalityAsTable to a temp table
** 9	 	2019-07-22    MY      B-23801	  Productivity Target should only use productive class pay code groups
** 10	 	2020-04-28    BK      D-09683	  Productivity Target should use only use months loaded for annualized and projection
** 11	 	2020-08-26    MD      JAZZ-20118  Remove Productivity Target Use MonthsLoaded Only FF
** 12		2022-11-07    MY      JAZZ-35951  Add EmployeeID to FactStaffingVariabilityDetail
** 13		2023-09-20    BK      JAZZ-60973  Update for new structure (again)
** 14		2024-06-14    SM      JAZZ-71536  change JobCodeID from smallint to int
** 15		2024-09-19    MY      JAZZ-76045  Missing Budget Config Filter
*************************************************************/
CREATE   PROCEDURE [fp].[procUpdateProductivityTargets]
	-- Add the parameters for the stored procedure here
	@BudgetConfigID INT,
	@EntityGroupConfigID INT,
	@EntityGroupConfigGUID UNIQUEIDENTIFIER,
	@PayrollFiscalYearID SMALLINT,
	@PayrollTimeClassID TINYINT,
	@MonthsLoaded INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
AS

BEGIN
 
	IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment;
	IF OBJECT_ID('tempdb..#GroupedByLowestLevel') IS NOT NULL DROP TABLE #GroupedByLowestLevel;
	IF OBJECT_ID('tempdb..#GroupedByLowestLevelProj') IS NOT NULL DROP TABLE #GroupedByLowestLevelProj;
	IF OBJECT_ID('tempdb..#GroupedByDepartmentTotal') IS NOT NULL DROP TABLE #GroupedByDepartmentTotal;
	IF OBJECT_ID('tempdb..#GroupedByDepartmentTotalProj') IS NOT NULL DROP TABLE #GroupedByDepartmentTotalProj;
	IF OBJECT_ID('tempdb..#ResultSet') IS NOT NULL DROP TABLE #ResultSet;
	IF OBJECT_ID('tempdb..#ProjectionResultSet') IS NOT NULL DROP TABLE #ProjectionResultSet;

	CREATE TABLE #FilterByDepartment (DepartmentID int)
	INSERT INTO #FilterByDepartment (DepartmentID)
	SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)

	IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN
		INSERT INTO #FilterByDepartment
		SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE BudgetConfigID = @BudgetConfigID
	END
	
	DECLARE @ProjectionFiscalYearID SMALLINT, @ProjectionTimeClassID INT			

	SELECT @ProjectionTimeClassID = 1,@ProjectionFiscalYearID = bc.FiscalYearID - 1
	FROM [fp].[BudgetConfig] bc 
	WHERE BudgetConfigID = @BudgetConfigID
	
	CREATE TABLE #GroupedByLowestLevel (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, [Value] DECIMAL(19,8))
	CREATE TABLE #GroupedByLowestLevelProj (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, [Value] DECIMAL(19,8))
	CREATE TABLE #GroupedByDepartmentTotal (DepartmentID INT,  [Value] DECIMAL(19,8))
	CREATE TABLE #GroupedByDepartmentTotalProj (DepartmentID INT,  [Value] DECIMAL(19,8))
	CREATE TABLE #ResultSet (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EntityID INT, BudgetConfigID INT, [Value] DECIMAL(19,8), EntityGroupConfigID INT)
	CREATE TABLE #ProjectionResultSet (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EntityID INT, BudgetConfigID INT, [Value] DECIMAL(19,8), EntityGroupConfigID INT)
	DECLARE @BudgetYear INT, @SourceYear INT		       
	SELECT @BudgetYear = FiscalYearID  FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID

	DECLARE @IsAnnualized BIT = (CASE WHEN @PayrollFiscalYearID = @BudgetYear - 1 AND @PayrollTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END)    

	INSERT INTO #GroupedByLowestLevel
			SELECT st.DepartmentID, 
					st.JobCodeID, 
					pc.PayCodeGroupID, 
					CASE 
	        			WHEN SUM(ISNULL(st.Value, 0)) = 0 THEN 0
						ELSE (ISNULL(MAX((1 - fv.FixedPercentage)), 0) * SUM(st.Value))
					END AS Value
			FROM [int].[FactStaffing] st  -- As of May 2020, we can't use fp.FactStaffing because variable hours in fp.FactStaffing have the working hours ratio applied to them and may differ from the values in int.FactStaffing
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = st.DepartmentID)
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv ON fv.DepartmentID = st.DepartmentID 
					AND fv.JobCodeID = st.JobCodeID
					AND fv.PayCodeID = st.PayCodeID
					AND fv.EmployeeID = 0 -- Only Variable Employees are going to be using Productivity Targets
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = st.PayCodeID 
				INNER JOIN [fp].[FlexConfigMapping] fcm ON 
					st.DepartmentID = fcm.DepartmentID
					AND st.JobCodeID = fcm.PRJobCodeID
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = st.FiscalMonthID   
			WHERE IsDeleted = 0 
				AND st.UnitTypeID = 51 
				AND st.FiscalYearID = @PayrollFiscalYearID AND st.TimeClassID = @PayrollTimeClassID
				AND fcm.EntityGroupConfigID = @EntityGroupConfigID
				AND fcm.FlexingTypeID = 3
				AND pc.IsHoursIgnored = 0
				AND pcg.ProductiveClassID = 3 -- Productive
				AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded))      
			GROUP BY st.DepartmentID, st.JobCodeID, pc.PayCodeGroupID
	
			INSERT INTO #GroupedByLowestLevelProj
			SELECT  st.DepartmentID, 
					st.JobCodeID, 
					pc.PayCodeGroupID, 
					CASE 
	        			WHEN SUM(ISNULL(st.Value, 0)) = 0 THEN 0
						ELSE (ISNULL(MAX((1 - fv.FixedPercentage)), 0) * SUM(st.Value))
					END AS Value
			FROM [int].[FactStaffing] st
			INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = st.DepartmentID)
				LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv ON fv.DepartmentID = st.DepartmentID 
					AND fv.JobCodeID = st.JobCodeID
					AND fv.PayCodeID = st.PayCodeID
					AND fv.EmployeeID = 0 -- Only Variable Employees are going to be using Productivity Targets
					AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID
				INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = st.PayCodeID 
				INNER JOIN [fp].[FlexConfigMapping] fcm ON 
					st.DepartmentID = fcm.DepartmentID
					AND st.JobCodeID = fcm.PRJobCodeID		
				INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID
				INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = st.FiscalMonthID   
			WHERE IsDeleted = 0 
				AND st.UnitTypeID = 51 
				AND st.FiscalYearID = @ProjectionFiscalYearID AND st.TimeClassID = @ProjectionTimeClassID
				AND fcm.EntityGroupConfigID = @EntityGroupConfigID
				AND fcm.FlexingTypeID = 3
				AND pc.IsHoursIgnored = 0
				AND pcg.ProductiveClassID = 3 -- Productive
				AND fm.SortOrder <= @MonthsLoaded      
			GROUP BY st.DepartmentID, st.JobCodeID, pc.PayCodeGroupID
	
	INSERT INTO #GroupedByDepartmentTotal
	SELECT DepartmentID, SUM(ISNULL(Value, 0)) as Value 
    FROM #GroupedByLowestLevel
    GROUP BY DepartmentID
    
	INSERT INTO #GroupedByDepartmentTotalProj
	SELECT DepartmentID, SUM(ISNULL(Value, 0)) as Value 
    FROM #GroupedByLowestLevelProj
    GROUP BY DepartmentID    
	
	INSERT INTO #ResultSet
    SELECT basis.DepartmentID, basis.JobCodeID, basis.PayCodeGroupID, basis.ProductiveClassID, basis.EntityID, 
		   basis.BudgetConfigID, 
		   CASE WHEN dept.Value = 0 THEN 0 ELSE 
		   COALESCE(fc.ProductivityTarget * (jc.Value/dept.Value), 0) END 
		   AS Value,
		   @EntityGroupConfigID AS EntityGroupConfigID
	FROM [fp].[Staffing] basis
		INNER JOIN #GroupedByLowestLevel jc ON basis.DepartmentID = jc.DepartmentID
			AND basis.JobCodeID = jc.JobCodeID
			AND basis.PayCodeGroupID = jc.PayCodeGroupID
		INNER JOIN #GroupedByDepartmentTotal dept ON basis.DepartmentID = dept.DepartmentID
		INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.DepartmentID = basis.DepartmentID
	WHERE fc.IsUsingProductivityTarget = 1
		AND basis.EntityGroupConfigID = @EntityGroupConfigID	
		AND fc.EntityGroupConfigGUID = @EntityGroupConfigGUID


	INSERT INTO #ProjectionResultSet
	SELECT basis.DepartmentID, basis.JobCodeID, basis.PayCodeGroupID, basis.ProductiveClassID, basis.EntityID,
		   basis.BudgetConfigID, 
		   CASE WHEN dept.Value = 0 THEN 0 ELSE 
		   COALESCE(fc.ProductivityTarget * (jc.Value/dept.Value), 0) END AS Value,
		   @EntityGroupConfigID AS EntityGroupConfigID
	FROM [fp].[Staffing] basis   --projection
		INNER JOIN #GroupedByLowestLevelProj jc ON basis.DepartmentID = jc.DepartmentID
			AND basis.JobCodeID = jc.JobCodeID
			AND basis.PayCodeGroupID = jc.PayCodeGroupID
		INNER JOIN #GroupedByDepartmentTotalProj dept ON basis.DepartmentID = dept.DepartmentID
		INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.DepartmentID = basis.DepartmentID 
	WHERE fc.EntityGroupConfigGUID = @EntityGroupConfigGUID
		AND fc.IsUsingProductivityTarget = 1
		AND basis.EntityGroupConfigID = @EntityGroupConfigID

		
	UPDATE basis
	SET    InitialBudgetRate01 = result.Value
		 , InitialBudgetRate02 = result.Value
		 , InitialBudgetRate03 = result.Value
		 , InitialBudgetRate04 = result.Value
		 , InitialBudgetRate05 = result.Value
		 , InitialBudgetRate06 = result.Value
		 , InitialBudgetRate07 = result.Value
		 , InitialBudgetRate08 = result.Value
		 , InitialBudgetRate09 = result.Value
		 , InitialBudgetRate10 = result.Value
		 , InitialBudgetRate11 = result.Value
		 , InitialBudgetRate12 = result.Value
	FROM [fp].[Staffing] basis
		INNER JOIN #ResultSet result ON 
				basis.BudgetConfigID = result.BudgetConfigID
			AND basis.DepartmentID = result.DepartmentID
			AND basis.JobCodeID = result.JobCodeID
			AND basis.PayCodeGroupID = result.PayCodeGroupID
			AND basis.ProductiveClassID = result.ProductiveClassID
			AND basis.EntityID = result.EntityID	
	
		
	UPDATE basis
	SET    InitialProjectionRate01 = CASE WHEN @MonthsLoaded < 1 THEN result.Value ELSE 0 END
		 , InitialProjectionRate02 = CASE WHEN @MonthsLoaded < 2 THEN result.Value ELSE 0 END 
		 , InitialProjectionRate03 = CASE WHEN @MonthsLoaded < 3 THEN result.Value ELSE 0 END
		 , InitialProjectionRate04 = CASE WHEN @MonthsLoaded < 4 THEN result.Value ELSE 0 END
		 , InitialProjectionRate05 = CASE WHEN @MonthsLoaded < 5 THEN result.Value ELSE 0 END
		 , InitialProjectionRate06 = CASE WHEN @MonthsLoaded < 6 THEN result.Value ELSE 0 END
		 , InitialProjectionRate07 = CASE WHEN @MonthsLoaded < 7 THEN result.Value ELSE 0 END
		 , InitialProjectionRate08 = CASE WHEN @MonthsLoaded < 8 THEN result.Value ELSE 0 END
		 , InitialProjectionRate09 = CASE WHEN @MonthsLoaded < 9 THEN result.Value ELSE 0 END
		 , InitialProjectionRate10 = CASE WHEN @MonthsLoaded < 10 THEN result.Value ELSE 0 END
		 , InitialProjectionRate11 = CASE WHEN @MonthsLoaded < 11 THEN result.Value ELSE 0 END
		 , InitialProjectionRate12 = CASE WHEN @MonthsLoaded < 12 THEN result.Value ELSE 0 END
	FROM [fp].[Staffing] basis
		INNER JOIN #ProjectionResultSet result ON 
				basis.BudgetConfigID = result.BudgetConfigID
			AND basis.DepartmentID = result.DepartmentID
			AND basis.JobCodeID = result.JobCodeID
			AND basis.PayCodeGroupID = result.PayCodeGroupID
			AND basis.ProductiveClassID = result.ProductiveClassID
			AND basis.EntityID = result.EntityID			 
	
	
	UPDATE basis
	SET    TargetAdjustedRate01 = InitialBudgetRate01 
		 , TargetAdjustedRate02 = InitialBudgetRate02 
		 , TargetAdjustedRate03 = InitialBudgetRate03
		 , TargetAdjustedRate04 = InitialBudgetRate04
		 , TargetAdjustedRate05 = InitialBudgetRate05
		 , TargetAdjustedRate06 = InitialBudgetRate06
		 , TargetAdjustedRate07 = InitialBudgetRate07
		 , TargetAdjustedRate08 = InitialBudgetRate08
		 , TargetAdjustedRate09 = InitialBudgetRate09
		 , TargetAdjustedRate10 = InitialBudgetRate10
		 , TargetAdjustedRate11 = InitialBudgetRate11
		 , TargetAdjustedRate12 = InitialBudgetRate12
		 , BudgetAdjustedRate01 = InitialBudgetRate01 
		 , BudgetAdjustedRate02 = InitialBudgetRate02 
		 , BudgetAdjustedRate03 = InitialBudgetRate03
		 , BudgetAdjustedRate04 = InitialBudgetRate04
		 , BudgetAdjustedRate05 = InitialBudgetRate05
		 , BudgetAdjustedRate06 = InitialBudgetRate06
		 , BudgetAdjustedRate07 = InitialBudgetRate07
		 , BudgetAdjustedRate08 = InitialBudgetRate08
		 , BudgetAdjustedRate09 = InitialBudgetRate09
		 , BudgetAdjustedRate10 = InitialBudgetRate10
		 , BudgetAdjustedRate11 = InitialBudgetRate11
		 , BudgetAdjustedRate12 = InitialBudgetRate12
		 , ProjectionAdjustedRate01 = InitialProjectionRate01 
		 , ProjectionAdjustedRate02 = InitialProjectionRate02 
		 , ProjectionAdjustedRate03 = InitialProjectionRate03
		 , ProjectionAdjustedRate04 = InitialProjectionRate04
		 , ProjectionAdjustedRate05 = InitialProjectionRate05
		 , ProjectionAdjustedRate06 = InitialProjectionRate06
		 , ProjectionAdjustedRate07 = InitialProjectionRate07
		 , ProjectionAdjustedRate08 = InitialProjectionRate08
		 , ProjectionAdjustedRate09 = InitialProjectionRate09
		 , ProjectionAdjustedRate10 = InitialProjectionRate10
		 , ProjectionAdjustedRate11 = InitialProjectionRate11
		 , ProjectionAdjustedRate12 = InitialProjectionRate12
	FROM [fp].[Staffing] basis
		INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = basis.DepartmentID)	
	WHERE basis.ProductiveClassID = 3 -- Productive
		AND basis.BudgetConfigID = @BudgetConfigID

END;
GO


---------------------------------------------

-- fp.procUpdateSystemCenterScreensSecurity
/*************************************************************
** Change History
**************************************************************
** CID		Date		    Author		WI			Description
** 1		2019-01-09		kzhuk		B-21502		Created
** 2		2019-01-11		gforeman	B-21502		Added roster
** 3									B-22226		SEE BELOW FOR PROPOSED CHANGES
** 4        2019-03-27      OV          B-22369     leave screens enabled if "AP Preview Enabled" = 1
** 5		2019-08-12		NL		 	D-08644		fixing bug where stuff wasn't being enabled properly
** 6		2021-12-21		SD			JAZZ-30939	Hide OB system center pages when OnePlan is enabled
** 7		2022-06-21		SD			JAZZ-34197	Enable pages for new clients that use only PlanEditor
** 8		2023-08-22		LR			JAZZ-54949	Hide\Show OB pages when OnePlan is enabled on Maintenance Mode
***************************************************************/
CREATE procEDURE [fp].[procUpdateSystemCenterScreensSecurity] 
AS
BEGIN
	declare @groupObSysAdmin uniqueidentifier
	select @groupObSysAdmin = UserGroupGUID from UserGroup where GlobalID = 'OB - System Administrator'

	DECLARE @isReadValue bit = 1
	
	-- if the AP is enabled or the AP preview is enabled, then we want to make sure any dependent sys center pages are also enabled
    IF (EXISTS (SELECT 1 FROM fp.SystemSetting WHERE Name = 'Is APE Enabled' AND Value = '1') /* We only want DBs with OnePlan functionality enabled */
		AND EXISTS (SELECT 1 FROM fp.SystemSetting WHERE Name = 'AP Preview Enabled' AND Value = '0'))/* Clients stil in Preview mode need to keep these pages enabled */
	  BEGIN
		SET @isReadValue = 0
	  END

		UPDATE s3 SET ReadValue = @isReadValue
		FROM [dbo].[S3SimplePermission] s3
			JOIN [dbo].[UserGroup] ug ON s3.IdentityGUID=ug.UserGroupGUID
			JOIN [dbo].[SystemCenterSection] scsec ON s3.LootID = scsec.SectionGUID
			JOIN [dbo].[SystemCenterCategory] sccat ON scsec.CategoryGUID=sccat.CategoryGUID
			JOIN [dbo].[SystemCenterModule] scmod ON sccat.ModuleGUID=scmod.ModuleGUID
		WHERE 1=1
			AND ug.GlobalID = 'OB - System Administrator'
			/* Setup mode is for Strata users so it is lower priority, will update later */
			AND sccat.IsMaintenanceMode=1
			AND scmod.Name = 'Operating Budgeting'
			/* Exceptions - The list of pages still used by OnePlan clients */
			AND scsec.Name NOT IN (
				'Budgeted Department Setup',
				'Payroll to General Ledger Link',
				'Metrics Setup',
				'Primary Statistics Configuration',
				'Manage Plan Configurations',
				'Manage Roster Budgeting Configurations'
			)

-- Enable pages for new clients that use only PlanEditor
		UPDATE s3 SET ReadValue = 1
		FROM [dbo].[S3SimplePermission] s3
			JOIN [dbo].[UserGroup] ug ON s3.IdentityGUID=ug.UserGroupGUID
			JOIN [dbo].[SystemCenterSection] scsec ON s3.LootID = scsec.SectionGUID
			JOIN [dbo].[SystemCenterCategory] sccat ON scsec.CategoryGUID=sccat.CategoryGUID
			JOIN [dbo].[SystemCenterModule] scmod ON sccat.ModuleGUID=scmod.ModuleGUID
		WHERE ug.GlobalID = 'OB - System Administrator'
			/* Setup mode is for Strata users so it is lower priority, will update later */
			AND sccat.IsMaintenanceMode=1
			AND scmod.Name = 'Operating Budgeting'
			/* The list of pages still used by OnePlan clients */
			AND scsec.Name IN (
				'Budgeted Department Setup',
				'Payroll to General Ledger Link',
				'Metrics Setup',
				'Primary Statistics Configuration',
				'Manage Plan Configurations',
				'Manage Roster Budgeting Configurations'
			)

	declare @isRosterEnabled bit
	select @isRosterEnabled = Value from ob.SystemSetting where name='Is Roster Budgeting Enabled'

	UPDATE [dbo].[S3SimplePermission] SET ReadValue = @isRosterEnabled WHERE IdentityGuid = @groupObSysAdmin AND LootID = '1C04F259-8150-4909-A3F3-EBB23CDE6438'
END
GO


---------------------------------------------

-- fp.procVariableDirectCostPerUnitPopulate
-- =============================================
-- Author:		Michael Young
-- Create date: 4/5/2016
-- Description:	Populates VariableDirectCostPerUnit in fp.FactDepartmentChargeVolumeBasis
-- Change History:
-- *1	NL	1/28/19	 Complete re-write
-- *2	BK	4/22/19	 Add null check on update [TK-73046]
-- *3	BK	11/11/21 Limit to only the departments that use PAF
-- *4  NT 01/26/23   JAZZ-48268 Make change to update fp.ChargeVolume (data restructure)
-- =============================================

CREATE PROCEDURE [fp].[procVariableDirectCostPerUnitPopulate]
	@LatestCostingResult AS INT,
	@CostingTimeClassFromBudgetConfig AS TINYINT,
	@BudgetConfigID AS SMALLINT
	WITH RECOMPILE
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
		SET NOCOUNT ON;

	IF OBJECT_ID('tempdb..#Dept') IS NOT NULL DROP TABLE #Dept
	IF OBJECT_ID('tempdb..#UnitCostsPerRVU') IS NOT NULL DROP TABLE #UnitCostsPerRVU
	IF OBJECT_ID('tempdb..#VariableDirectUnitCost') IS NOT NULL DROP TABLE #VariableDirectUnitCost
	IF OBJECT_ID('tempdb..#Costing') IS NOT NULL DROP TABLE #Costing
	

	DECLARE @CostingConfigGUID uniqueidentifier;
	SELECT @CostingConfigGUID = CostingConfigGUID FROM [dss].[CostingResult] WHERE CostingResultID = @LatestCostingResult;
	
	CREATE TABLE #UnitCostsPerRVU (DepartmentID INT, CostComponentID INT, UnitCostPerRVU DECIMAL(19,8))
	CREATE TABLE  #VariableDirectUnitCost (DepartmentID INT, ChargeCodeID INT, ServiceLineID INT, PatientClassID INT, VariableDirectUnitCostNew DECIMAL(19,8))
	
	DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER
	SELECT @BudgetConfigGUID = BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID

	CREATE TABLE #Dept (DepartmentID INT)
	INSERT INTO #Dept (DepartmentID) 
	SELECT DISTINCT DepartmentID 
	FROM fp.FlexConfigMapping fcm INNER JOIN fp.EntityGroupConfig ecg ON fcm.EntityGroupConfigID = ecg.EntityGroupConfigID 
	WHERE FlexingTypeID = 7 AND ecg.BudgetConfigGUID = @BudgetConfigGUID

	CREATE TABLE #Costing (DepartmentID INT, CostComponentID INT, ChargeCodeID INT, Volume DECIMAL(19,8), TotalVariableDirectCost DECIMAL(19,8))
	
	INSERT INTO #Costing(DepartmentID, CostComponentID, ChargeCodeID, Volume, TotalVariableDirectCost)
		SELECT gl.OriginalDepartmentID, gl.CostComponentID, gl.ChargeCodeID, gl.Volume, gl.VariableDirectUnitCost * gl.Volume as TotalVariableDirectCost 
					 FROM [dss].[FactCostingOutDetailGL] gl INNER JOIN #Dept d on gl.DepartmentID = d.DepartmentID
					 WHERE gl.CostingResultID = @LatestCostingResult AND gl.TimeClassID = @CostingTimeClassFromBudgetConfig 
		UNION ALL
		 SELECT pr.OriginalDepartmentID, pr.CostComponentID, pr.ChargeCodeID, pr.Volume, pr.VariableDirectUnitCost * pr.Volume as TotalVariableDirectCost 
			     FROM [dss].[FactCostingOutDetailPayroll] pr INNER JOIN #Dept d on pr.DepartmentID = d.DepartmentID
			     WHERE pr.CostingResultID = @LatestCostingResult AND pr.TimeClassID = @CostingTimeClassFromBudgetConfig

	INSERT INTO #UnitCostsPerRVU (DepartmentID, CostComponentID, UnitCostPerRVU)
	SELECT cost.DepartmentID, cost.CostComponentID, sum(TotalCost/NULLIF(volume, 0))/NULLIF(sum(ca.RVU), 0) as UnitCostPerRVU
		FROM 
		 (   SELECT
			    co.DepartmentID, 
			    co.CostComponentID,
				co.ChargeCodeID,
			    sum(TotalVariableDirectCost) as TotalCost, Max(Volume) as Volume
			 FROM #Costing co
			 GROUP BY co.DepartmentID, co.CostComponentID, co.ChargeCodeID
		 ) cost

			INNER JOIN [dss].[ChargeAllocation] ca
		        ON cost.DepartmentID = ca.DepartmentID
		        AND cost.CostComponentID = ca.CostComponentID
				AND cost.ChargeCodeID = ca.ChargeCodeID
		WHERE ca.CostingConfigGuid = @CostingConfigGUID AND ca.AllocationType = 1 AND ca.IsFixed = 0 AND ca.IsIndirect = 0
		GROUP BY cost.DepartmentID, cost.CostComponentID

		
	 INSERT INTO #VariableDirectUnitCost (DepartmentID, ChargeCodeID, ServiceLineID, PatientClassID, VariableDirectUnitCostNew)
		SELECT f.DepartmentID, f.ChargeCodeID, f.ServiceLineID, f.PatientClassID, SUM(UnitCostPerRVU * RVU) as VariableDirectUnitCostNew
		FROM [fp].[ChargeVolume] f
			INNER JOIN [dss].[ChargeAllocation] ca
				ON f.ChargeCodeID = ca.ChargeCodeID
				AND f.DepartmentID = ca.DepartmentID
			INNER JOIN #UnitCostsPerRVU t
				ON f.DepartmentID = t.DepartmentID
				AND ca.CostComponentID = t.CostComponentID
		WHERE f.BudgetConfigID = @BudgetConfigID
			  and ca.CostingConfigGuid = @CostingConfigGUID
		      AND ca.AllocationType = 1 AND ca.IsFixed = 0 AND ca.IsIndirect = 0 AND ca.RVU != 0
			  and f.UnitTypeID = 145
		GROUP BY f.DepartmentID, f.ChargeCodeID, f.ServiceLineID, f.PatientClassID
	

			
	UPDATE f
	SET f.VariableDirectUnitCost = COALESCE(VariableDirectUnitCostNew, 0)
    FROM [fp].[ChargeVolume] f
		 INNER JOIN #VariableDirectUnitCost v
		 	ON f.DepartmentID = v.DepartmentID
			AND f.ChargeCodeID = v.ChargeCodeID
			AND f.ServiceLineID = v.ServiceLineID
			AND f.PatientClassID = v.PatientClassID
    WHERE f.BudgetConfigID = @BudgetConfigID
          and f.UnitTypeID = 145	

END
GO


---------------------------------------------

---------------------------------------------
--  FUNCTIONS
---------------------------------------------

-- fp.GetAdjustmentHierarchyEntityIDs
CREATE FUNCTION [fp].[GetAdjustmentHierarchyEntityIDs]
( 
	@groupingHierarchyJSON VARCHAR(MAX)   
)  
RETURNS @adjustmentHierarchyDepartmentIDs TABLE (
	EntityID INT
)
AS
    BEGIN   
		DECLARE @level VARCHAR(MAX);
		DECLARE @hierarchyPathArray VARCHAR(MAX);

		SELECT @level = gh.[value] 
		FROM OPENJSON(@groupingHierarchyJSON, '$.Levels') AS gh
		CROSS APPLY OPENJSON(gh.[value]) AS ghr
		WHERE ghr.[key] ='Name' AND ghr.[value] = 'Entity'

		SELECT @hierarchyPathArray = [value] 
		FROM OPENJSON(@level) 
		WHERE [key] ='HierarchyPaths'
		
		INSERT INTO @adjustmentHierarchyDepartmentIDs
		SELECT CAST(RIGHT(hpi.[value], charindex('|', reverse(hpi.[value]) + '|') - 1) AS INT) AS EntitiyID
		FROM OPENJSON(@hierarchyPathArray) AS hp
		CROSS APPLY OPENJSON(hp.value) AS hpi
		WHERE hpi.[key] = 'id'

		RETURN;
    END
GO


---------------------------------------------

-- fp.GetAdjustmentHierarchyIDs
CREATE   FUNCTION [fp].[GetAdjustmentHierarchyIDs]
( 
	@groupingHierarchyJSON VARCHAR(MAX),
	@entityName VARCHAR(50) 
)  
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI   Description
 ** 1 	 2021-07-28  OP  	 JAZZ-8052	Handled case when there is no ID at the hierarchy end
 *************************************************************/
RETURNS @adjustmentHierarchyIDs TABLE (
	ID INT
)
AS
    BEGIN   
		DECLARE @level VARCHAR(MAX);
		DECLARE @hierarchyPathArray VARCHAR(MAX);

		SELECT @level = gh.[value] 
		FROM OPENJSON(@groupingHierarchyJSON, '$.Levels') AS gh
		CROSS APPLY OPENJSON(gh.[value]) AS ghr
		WHERE ghr.[key] ='Name' AND ghr.[value] = @entityName

		SELECT @hierarchyPathArray = [value] 
		FROM OPENJSON(@level) 
		WHERE [key] ='HierarchyPaths'

		INSERT INTO @adjustmentHierarchyIDs
		SELECT TRY_CAST(RIGHT(hpi.[value], charindex('|', reverse(hpi.[value]) + '|') - 1) AS INT) AS ID
		FROM OPENJSON(@hierarchyPathArray) AS hp
		CROSS APPLY OPENJSON(hp.value) AS hpi
		WHERE hpi.[key] = 'id'
		
		RETURN;
    END
GO


---------------------------------------------

-- fp.GetAdjustmentMeasure
CREATE FUNCTION fp.GetAdjustmentMeasure
( 
	@AdjustmentType TINYINT,
	@unitTypeId TINYINT
)  
RETURNS VARCHAR(25)
    BEGIN   
		DECLARE @adjustmentMeasureString VARCHAR(25);
		
		-- Keeping original 'logic' from C#:

		IF @AdjustmentType = 6 -- FTE
			RETURN 'FTEs';

        SET @adjustmentMeasureString = CASE
			WHEN (@unitTypeId = 33 -- ID_DOLLARSPERUOS
				OR @unitTypeId = 34) -- ID_DOLLARS
				THEN 'Dollars$'
			WHEN @unitTypeId = 51 -- ID_HOURS
				THEN 'Hours'
			WHEN @unitTypeId = 144 -- ID_FTES
				THEN 'FTEs'
			WHEN @unitTypeId = 140 -- ID_VOLUME
				THEN 'Volume'
			WHEN @unitTypeId = 159 -- ID_WAGERATE
				THEN 'Wage Rate$'
			WHEN @unitTypeId = 169 -- ID_SALARIES
				THEN 'Salaries$'
			WHEN @unitTypeId = 170 -- ID_PERCENTOFSALARIES
				THEN '% of Salary'
			WHEN @unitTypeId = 171 -- ID_DOLLARSPERFTE
				THEN '$ Per FTE'
			WHEN @unitTypeId = 172 -- ID_HOURSPERUOS
				THEN 'Hours per UOS'
			WHEN @unitTypeId = 145 -- ID_UNITS
				THEN 'Units'
		   ELSE ''
		  END;

        RETURN @adjustmentMeasureString  
    END
GO


---------------------------------------------

-- fp.GetAdjustmentPath
CREATE FUNCTION [fp].[GetAdjustmentPath]
( 	
	@adjustmentFilterJSON VARCHAR(MAX),
	@hierarhyJSON VARCHAR(MAX),
	@PlanSectionID TINYINT
)  
RETURNS NVARCHAR(MAX)
BEGIN 

DECLARE @result NVARCHAR(max)    
DECLARE @HierarhyParsed TABLE(
    Name VARCHAR(50),
    LevelID VARCHAR(50),
    IsHidden BIT,
    IsDisabled BIT,
    Value VARCHAR(500)
)

INSERT INTO @HierarhyParsed(Name, LevelID, IsHidden, isDisabled)
SELECT Name, LevelID, IsHidden, IsDisabled
FROM OPENJSON(@hierarhyJSON, '$.Levels')
WITH ( Name VARCHAR(50) '$.Name',
       LevelID VARCHAR(50) '$.LevelID',
       IsHidden BIT '$.IsHidden',
       IsDisabled BIT '$.IsDisabled')


-------------- SERVICE LINE -----------------------------
IF @PlanSectionID = 1
BEGIN
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLineRollup.Name') WHERE Name = 'Service Line Rollup'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLine.Name') WHERE Name = 'Service Line'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MedicalSurgical.Name') WHERE Name = 'Medical/Surgical'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.AgeCohort.Name') WHERE Name = 'Age Cohort'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Payor.Name') WHERE Name = 'Payor'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PayorGroup.Name') WHERE Name = 'Payor Group'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MSDRG.Name') WHERE Name = 'MSDRG'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.CPT.Name') WHERE Name = 'CPT'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name') WHERE Name = 'Provider'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name') WHERE Name = 'Provider Specialty'
END

--------------- CHARGE VOLUME -------------
IF @PlanSectionID = 2
BEGIN
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ChargeCode.Name') WHERE Name = 'Charge Code'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLine.Name') WHERE Name = 'Service Line'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MedicalSurgical.Name') WHERE Name = 'Medical/Surgical'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.AgeCohort.Name') WHERE Name = 'Age Cohort'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceEntity.Name') WHERE Name = 'Service Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MSDRG.Name') WHERE Name = 'MSDRG'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.UBRevCode.Name') WHERE Name = 'Revenue Code'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PrimaryCPT.Name') WHERE Name = 'Primary CPT'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProvider.Name') WHERE Name = 'Service Provider'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProviderSpecialty.Name') WHERE Name = 'Service Provider Specialty'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProvider.Name') WHERE Name = 'Performing Provider'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProviderSpecialty.Name') WHERE Name = 'Performing Provider Specialty'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.BillingCPT.Name') WHERE Name = 'Billing CPT'
END

---------------------STATISTICS
IF @PlanSectionID = 3
BEGIN
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name') WHERE Name = 'Account'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name') WHERE Name = 'Provider'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name') WHERE Name = 'Financial Reporting Rollup'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Payor.Name') WHERE Name = 'Payor'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderType.Name') WHERE Name = 'Provider Type'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderLineItem.Name') WHERE Name = 'Provider Line Item'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name') WHERE Name = 'Provider Specialty'
END

----------------------STAFFFING
IF @PlanSectionID = 4
BEGIN
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PayCodeGroup.Name') WHERE Name = 'Pay Code Group'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.JobCode.Name') WHERE Name = 'Job Code'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Variability.Name') WHERE Name = 'Fixed/Variable'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProductiveClass.Name') WHERE Name = 'Productive Class'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Employee.Name') WHERE Name = 'Employee'
-------------PROVIDER COMPENSATION
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name') WHERE Name = 'Provider Specialty'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderLineItem.Name') WHERE Name = 'Provider Line Item'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name') WHERE Name = 'Provider'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderType.Name') WHERE Name = 'Provider Type'
END

-----------------BENEFITS-------
IF @PlanSectionID = 5
BEGIN
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name') WHERE Name = 'Financial Reporting Rollup'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name') WHERE Name = 'Account'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department'
END

-------------------GL -----------------------
IF @PlanSectionID = 6
BEGIN
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name') WHERE Name = 'Financial Reporting Rollup'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name') WHERE Name = 'Account'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Variability.Name') WHERE Name = 'Fixed/Variable'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department'
END

-------------------Reimbursement -----------------------
IF @PlanSectionID = 7
BEGIN
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class'
    UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PayorGroup.Name') WHERE Name = 'Payor Group'
END

SELECT @result = ( SELECT STRING_AGG(Value, ' => ') FROM @HierarhyParsed WHERE IsHidden = 0 AND IsDisabled = 0)

RETURN COALESCE(@result, '')
END
GO


---------------------------------------------

-- fp.GetAdjustmentReportValue
CREATE FUNCTION [fp].[GetAdjustmentReportValue]
( 
	@AdjustmentValue DECIMAL(19,4),
	@AdjustmentType TINYINT
)  
RETURNS VARCHAR(25)
    BEGIN   
		DECLARE @adjustmentValueString VARCHAR(25);

        SET @adjustmentValueString = CASE
			WHEN @AdjustmentType = 1 -- Percentage
				THEN CAST(CAST(@AdjustmentValue * 100 AS DECIMAL(19,2)) AS VARCHAR(23)) + '%'
			WHEN @AdjustmentType = 10
			   THEN 'Lock'
			WHEN @AdjustmentType = 11
			   THEN 'Unlock'
			ELSE CONVERT(VARCHAR(25), CAST(ROUND(@AdjustmentValue, 2, 1) AS DECIMAL(19,2)))
		  END;

        RETURN @adjustmentValueString  
    END
GO


---------------------------------------------

-- fp.GetAdjustmentTimeClass
CREATE FUNCTION fp.GetAdjustmentTimeClass
( 
	@timeClassID TINYINT,
	@budgetPhaseID TINYINT
)  
RETURNS TINYINT
    BEGIN   
		DECLARE @adjustmentTimeClass TINYINT;
		
		SET @adjustmentTimeClass = CASE
			WHEN @timeClassID = 12
				THEN 12
			WHEN (@timeClassID = 2
					AND @budgetPhaseID = 2) -- Admin
				THEN 20
			WHEN (@timeClassID = 2
					AND @budgetPhaseID = 3) -- Department
				THEN 2
		   ELSE 0
		  END;

        RETURN @adjustmentTimeClass  
    END
GO


---------------------------------------------

-- fp.GetAdjustmentTimeClassString
CREATE FUNCTION fp.GetAdjustmentTimeClassString
( 
	@adjustmentType TINYINT,
	@timeClassID TINYINT,
	@budgetPhaseID TINYINT
)  
RETURNS VARCHAR(25)
    BEGIN   
		DECLARE @adjustmentTimeClassString VARCHAR(25);
		
		IF (@adjustmentType = 6 AND @timeClassID = 0) -- FTE
		BEGIN
			RETURN 'target'
		END

		SET @adjustmentTimeClassString = CASE
			WHEN @timeClassID = 12
				THEN 'projection'
			WHEN (@timeClassID = 2
					AND @budgetPhaseID = 2) -- Admin
				THEN 'target'
			WHEN (@timeClassID = 2
					AND @budgetPhaseID = 3) -- Department
				THEN 'budget'
		   ELSE ''
		  END;

        RETURN @adjustmentTimeClassString  
    END
GO


---------------------------------------------

-- fp.GetAdjustmentType
CREATE FUNCTION [fp].[GetAdjustmentType]
( 
	@AdjustmentType TINYINT   
)  
RETURNS VARCHAR(20)
    BEGIN   
		DECLARE @adjustmentTypeString VARCHAR(20);

        SET @adjustmentTypeString = CASE
			WHEN @AdjustmentType = 0
				THEN 'Incremental'
			WHEN @AdjustmentType = 1
				THEN 'Percentage%'
			WHEN @AdjustmentType = 2
				THEN 'Set Value'
			WHEN @AdjustmentType = 3
				THEN  'Final'
			WHEN @AdjustmentType = 4
				THEN 'Imported'
			WHEN @AdjustmentType = 5
				THEN 'Mix'
			WHEN @AdjustmentType = 6
				THEN 'FTE'
			WHEN @AdjustmentType = 7
				THEN 'Manager'
			WHEN @AdjustmentType = 8
				THEN 'Varuable Reset'
			WHEN @AdjustmentType = 9
				THEN 'Spread Unlock'
			WHEN @AdjustmentType = 10
				THEN 'Lock'
			WHEN @AdjustmentType = 11
				THEN 'Unlock'
			WHEN @AdjustmentType = 12
				THEN 'Set Value'
			WHEN @AdjustmentType = 13
				THEN 'Final Value'
			WHEN @AdjustmentType = 14
				THEN 'Incremental'
			WHEN @AdjustmentType = 15
				THEN 'Add Provider'
			WHEN @AdjustmentType = 20
				THEN 'Manager Set'
		   ELSE ''
		  END;

        RETURN @adjustmentTypeString  
    END
GO


---------------------------------------------

-- fp.GetAdjustmentValue
CREATE FUNCTION [fp].[GetAdjustmentValue]
( 
	@AdjustmentValue DECIMAL(19,4),
	@AdjustmentType TINYINT   
)  
RETURNS VARCHAR(25)
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2020-01-15  OP  	 JAZZ-12268		Now returning "5.00%" values for percentage adjustments
 *************************************************************/
    BEGIN   
		DECLARE @adjustmentValueString VARCHAR(25);

        SET @adjustmentValueString = CASE
			WHEN @AdjustmentType = 1 -- Percentage
				--THEN @AdjustmentValue * 100
				THEN CAST(CAST(@AdjustmentValue * 100 AS DECIMAL(19,2)) AS VARCHAR(23)) + '%'
		   ELSE CAST(@AdjustmentValue AS VARCHAR(23))
		  END;

        RETURN @adjustmentValueString  
    END
GO


---------------------------------------------

-- fp.GetIsNetRevenueModelLocked
CREATE   FUNCTION [fp].[GetIsNetRevenueModelLocked]
(@budgetConfigGuid UNIQUEIDENTIFIER)
	RETURNS BIT
AS
BEGIN
	IF EXISTS(
	SELECT	1
	FROM	fp.ReimbursementGeneralLedgerAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid

	UNION ALL

	SELECT	1
	FROM	fp.ReimbursementAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid	
	)
	BEGIN
		RETURN CAST(1 AS BIT)
	END

	RETURN CAST(0 AS BIT) 
END
GO


---------------------------------------------

-- fp.GetIsSectionSetupLocked
CREATE   FUNCTION [fp].[GetIsSectionSetupLocked]
(@budgetConfigGuid UNIQUEIDENTIFIER)
	RETURNS BIT
AS
BEGIN
	IF EXISTS(
	SELECT	1
	FROM	fp.StaffingAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid

	UNION ALL

	SELECT	1
	FROM	fp.BenefitsAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid

	UNION ALL

	SELECT	1
	FROM	fp.DepartmentChargeVolumeAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid

	UNION ALL

	SELECT	1
	FROM	fp.GeneralLedgerAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid

	UNION ALL

	SELECT	1
	FROM	fp.ServiceLineEncounterAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid

	UNION ALL

	SELECT	1
	FROM	fp.StatisticsAdjustment a
	WHERE	a.BudgetConfigGuid = @budgetConfigGuid	
	)
	BEGIN
		RETURN CAST(0 AS BIT)
	END

	RETURN CAST(1 AS BIT) 
END
GO


---------------------------------------------

-- fp.SearchAdjustmentMeasureForImport
CREATE FUNCTION fp.SearchAdjustmentMeasureForImport
( 
	@AdjustmentType TINYINT,
	@importUnitTypeIDs VARCHAR(MAX),
	@search VARCHAR(MAX)
)  
RETURNS BIT
    BEGIN   
		DECLARE @result BIT = 0;

		IF EXISTS(
			SELECT 1
			FROM	(
				SELECT	[value]
				FROM	STRING_SPLIT(@importUnitTypeIDs, ' ')
			) AS res
			WHERE LOWER(fp.GetAdjustmentMeasure(@AdjustmentType, res.[value])) LIKE @search ESCAPE '\')
		BEGIN
			SET @result = 1
		END

        RETURN @result  
    END
GO


---------------------------------------------

-- fp.SearchHierarchyLevel
CREATE FUNCTION fp.SearchHierarchyLevel
( 	
	@adjustmentFilterJSON VARCHAR(MAX),
	@search VARCHAR(MAX)
)  
RETURNS BIT
    BEGIN   
		DECLARE @containsSearchString BIT = 0;

		IF (
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.AgeCohort.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.MedicalSurgical.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLine.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ChargeCode.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Payor.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.JobCode.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.JobCodeGroup.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PayCodeGroup.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProductiveClass.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Variability.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLineRollup.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.BillingCPT.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.MSDRG.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProvider.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProviderSpecialty.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PrimaryCPT.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceEntity.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProvider.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProviderSpecialty.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.UBRevCode.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.CPT.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PayorGroup.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PhysicianSpecialty.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Employee.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProviderLineItem.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProviderType.Name')) LIKE @search ESCAPE '\' OR
			LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name')) LIKE @search ESCAPE '\'
			)
			SET @containsSearchString = 1;

		RETURN @containsSearchString;
    END
GO


---------------------------------------------

-- fp.funcCompareAdjustmentDateTime
CREATE FUNCTION [fp].[funcCompareAdjustmentDateTime]
( 
	@adjustmentDate DATETIME,
	@search VARCHAR(MAX),
	@dateTimeFormat VARCHAR(30),
	@userTimeZone VARCHAR(50)
)  
RETURNS BIT
/**************************************************************
 ** Change History
 **************************************************************
 ** CID  Date        Author  WI				Description
 ** 1 	 2020-01-15  OP  	 JAZZ-12268		Now skipping date check for search values that are containing "%" (that is modified into "\%" on backend)
 *************************************************************/
    BEGIN
		DECLARE @result BIT = 0

		IF CHARINDEX('\%', @search) = 0 
		BEGIN

    		DECLARE @utcTimeZone VARCHAR(5) = 'UTC'
    		SET @adjustmentDate = @adjustmentDate AT TIME ZONE @utcTimeZone AT TIME ZONE @userTimeZone
		
			DECLARE @formatedAdjustmentDateTime VARCHAR(50) = FORMAT(@adjustmentDate, @dateTimeFormat)
			DECLARE @pureSearchValue VARCHAR(50)

			SET @search = REPLACE(@search, '\', '')
			SET @pureSearchValue = REPLACE(@search, '%', '')

			IF(@formatedAdjustmentDateTime LIKE @search
				OR @formatedAdjustmentDateTime LIKE FORMAT(TRY_PARSE(@pureSearchValue AS DATETIME), @dateTimeFormat))
			BEGIN
				SET @result = 1
			END

		END

		RETURN @result
    END
GO


---------------------------------------------

-- fp.funcFindAdvancedPlanningTSQLPerformanceFlawsForMigration
CREATE FUNCTION [fp].[funcFindAdvancedPlanningTSQLPerformanceFlawsForMigration] (
	@MigrationName NVARCHAR(MAX)
)
RETURNS @Results TABLE (
		Name NVARCHAR(MAX),
		ObjectType NVARCHAR(MAX),
		Severity NVARCHAR(MAX),
		Category NVARCHAR(MAX),
		Description NVARCHAR(MAX)
	) 
AS
BEGIN
   
	DECLARE @Sql NVARCHAR(MAX) = (SELECT ForwardScript FROM [migration].[MigrationLog] WHERE Name = @MigrationName AND SourceFolder = 'AP')

	INSERT INTO @Results(Name, Severity, ObjectType, Category, Description)
	SELECT @MigrationName AS Name, CASE WHEN Severity = 3 THEN 'High'
		  WHEN Severity = 2 THEN 'Medium'
		  WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, 'Migration' AS ObjectType, Category, Description 
	FROM [fp].[funcFindTSQLPerformanceFlaws_AdvancedPlanning] (@Sql)
	
	RETURN;
END
GO


---------------------------------------------

-- fp.funcFindRequestVersion
CREATE   FUNCTION fp.funcFindRequestVersion(@date DATETIME)
RETURNS NVARCHAR(100)
AS
BEGIN
	RETURN (
		SELECT TOP 1 [Version]
		FROM [dbo].[UpgradeLog]
		WHERE @date >= [LogDateUtc]
		GROUP BY Version
		ORDER BY Min([LogDateUtc]) DESC
	)
END
GO


---------------------------------------------

-- fp.funcFindTSQLPerformanceFlaws_AdvancedPlanning
CREATE FUNCTION [fp].[funcFindTSQLPerformanceFlaws_AdvancedPlanning] (
	@sql NVARCHAR(MAX)
)
RETURNS @Results TABLE (
		Severity SMALLINT,
		Category NVARCHAR(MAX),
		Description NVARCHAR(MAX)
	) 
AS
BEGIN
   
	-- Rule 1 do not join on source dimensionality
	IF (@sql LIKE '%INNER JOIN @SourceDimensionality%' OR
		@sql LIKE '%INNER JOIN [fp].[funcGetSourceDimensionalityAsTable]%')
	BEGIN
		INSERT INTO @Results (Category, Description, Severity) VALUES ('Join on Targeting', 'Do not join on targeting obj, create a temporary table and join on that instead', 3)		
	END		
	
	-- Rule 2 do not join with Department IS NULL
	-- NOTE: This may have some false positives for real DepartmentID is null checks, but that shouldn't be many
	IF (@sql LIKE '%DepartmentID IS NULL%')
	BEGIN
		INSERT INTO @Results (Category, Description, Severity) VALUES ('NULL Check on Department Targeting', 'Do not check for null within the join, seperate this out into 2 blocks', 3)		
	END		
	
	RETURN;
END
GO


---------------------------------------------

-- fp.funcFormatColumnByMonth
CREATE   FUNCTION fp.funcFormatColumnByMonth (
	@expression NVARCHAR(1000),
	@month INT
)
RETURNS VARCHAR(2000) AS
BEGIN
    -- if the month is less than 10, we need to add a 0 to the front of it.
	RETURN @expression + CASE WHEN @month < 10 THEN '0' ELSE '' END + CAST(@month AS VARCHAR(2))
END;
GO


---------------------------------------------

-- fp.funcGetChargeRate
CREATE FUNCTION [fp].[funcGetChargeRate] (@SelectedSortOrder INT, @BudgetConfigID INT)
RETURNS VARCHAR(250)
AS BEGIN
    
	DECLARE @ChargeMasterConfigJson NVARCHAR(MAX) = (SELECT ISNULL(ChargeMasterConfigJson, '') FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID)
	DECLARE @ChargeRateConfiguration TABLE (Name NVARCHAR(MAX), RateMonthID INT, FiscalMonthID INT) 

	IF (@ChargeMasterConfigJson IS NOT NULL)
	BEGIN

		-- Parse out the ChargeMasterJSON to a SQL readable format
		INSERT INTO @ChargeRateConfiguration
		SELECT REPLACE(NAME, 'EffectiveFiscalMonthID', '') as Name, REPLACE(REPLACE(NAME, 'EffectiveFiscalMonthID', ''), 'ChargeRate', '') AS RateMonthID, StringValue As FiscalMonthID
		FROM dbo.parseJSON(@ChargeMasterConfigJson)
		WHERE Name LIKE 'ChargeRate%'

		DECLARE @SortOrder INT, @FiscalMonthID INT, @CurrentRate INT = 1, @NextMonthEffective INT = 0;
		DECLARE db_cursor CURSOR FOR SELECT SortOrder, FiscalMonthID FROM [fw].[DimFiscalMonth] WHERE FiscalMonthID != 0 ORDER BY SortOrder

		OPEN db_cursor  
		FETCH NEXT FROM db_cursor INTO @SortOrder, @FiscalMonthID

		WHILE @@FETCH_STATUS = 0  
		BEGIN  
		      
			  SET @NextMonthEffective = (SELECT FiscalMonthID FROM @ChargeRateConfiguration WHERE RateMonthID = @CurrentRate + 1);
			  
			  -- Need to check if the next month is 0, if it is all the rest of the months are going to be the current rate
			  -- If it is not 0, but not equal to the current fiscal month we can assume it's still the current rate.
			  IF (@NextMonthEffective = 0 OR @FiscalMonthID != @NextMonthEffective)
			  BEGIN
			  
			  	-- We found the one we want, skip the rest and return
			  	IF (@SelectedSortOrder = @SortOrder)
					RETURN (SELECT Name FROM @ChargeRateConfiguration WHERE RateMonthID = @CurrentRate)
					
			  -- Check if the current fiscal month matches the next effective FMID, if it does, that's now the current rate.
			  END ELSE IF (@FiscalMonthID = @NextMonthEffective) BEGIN 
			  	SET @CurrentRate = @CurrentRate + 1;
				
				-- We found the one we want, skip the rest and return
				IF (@SelectedSortOrder = @SortOrder)
			  		RETURN (SELECT Name FROM @ChargeRateConfiguration WHERE RateMonthID = @CurrentRate)	
			  END

		      FETCH NEXT FROM db_cursor INTO @SortOrder, @FiscalMonthID 
		END 

		CLOSE db_cursor  
		DEALLOCATE db_cursor 
		
	END
	
	-- Default
	RETURN (SELECT TOP (1) Name FROM @ChargeRateConfiguration WHERE FiscalMonthID != 0 ORDER BY RateMonthID DESC)
	
END
GO


---------------------------------------------

-- fp.funcGetClassificationsUsedOnAdjustments
CREATE   FUNCTION [fp].[funcGetClassificationsUsedOnAdjustments] 
	(@budgetConfigGuid UNIQUEIDENTIFIER)
RETURNS @return_variable TABLE (ClassificationCategoryID INT, ClassificationGroupID INT)
as 
BEGIN
	
	INSERT INTO @return_variable
	SELECT	ClassificationCategoryID, 
			ClassificationGroupID
	FROM
	(

		SELECT	ClassificationCategoryID, 
				ClassificationGroupID
		FROM	fp.ServiceLineEncounterAdjustment
		WHERE	BudgetConfigGUID = @budgetConfigGuid
				AND ClassificationGroupID <> 0
				AND (GroupingGUID = '00000000-0000-0000-0000-000000000000'
					OR AdjustmentType <> 0)
				
		UNION ALL

		SELECT	ClassificationCategoryID, 
				ClassificationGroupID
		FROM	fp.DepartmentChargeVolumeAdjustment
		WHERE	BudgetConfigGUID = @budgetConfigGuid
				AND ClassificationGroupID <> 0
				AND (GroupingGUID = '00000000-0000-0000-0000-000000000000'
					OR AdjustmentType <> 0)

		UNION ALL

		SELECT	ClassificationCategoryID, 
				ClassificationGroupID
		FROM	fp.StatisticsAdjustment
		WHERE	BudgetConfigGUID = @budgetConfigGuid
				AND ClassificationGroupID <> 0
				AND (GroupingGUID = '00000000-0000-0000-0000-000000000000'
					OR AdjustmentType <> 0)
		
		UNION ALL

		SELECT	ClassificationCategoryID, 
				ClassificationGroupID
		FROM	fp.StaffingAdjustment
		WHERE	BudgetConfigGUID = @budgetConfigGuid
				AND ClassificationGroupID <> 0
				AND (GroupingGUID = '00000000-0000-0000-0000-000000000000'
					OR AdjustmentType <> 0)

		UNION ALL

		SELECT	ClassificationCategoryID, 
				ClassificationGroupID
		FROM	fp.BenefitsAdjustment
		WHERE	BudgetConfigGUID = @budgetConfigGuid
				AND ClassificationGroupID <> 0
				AND (GroupingGUID = '00000000-0000-0000-0000-000000000000'
					OR AdjustmentType <> 0)

		UNION ALL

		SELECT	ClassificationCategoryID, 
				ClassificationGroupID
		FROM	fp.GeneralLedgerAdjustment
		WHERE	BudgetConfigGUID = @budgetConfigGuid
				AND ClassificationGroupID <> 0
				AND (GroupingGUID = '00000000-0000-0000-0000-000000000000'
					OR AdjustmentType <> 0)

		UNION ALL

		-- Add Provider Adjustment's classification info (AdjustmentType = 15) is stored here
		SELECT	aps.ClassificationCategoryID, 
				aps.ClassificationGroupID
		FROM	fp.AddProviderSummary AS aps
				JOIN fp.ServiceLineEncounterAdjustment AS slea ON slea.AdjustmentGUID = aps.SLEncounterAdjustmentGUID
		WHERE	slea.BudgetConfigGUID = @budgetConfigGuid
				AND aps.ClassificationGroupID <> 0

		UNION ALL

		SELECT  saps.ClassificationCategoryID, 
                saps.ClassificationGroupID
        FROM    fp.StatisticAddProviderSummary AS saps
                JOIN fp.StatisticsAdjustment AS sa ON sa.AdjustmentGUID = saps.DriverAdjustmentGUID
        WHERE   sa.BudgetConfigGUID = @budgetConfigGuid
                AND saps.ClassificationGroupID <> 0
	) res
	GROUP BY ClassificationCategoryID, 
			ClassificationGroupID

	RETURN
END
GO


---------------------------------------------

-- fp.funcGetDifferencesBetweenConfigs_GeneralLedger
CREATE FUNCTION fp.funcGetDifferencesBetweenConfigs_GeneralLedger (
	@BudgetConfigBase INT,
	@BudgetConfigComparer INT
)
RETURNS TABLE AS
RETURN SELECT 
			base.[GeneralLedgerID], 
			base.[BudgetConfigID], 
			base.[EntityGroupConfigID], 
			base.[EntityID], 
			e.Name AS Entity,
			base.[DepartmentID], 
			d.Name AS Department,
			base.[AccountID], 
			a.Name AS Account,
			base.[FinancialReportingID], 
			fr.Name AS FinancialReporting, 
			base.[APEModelSectionID],
			map.APEModelSectionName AS ModelSection,
			base.[VariabilityID], 
			v.Name AS Variability,
			base.[UnitTypeID], 
			ut.Name AS UnitType,
			base.[TimeClassID], 
			base.[FiscalYearID], 
			base.[FiscalMonthID],  
			base.[LockType] AS SnapshotLockType,
			comparer.OriginalValue AS SnapshotInitial,
			comparer.Value AS SnapshotTarget,
			comparer.ManagerValue AS SnapshotBudget,
			comparer.[LockType] AS CurrentLockType,
			base.OriginalValue AS CurrentInitial,
			base.Value AS CurrentTarget,
			base.ManagerValue AS CurrentBudget,
			comparer.OriginalValue - base.OriginalValue As DifferenceInitial,
			comparer.Value - base.Value As DifferenceTarget,
			comparer.ManagerValue - base.ManagerValue As DifferenceBudget
		FROM [fp].[viewFactGeneralLedger_Unpivoted_source] base
			INNER JOIN [fp].[viewFactGeneralLedger_Unpivoted_source] comparer ON 
					base.DepartmentID = comparer.DepartmentID
				AND base.EntityID = comparer.EntityID
				AND base.AccountID = comparer.AccountID
				AND base.FinancialReportingID = comparer.FinancialReportingID
				AND base.VariabilityID = comparer.VariabilityID
				AND base.FiscalMonthID = comparer.FiscalMonthID
				AND base.TimeClassID = comparer.TimeClassID	
				AND base.UnitTypeID = comparer.UnitTypeID
			INNER JOIN [fw].[DimEntity] e ON base.EntityID = e.EntityID
			INNER JOIN [fw].[DimDepartment] d ON base.DepartmentID = d.DepartmentID
			INNER JOIN [fw].[DimAccount] a ON base.AccountID = a.AccountID
			INNER JOIN [ob].[DimFinancialReporting] fr ON base.FinancialReportingID = fr.FinancialReportingID
			INNER JOIN [fw].[DimVariability] v ON base.VariabilityID = v.VariabilityID
			INNER JOIN [fw].[DimUnitType] ut ON base.UnitTypeID = ut.UnitTypeID
			INNER JOIN [fp].[ModelSectionMap] map ON base.APEModelSectionID = map.APEModelSectionID
		WHERE base.BudgetConfigID = @BudgetConfigBase
			AND comparer.BudgetConfigID = @BudgetConfigComparer
GO


---------------------------------------------

-- fp.funcGetDifferencesBetweenConfigs_Staffing
CREATE FUNCTION fp.funcGetDifferencesBetweenConfigs_Staffing (
	@BudgetConfigBase INT,
	@BudgetConfigComparer INT
)
RETURNS TABLE AS
RETURN SELECT 
			base.[BudgetConfigID], 
			base.[EntityID], 
			e.Name AS Entity,
			base.[DepartmentID],
			d.Name AS Department,
			base.[JobCodeID], 
			jc.Name AS JobCode,
			base.[ProductiveClassID], 
			pc.Name AS ProductiveClass,
			base.[PayCodeGroupID], 
			p.PayCodeGroupID AS PayCodeGroup,
			base.[VariabilityID], 
			v.Name AS Variability,
			base.[UnitTypeID], 
			ut.Name AS UnitType,
			base.[TimeClassID], 
			base.[FiscalMonthID], 
			base.[FiscalYearID],
			comparer.OriginalValue AS SnapshotInitial,
			comparer.Value AS SnapshotTarget,
			comparer.ManagerValue AS SnapshotBudget,
			base.OriginalValue AS CurrentInitial,
			base.Value AS CurrentTarget,
			base.ManagerValue AS CurrentBudget,
			comparer.OriginalValue - base.OriginalValue As DifferenceInitial,
			comparer.Value - base.Value As DifferenceTarget,
			comparer.ManagerValue - base.ManagerValue As DifferenceBudget
		FROM [fp].[viewFactStaffing_Unpivoted_source] base
			INNER JOIN [fp].[viewFactStaffing_Unpivoted_source] comparer ON 
					base.DepartmentID = comparer.DepartmentID
				AND base.EntityID = comparer.EntityID
				AND base.JobCodeID = comparer.JobCodeID
				AND base.ProductiveClassID = comparer.ProductiveClassID
				AND base.PayCodeGroupID = comparer.PayCodeGroupID
				AND base.VariabilityID = comparer.VariabilityID
				AND base.FiscalMonthID = comparer.FiscalMonthID
				AND base.TimeClassID = comparer.TimeClassID	
				AND base.UnitTypeID = comparer.UnitTypeID
			INNER JOIN [fw].[DimEntity] e ON base.EntityID = e.EntityID
			INNER JOIN [fw].[DimDepartment] d ON base.DepartmentID = d.DepartmentID
			INNER JOIN [fw].[DimJobCode] jc ON base.JobCodeID = jc.JobCodeID
			INNER JOIN [fw].[DimProductiveClass] pc ON base.ProductiveClassID = pc.ProductiveClassID
			INNER JOIN [fw].[DimPayCodeGroup] p ON base.PayCodeGroupID = p.PayCodeGroupID
			INNER JOIN [fw].[DimVariability] v ON base.VariabilityID = v.VariabilityID
			INNER JOIN [fw].[DimUnitType] ut ON base.UnitTypeID = ut.UnitTypeID
		WHERE base.BudgetConfigID = @BudgetConfigBase
			AND comparer.BudgetConfigID = @BudgetConfigComparer
GO


---------------------------------------------

-- fp.funcGetHistoryViewerGLFilter
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	2016-12-13	IP			B-20335		Created SP for Admin Plan - Details feature expansion - Backend
** 2	2018-08-29	IP						fixed afetr clarification
*************************************************************/
CREATE FUNCTION fp.funcGetHistoryViewerGLFilter (@StringToParse VARCHAR(max), @Prefix VARCHAR(50) = NULL)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @ReturnLine VARCHAR(max) = ''

	SELECT @ReturnLine = @ReturnLine + ' AND ' + ISNULL(@Prefix+'.','')+ Component
	FROM dbo.split(replace(@StringToParse, ' and ', '&'), '&') AS split
	WHERE Component NOT LIKE '%FiscalMonthID%' and Component NOT LIKE '%UnitType%'

	RETURN @ReturnLine
END
GO


---------------------------------------------

-- fp.funcGetHistoryViewerMonthFilter
/*************************************************************
** Change History
**************************************************************
** CID	Date        Author    	WI			Description
** 1	2018-09-05	GF			B-20335		Created
*************************************************************/
CREATE FUNCTION fp.funcGetHistoryViewerMonthFilter (@FilterColumns VARCHAR(max))
RETURNS INT
AS
BEGIN
	declare @FilteredMonth int = 0
	SET @FilteredMonth = 
		(
		SELECT 
			MAX(ValueList)
		FROM (
			SELECT 
				LTRIM(RTRIM(SUBSTRING(Component, CHARINDEX('=', Component, 1) + 1, 1000))) AS ValueList
			FROM dbo.split(replace(@FilterColumns, ' and ', '&'), '&') AS split
			WHERE Component LIKE '%FiscalMonthID%'
	
		UNION ALL
	
			SELECT 0 AS ValueList -- if Month is NOT present in filter
			)X
		)

	RETURN @FilteredMonth
END
GO


---------------------------------------------

-- fp.funcGetMissingNonStaffingFlexConfigMappings
CREATE FUNCTION fp.funcGetMissingNonStaffingFlexConfigMappings (@EntityGroupConfigGUID UNIQUEIDENTIFIER, @DepartmentID INT, @AccountIDs SqlInt32ListTableType READONLY) 
 RETURNS @Result TABLE (
	DepartmentID INT, 
	GLAccountID INT, 
	StatAccountID INT )
 AS
 BEGIN
 	DECLARE @BudgetConfigID INT;
	SET @BudgetConfigID = (SELECT BudgetConfigID 
						   FROM [fp].[EntityGroupConfig] ec
						    	INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = ec.BudgetConfigGUID
						   WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
 
 	DECLARE @EntityGroupConfigID INT;
	SET @EntityGroupConfigID = (SELECT EntityGroupConfigID 
						   FROM [fp].[EntityGroupConfig]
						   WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID)
 
	INSERT INTO @Result(DepartmentID, GLAccountID, StatAccountID)
	SELECT DISTINCT stat.DepartmentID, ns.AccountID AS GLAccountID, nso.AccountID AS StatAccountID
	FROM [fp].[FactStatistics] stat
	    INNER JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] ns ON ns.DepartmentID = stat.DepartmentID
	    INNER JOIN [fp].[NSOverrideFlexConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID
	    INNER JOIN [fw].[DimAccount] a ON ns.AccountID = a.AccountID
	    INNER JOIN [ob].[DimAccountPH] aph ON a.OBAccountPHID = aph.AccountPHID
	WHERE aph.Name = 'Expenses - Non-Staffing'
	    AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND stat.BudgetConfigID = @BudgetConfigID
	    AND ns.FlexMethodID = 1
		AND stat.DepartmentID = @DepartmentID
		AND ns.AccountID IN ( Select value FROM @AccountIDs )
			
	INSERT INTO @Result(DepartmentID, GLAccountID, StatAccountID)
	SELECT DISTINCT stat.DepartmentID, acc.AccountID AS GLAccountID, stat.AccountID AS StatAccountID
	FROM [fp].[FactStatistics] stat
	    INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID
	    INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID
	    INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] ns ON ns.DepartmentID = stat.DepartmentID
		CROSS JOIN (SELECT AccountID FROM [fw].[DimAccount] WHERE OBModelSectionName LIKE '%Expenses - Non-Staffing%' AND AccountID IN ( Select value FROM @AccountIDs )) acc
		LEFT JOIN (SELECT DepartmentID, AccountID FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr
			ON ovr.DepartmentID = stat.DepartmentID
			AND ovr.AccountID = acc.AccountID
	WHERE stat.DepartmentID = @DepartmentID
		AND fsc.IsNonStaffing = 1
	    AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID
	    AND stat.BudgetConfigID = @BudgetConfigID
	    AND ns.FlexMethodID = 1
	    AND ovr.DepartmentID IS NULL;
	
	DELETE res
	FROM @Result res
		INNER JOIN [fp].[FlexConfigMapping] flex ON
			res.DepartmentID = flex.DepartmentID
			AND res.GLAccountID = flex.GLAccountID
			AND res.StatAccountID = flex.StatAccountID
	WHERE flex.FlexingTypeID = 1 -- NonStaffing
		AND flex.DepartmentID = @DepartmentID
		AND flex.EntityGroupConfigID = @EntityGroupConfigID
	
	RETURN
 END
GO


---------------------------------------------

-- fp.funcGetSourceDimensionalityAsTable
CREATE FUNCTION fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY)
RETURNS @return_variable TABLE (DepartmentId int, EntityId int, BudgetPhaseId int)
as 
BEGIN
	INSERT INTO @return_variable (DepartmentID, BudgetPhaseID)
	SELECT DepartmentID, BudgetPhaseID
	FROM @SourceDimensionality

	UNION

	SELECT d.DepartmentID, sd.BudgetPhaseID
	FROM fw.DimDepartment d
	INNER JOIN @SourceDimensionality sd 
		ON sd.EntityID = d.EntityID
	WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID 

	IF (select count(*) from @return_variable) = 0
	INSERT INTO @return_variable (DepartmentID) VALUES (NULL)
	RETURN
END
GO


---------------------------------------------

-- fp.funcJSONUpdate_DeleteMeasureByName
CREATE FUNCTION fp.funcJSONUpdate_DeleteMeasureByName( 
		@configJSON NVARCHAR(MAX),
		@measureNameToDelete NVARCHAR(MAX)
		)
RETURNS NVARCHAR(MAX)

BEGIN
	-- some variables that we would need
	DECLARE
		@oldMeasuresString NVARCHAR(MAX), 
		@key INT,
		@newMeasure NVARCHAR(MAX)
		

	DECLARE update_measures_cursor CURSOR FOR
	SELECT tl.[value], tl.[key]
	FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures') AS tl


	OPEN update_measures_cursor
	
	FETCH NEXT FROM update_measures_cursor INTO @oldMeasuresString, @key

	WHILE(@@FETCH_STATUS = 0)
	BEGIN

	DECLARE @filteredMeasures NVARCHAR(MAX) = NULL
		SELECT @filteredMeasures = CONCAT_WS(',', JSON_QUERY(@filteredMeasures), [value])
		FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + '].measures')
			CROSS APPLY OPENJSON([value])
				WITH(name NVARCHAR(100) '$.name')
				WHERE name <> @measureNameToDelete
		
		SET @newMeasure = JSON_MODIFY(@oldMeasuresString, '$.measures', JSON_QUERY('['+ @filteredMeasures + ']'))
		SET @configJSON = JSON_MODIFY(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + ']', JSON_QUERY(@newMeasure))

		FETCH NEXT FROM update_measures_cursor into @oldMeasuresString, @key
	END

	CLOSE update_measures_cursor
	DEALLOCATE update_measures_cursor

	RETURN @configJSON

END
GO


---------------------------------------------

-- fp.funcJSONUpdate_InsertNewMeasure
CREATE FUNCTION fp.funcJSONUpdate_InsertNewMeasure (
	@configJSON NVARCHAR(MAX),
	@newMeasureObject NVARCHAR(MAX)
) 
RETURNS NVARCHAR(MAX)

BEGIN

	DECLARE
		@oldMeasuresString NVARCHAR(MAX), 
		@key INT,
		@newMeasure NVARCHAR(MAX),
		@measureId INT
		

	DECLARE update_measures_cursor CURSOR FOR
	SELECT tl.[value], tl.[key]
	FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures') AS tl


	OPEN update_measures_cursor
	
	FETCH NEXT FROM update_measures_cursor INTO @oldMeasuresString, @key

	WHILE(@@FETCH_STATUS = 0)
	BEGIN
		SELECT @measureId=MAX(tl.[id])
		FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + '].measures') 
		WITH(
				id int '$.id') AS tl

		SET @newMeasure= JSON_MODIFY(@oldMeasuresString, ' append $.measures', JSON_QUERY(JSON_MODIFY(@newMeasureObject, '$.id', @measureId+1)))
		SET @configJSON = JSON_MODIFY(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + ']', JSON_QUERY(@newMeasure))
		FETCH NEXT FROM update_measures_cursor into @oldMeasuresString, @key
	END

	CLOSE update_measures_cursor
	DEALLOCATE update_measures_cursor

	RETURN @configJSON

END
GO


---------------------------------------------

-- fp.viewDepartmentManagerNonStaffingUosQuery
/**************************************************************
** Change History
**************************************************************
** CID  Date       Author  WI				Description
** 1	3-30-2023  NT      JAZZ-49042		Apply cross departmnet flexing change
*************************************************************/
CREATE FUNCTION fp.viewDepartmentManagerNonStaffingUosQuery (@BudgetConfigID INT, @DepartmentID INT) 
 RETURNS @Result TABLE (
	BudgetConfigID INT, 
	EntityID INT, 
	DepartmentID INT, 
	AccountID INT, 
	BudgetPhaseID TINYINT,
	AdjustedValue01 DECIMAL(19, 8), AdjustedValue02 DECIMAL(19, 8), AdjustedValue03 DECIMAL(19, 8), AdjustedValue04 DECIMAL(19, 8), AdjustedValue05 DECIMAL(19, 8), AdjustedValue06 DECIMAL(19, 8), AdjustedValue07 DECIMAL(19, 8), AdjustedValue08 DECIMAL(19, 8), AdjustedValue09 DECIMAL(19, 8), AdjustedValue10 DECIMAL(19, 8), AdjustedValue11 DECIMAL(19, 8), AdjustedValue12 DECIMAL(19, 8), AdjustedValueTotal DECIMAL(19, 8),
	AdjustedProjectionValue01 DECIMAL(19, 8), AdjustedProjectionValue02 DECIMAL(19, 8), AdjustedProjectionValue03 DECIMAL(19, 8), AdjustedProjectionValue04 DECIMAL(19, 8), AdjustedProjectionValue05 DECIMAL(19, 8), AdjustedProjectionValue06 DECIMAL(19, 8), AdjustedProjectionValue07 DECIMAL(19, 8), AdjustedProjectionValue08 DECIMAL(19, 8), AdjustedProjectionValue09 DECIMAL(19, 8), AdjustedProjectionValue10 DECIMAL(19, 8), AdjustedProjectionValue11 DECIMAL(19, 8), AdjustedProjectionValue12 DECIMAL(19, 8), AdjustedProjectionValueTotal DECIMAL(19, 8))
 AS
 BEGIN
	
INSERT INTO @Result (BudgetConfigID, EntityID, DepartmentID, AccountID, BudgetPhaseID,
	AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12, AdjustedValueTotal,
	AdjustedProjectionValue01, AdjustedProjectionValue02, AdjustedProjectionValue03, AdjustedProjectionValue04, AdjustedProjectionValue05, AdjustedProjectionValue06, AdjustedProjectionValue07, AdjustedProjectionValue08, AdjustedProjectionValue09, AdjustedProjectionValue10, AdjustedProjectionValue11, AdjustedProjectionValue12, AdjustedProjectionValueTotal) 
	SELECT 
		sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, fc.AccountID, dept.BudgetPhaseID,
		ISNULL(SUM(sb.AdjustedValue01), 0) AS AdjustedValue01, ISNULL(SUM(sb.AdjustedValue02), 0) AS AdjustedValue02, ISNULL(SUM(sb.AdjustedValue03), 0) AS AdjustedValue03, ISNULL(SUM(sb.AdjustedValue04), 0) AS AdjustedValue04, ISNULL(SUM(sb.AdjustedValue05), 0) AS AdjustedValue05, ISNULL(SUM(sb.AdjustedValue06), 0) AS AdjustedValue06, ISNULL(SUM(sb.AdjustedValue07), 0) AS AdjustedValue07, ISNULL(SUM(sb.AdjustedValue08), 0) AS AdjustedValue08, ISNULL(SUM(sb.AdjustedValue09), 0) AS AdjustedValue09, ISNULL(SUM(sb.AdjustedValue10), 0) AS AdjustedValue10, ISNULL(SUM(sb.AdjustedValue11), 0) AS AdjustedValue11, ISNULL(SUM(sb.AdjustedValue12), 0) AS AdjustedValue12, ISNULL(SUM(sb.AdjustedValueTotal), 0) AS AdjustedValueTotal, 
		ISNULL(SUM(sb.AdjustedProjectionValue01), 0) AS AdjustedProjectionValue01, ISNULL(SUM(sb.AdjustedProjectionValue02), 0) AS AdjustedProjectionValue02, ISNULL(SUM(sb.AdjustedProjectionValue03), 0) AS AdjustedProjectionValue03, ISNULL(SUM(sb.AdjustedProjectionValue04), 0) AS AdjustedProjectionValue04, ISNULL(SUM(sb.AdjustedProjectionValue05), 0) AS AdjustedProjectionValue05, ISNULL(SUM(sb.AdjustedProjectionValue06), 0) AS AdjustedProjectionValue06, ISNULL(SUM(sb.AdjustedProjectionValue07), 0) AS AdjustedProjectionValue07, ISNULL(SUM(sb.AdjustedProjectionValue08), 0) AS AdjustedProjectionValue08, ISNULL(SUM(sb.AdjustedProjectionValue09), 0) AS AdjustedProjectionValue09, ISNULL(SUM(sb.AdjustedProjectionValue10), 0) AS AdjustedProjectionValue10, ISNULL(SUM(sb.AdjustedProjectionValue11), 0) AS AdjustedProjectionValue11, ISNULL(SUM(sb.AdjustedProjectionValue12), 0) AS AdjustedProjectionValue12, ISNULL(SUM(sb.AdjustedProjectionValueTotal), 0) AS AdjustedProjectionValueTotal
	FROM fp.viewFactStatistics sb
	  INNER JOIN fp.viewFactStatistics dept on sb.StatisticsID = dept.StatisticsID
		INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN (SELECT primStats.DepartmentID, primStats.AccountID, COALESCE(src.DepartmentID, primStats.DepartmentID) AS SourceDepartmentID 
					FROM [fp].[PrimaryStatisticsConfig] primStats
					LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] src
					 ON primStats.RowID = src.PrimaryStatisticsConfigID
					WHERE primStats.IsNonStaffing = 1
					) psc 
		  ON psc.SourceDepartmentID = sb.DepartmentID 
		 AND psc.AccountID = sb.AccountID
		INNER JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] fc ON fc.DepartmentID = psc.DepartmentID AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		INNER JOIN [fp].[NSOverrideFlexConfigAssignment] assign ON fc.OverrideFlexConfigGUID = assign.OverrideFlexConfigGUID AND sb.AccountID = assign.AccountID
	WHERE psc.DepartmentID = @DepartmentID
		AND sb.BudgetConfigID = @BudgetConfigID
		AND fc.FlexMethodID = 1
		AND dept.BudgetPhaseID = 3
		AND sb.BudgetPhaseID = 2
	GROUP BY sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, fc.AccountID, dept.BudgetPhaseID


	;WITH groupedStats AS(
		SELECT 
			sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, dept.BudgetPhaseID,
			ISNULL(SUM(sb.AdjustedValue01), 0) AS AdjustedValue01, ISNULL(SUM(sb.AdjustedValue02), 0) AS AdjustedValue02, ISNULL(SUM(sb.AdjustedValue03), 0) AS AdjustedValue03, ISNULL(SUM(sb.AdjustedValue04), 0) AS AdjustedValue04, ISNULL(SUM(sb.AdjustedValue05), 0) AS AdjustedValue05, ISNULL(SUM(sb.AdjustedValue06), 0) AS AdjustedValue06, ISNULL(SUM(sb.AdjustedValue07), 0) AS AdjustedValue07, ISNULL(SUM(sb.AdjustedValue08), 0) AS AdjustedValue08, ISNULL(SUM(sb.AdjustedValue09), 0) AS AdjustedValue09, ISNULL(SUM(sb.AdjustedValue10), 0) AS AdjustedValue10, ISNULL(SUM(sb.AdjustedValue11), 0) AS AdjustedValue11, ISNULL(SUM(sb.AdjustedValue12), 0) AS AdjustedValue12, ISNULL(SUM(sb.AdjustedValueTotal), 0) AS AdjustedValueTotal, 
			ISNULL(SUM(sb.AdjustedProjectionValue01), 0) AS AdjustedProjectionValue01, ISNULL(SUM(sb.AdjustedProjectionValue02), 0) AS AdjustedProjectionValue02, ISNULL(SUM(sb.AdjustedProjectionValue03), 0) AS AdjustedProjectionValue03, ISNULL(SUM(sb.AdjustedProjectionValue04), 0) AS AdjustedProjectionValue04, ISNULL(SUM(sb.AdjustedProjectionValue05), 0) AS AdjustedProjectionValue05, ISNULL(SUM(sb.AdjustedProjectionValue06), 0) AS AdjustedProjectionValue06, ISNULL(SUM(sb.AdjustedProjectionValue07), 0) AS AdjustedProjectionValue07, ISNULL(SUM(sb.AdjustedProjectionValue08), 0) AS AdjustedProjectionValue08, ISNULL(SUM(sb.AdjustedProjectionValue09), 0) AS AdjustedProjectionValue09, ISNULL(SUM(sb.AdjustedProjectionValue10), 0) AS AdjustedProjectionValue10, ISNULL(SUM(sb.AdjustedProjectionValue11), 0) AS AdjustedProjectionValue11, ISNULL(SUM(sb.AdjustedProjectionValue12), 0) AS AdjustedProjectionValue12, ISNULL(SUM(sb.AdjustedProjectionValueTotal), 0) AS AdjustedProjectionValueTotal
		FROM fp.viewFactStatistics sb
	  INNER JOIN fp.viewFactStatistics dept on sb.StatisticsID = dept.StatisticsID		
		INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID
		INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID
		INNER JOIN (SELECT primStats.EntityGroupConfigGUID, primStats.DepartmentID, primStats.AccountID, COALESCE(src.DepartmentID, primStats.DepartmentID) AS SourceDepartmentID 
				FROM [fp].[PrimaryStatisticsConfig] primStats
				LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] src
					ON primStats.RowID = src.PrimaryStatisticsConfigID
				WHERE primStats.IsNonStaffing = 1
				) psc 
		  ON psc.SourceDepartmentID = sb.DepartmentID 
		 AND psc.AccountID = sb.AccountID
		 AND psc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] fc ON fc.DepartmentID = psc.DepartmentID AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID
		WHERE psc.DepartmentID = @DepartmentID
			AND sb.BudgetConfigID = @BudgetConfigID
			AND fc.FlexMethodID = 1
			AND dept.BudgetPhaseID = 3
			AND sb.BudgetPhaseID = 2
		GROUP BY sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, dept.BudgetPhaseID
	) 
	
	INSERT INTO @Result (BudgetConfigID, EntityID, DepartmentID, AccountID, BudgetPhaseID,
		AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12, AdjustedValueTotal,
		AdjustedProjectionValue01, AdjustedProjectionValue02, AdjustedProjectionValue03, AdjustedProjectionValue04, AdjustedProjectionValue05, AdjustedProjectionValue06, AdjustedProjectionValue07, AdjustedProjectionValue08, AdjustedProjectionValue09, AdjustedProjectionValue10, AdjustedProjectionValue11, AdjustedProjectionValue12, AdjustedProjectionValueTotal)
	SELECT 
		sb.BudgetConfigID, sb.EntityID, sb.DepartmentID, acc.AccountID, sb.BudgetPhaseID,
		sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12, sb.AdjustedValueTotal,
		sb.AdjustedProjectionValue01, sb.AdjustedProjectionValue02, sb.AdjustedProjectionValue03, sb.AdjustedProjectionValue04, sb.AdjustedProjectionValue05, sb.AdjustedProjectionValue06, sb.AdjustedProjectionValue07, sb.AdjustedProjectionValue08, sb.AdjustedProjectionValue09, sb.AdjustedProjectionValue10, sb.AdjustedProjectionValue11, sb.AdjustedProjectionValue12, sb.AdjustedProjectionValueTotal
	FROM groupedStats sb
	CROSS JOIN (SELECT AccountID FROM [fw].[DimAccount] WHERE OBModelSectionName LIKE '%Expenses - Non-Staffing%') acc
		LEFT JOIN @Result uos ON uos.DepartmentID = sb.DepartmentID  AND uos.BudgetConfigID = sb.BudgetConfigID
	WHERE uos.BudgetConfigID IS NULL
	
	RETURN
 END
GO


---------------------------------------------

-- fp.viewGetStatsByGeneralLedgerIDForFlexing
CREATE   FUNCTION [fp].[viewGetStatsByGeneralLedgerIDForFlexing] (
	@EntityGroupConfigID INT,
	@BudgetConfigID INT,
	@FlexingTypeID INT,
	@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY
)
RETURNS TABLE AS
RETURN (

	/**************************************************************
	** Change History
	**************************************************************
	** CID  Date        Author  WI				Description
	** 1	02-28-2023  MY      JAZZ-48980		Inital
	** 2	08-25-2023  MY      JAZZ-59500		Updated view to restructure
	*************************************************************/

	-- Note, this was done so we didn't have to recreate the same logic in 3 different places

	WITH departmentFromTargeting AS (
		SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality)
	), departments AS (
		SELECT DepartmentID FROM departmentFromTargeting WHERE EXISTS (SELECT 1 FROM departmentFromTargeting WHERE DepartmentID IS NOT NULL) -- Targeted
		UNION ALL
		SELECT DISTINCT DepartmentID 
		FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED)
		WHERE EntityGroupConfigID  = @EntityGroupConfigID
			AND FlexingTypeID = @FlexingTypeID
			AND NOT EXISTS (SELECT 1 FROM departmentFromTargeting WHERE DepartmentID IS NOT NULL) -- Untargeted
	), glRecords AS (
		SELECT base.EntityGroupConfigID, base.GeneralLedgerID, base.DepartmentID, base.AccountID
		FROM [fp].[GeneralLedger] base
			INNER JOIN departments dept ON base.DepartmentID = dept.DepartmentID
		WHERE base.EntityGroupConfigID = @EntityGroupConfigID
			AND base.FlexingTypeID = @FlexingTypeID
			AND base.VariabilityID = 2
	), itemsToFlex AS (
		SELECT DISTINCT fsc.FlexingTypeID, fsc.DepartmentID, fsc.GLAccountID, fsc.StatAccountID, fsc.SourceDepartmentID
		FROM [fp].[FlexConfigMapping] fsc
			INNER JOIN glRecords fs ON fsc.DepartmentID = fs.DepartmentID AND fsc.GLAccountID = fs.AccountID
		WHERE fsc.FlexingTypeID = @FlexingTypeID
			AND fsc.EntityGroupConfigID = @EntityGroupConfigID
	), stats AS (
		-- Get the stats for each Source Department / Account combination
		SELECT 
			fs.DepartmentID AS SourceDepartmentID, 
			fs.AccountID, 
			SUM(tgt.AdjustedValue01) AS TargetAdjustedValue01,
			SUM(tgt.AdjustedValue02) AS TargetAdjustedValue02,
			SUM(tgt.AdjustedValue03) AS TargetAdjustedValue03,
			SUM(tgt.AdjustedValue04) AS TargetAdjustedValue04,
			SUM(tgt.AdjustedValue05) AS TargetAdjustedValue05,
			SUM(tgt.AdjustedValue06) AS TargetAdjustedValue06,
			SUM(tgt.AdjustedValue07) AS TargetAdjustedValue07,
			SUM(tgt.AdjustedValue08) AS TargetAdjustedValue08,
			SUM(tgt.AdjustedValue09) AS TargetAdjustedValue09,
			SUM(tgt.AdjustedValue10) AS TargetAdjustedValue10,
			SUM(tgt.AdjustedValue11) AS TargetAdjustedValue11,
			SUM(tgt.AdjustedValue12) AS TargetAdjustedValue12,
		                        
			SUM(bgt.AdjustedValue01) AS BudgetAdjustedValue01,
			SUM(bgt.AdjustedValue02) AS BudgetAdjustedValue02,
			SUM(bgt.AdjustedValue03) AS BudgetAdjustedValue03,
			SUM(bgt.AdjustedValue04) AS BudgetAdjustedValue04,
			SUM(bgt.AdjustedValue05) AS BudgetAdjustedValue05,
			SUM(bgt.AdjustedValue06) AS BudgetAdjustedValue06,
			SUM(bgt.AdjustedValue07) AS BudgetAdjustedValue07,
			SUM(bgt.AdjustedValue08) AS BudgetAdjustedValue08,
			SUM(bgt.AdjustedValue09) AS BudgetAdjustedValue09,
			SUM(bgt.AdjustedValue10) AS BudgetAdjustedValue10,
			SUM(bgt.AdjustedValue11) AS BudgetAdjustedValue11,
			SUM(bgt.AdjustedValue12) AS BudgetAdjustedValue12,
		                        
			SUM(proj.AdjustedValue01) AS ProjectionAdjustedValue01,
			SUM(proj.AdjustedValue02) AS ProjectionAdjustedValue02,
			SUM(proj.AdjustedValue03) AS ProjectionAdjustedValue03,
			SUM(proj.AdjustedValue04) AS ProjectionAdjustedValue04,
			SUM(proj.AdjustedValue05) AS ProjectionAdjustedValue05,
			SUM(proj.AdjustedValue06) AS ProjectionAdjustedValue06,
			SUM(proj.AdjustedValue07) AS ProjectionAdjustedValue07,
			SUM(proj.AdjustedValue08) AS ProjectionAdjustedValue08,
			SUM(proj.AdjustedValue09) AS ProjectionAdjustedValue09,
			SUM(proj.AdjustedValue10) AS ProjectionAdjustedValue10,
			SUM(proj.AdjustedValue11) AS ProjectionAdjustedValue11,
			SUM(proj.AdjustedValue12) AS ProjectionAdjustedValue12
		FROM [fp].[FactStatistics] fs 
			INNER JOIN (SELECT DISTINCT SourceDepartmentID, StatAccountID FROM itemsToFlex) fl ON fs.DepartmentID = fl.SourceDepartmentID 
				AND fl.StatAccountID = fs.AccountID
			INNER JOIN [fp].[FactStatisticsBudget] tgt ON fs.StatisticsID = tgt.StatisticsID AND tgt.BudgetPhaseID = 2
			INNER JOIN [fp].[FactStatisticsBudget] bgt ON fs.StatisticsID = bgt.StatisticsID AND bgt.BudgetPhaseID = 3
			INNER JOIN [fp].[FactStatisticsProjection] proj ON fs.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = 3
		WHERE fs.BudgetConfigID = @BudgetConfigID
		GROUP BY fs.DepartmentID, 
			fs.AccountID
	), statsBySourceDept AS (
		 -- Calculate the stats at an individual flex config level.
		SELECT 
			fs.DepartmentID,
			fs.SourceDepartmentID,
			fs.StatAccountID,
			fs.GLAccountID,
			SUM(TargetAdjustedValue01) AS TargetAdjustedValue01,
			SUM(TargetAdjustedValue02) AS TargetAdjustedValue02,
			SUM(TargetAdjustedValue03) AS TargetAdjustedValue03,
			SUM(TargetAdjustedValue04) AS TargetAdjustedValue04,
			SUM(TargetAdjustedValue05) AS TargetAdjustedValue05,
			SUM(TargetAdjustedValue06) AS TargetAdjustedValue06,
			SUM(TargetAdjustedValue07) AS TargetAdjustedValue07,
			SUM(TargetAdjustedValue08) AS TargetAdjustedValue08,
			SUM(TargetAdjustedValue09) AS TargetAdjustedValue09,
			SUM(TargetAdjustedValue10) AS TargetAdjustedValue10,
			SUM(TargetAdjustedValue11) AS TargetAdjustedValue11,
			SUM(TargetAdjustedValue12) AS TargetAdjustedValue12,

			SUM(BudgetAdjustedValue01) AS BudgetAdjustedValue01,
			SUM(BudgetAdjustedValue02) AS BudgetAdjustedValue02,
			SUM(BudgetAdjustedValue03) AS BudgetAdjustedValue03,
			SUM(BudgetAdjustedValue04) AS BudgetAdjustedValue04,
			SUM(BudgetAdjustedValue05) AS BudgetAdjustedValue05,
			SUM(BudgetAdjustedValue06) AS BudgetAdjustedValue06,
			SUM(BudgetAdjustedValue07) AS BudgetAdjustedValue07,
			SUM(BudgetAdjustedValue08) AS BudgetAdjustedValue08,
			SUM(BudgetAdjustedValue09) AS BudgetAdjustedValue09,
			SUM(BudgetAdjustedValue10) AS BudgetAdjustedValue10,
			SUM(BudgetAdjustedValue11) AS BudgetAdjustedValue11,
			SUM(BudgetAdjustedValue12) AS BudgetAdjustedValue12,

			SUM(ProjectionAdjustedValue01) AS ProjectionAdjustedValue01,
			SUM(ProjectionAdjustedValue02) AS ProjectionAdjustedValue02,
			SUM(ProjectionAdjustedValue03) AS ProjectionAdjustedValue03,
			SUM(ProjectionAdjustedValue04) AS ProjectionAdjustedValue04,
			SUM(ProjectionAdjustedValue05) AS ProjectionAdjustedValue05,
			SUM(ProjectionAdjustedValue06) AS ProjectionAdjustedValue06,
			SUM(ProjectionAdjustedValue07) AS ProjectionAdjustedValue07,
			SUM(ProjectionAdjustedValue08) AS ProjectionAdjustedValue08,
			SUM(ProjectionAdjustedValue09) AS ProjectionAdjustedValue09,
			SUM(ProjectionAdjustedValue10) AS ProjectionAdjustedValue10,
			SUM(ProjectionAdjustedValue11) AS ProjectionAdjustedValue11,
			SUM(ProjectionAdjustedValue12) AS ProjectionAdjustedValue12
		FROM itemsToFlex fs
			INNER JOIN stats st ON fs.SourceDepartmentID = st.SourceDepartmentID AND fs.StatAccountID = st.AccountID
		GROUP BY fs.DepartmentID,		
			fs.SourceDepartmentID,
			fs.StatAccountID,
			fs.GLAccountID
	)
	SELECT 
		uos.GeneralLedgerID,
		SUM(stat.TargetAdjustedValue01) As TargetStats01,
		SUM(stat.TargetAdjustedValue02) As TargetStats02,
		SUM(stat.TargetAdjustedValue03) As TargetStats03,
		SUM(stat.TargetAdjustedValue04) As TargetStats04,
		SUM(stat.TargetAdjustedValue05) As TargetStats05,
		SUM(stat.TargetAdjustedValue06) As TargetStats06,
		SUM(stat.TargetAdjustedValue07) As TargetStats07,
		SUM(stat.TargetAdjustedValue08) As TargetStats08,
		SUM(stat.TargetAdjustedValue09) As TargetStats09,
		SUM(stat.TargetAdjustedValue10) As TargetStats10,
		SUM(stat.TargetAdjustedValue11) As TargetStats11,
		SUM(stat.TargetAdjustedValue12) As TargetStats12,

		SUM(stat.BudgetAdjustedValue01) As BudgetStats01,
		SUM(stat.BudgetAdjustedValue02) As BudgetStats02,
		SUM(stat.BudgetAdjustedValue03) As BudgetStats03,
		SUM(stat.BudgetAdjustedValue04) As BudgetStats04,
		SUM(stat.BudgetAdjustedValue05) As BudgetStats05,
		SUM(stat.BudgetAdjustedValue06) As BudgetStats06,
		SUM(stat.BudgetAdjustedValue07) As BudgetStats07,
		SUM(stat.BudgetAdjustedValue08) As BudgetStats08,
		SUM(stat.BudgetAdjustedValue09) As BudgetStats09,
		SUM(stat.BudgetAdjustedValue10) As BudgetStats10,
		SUM(stat.BudgetAdjustedValue11) As BudgetStats11,
		SUM(stat.BudgetAdjustedValue12) As BudgetStats12,

		SUM(stat.ProjectionAdjustedValue01) As ProjectionStats01,
		SUM(stat.ProjectionAdjustedValue02) As ProjectionStats02,
		SUM(stat.ProjectionAdjustedValue03) As ProjectionStats03,
		SUM(stat.ProjectionAdjustedValue04) As ProjectionStats04,
		SUM(stat.ProjectionAdjustedValue05) As ProjectionStats05,
		SUM(stat.ProjectionAdjustedValue06) As ProjectionStats06,
		SUM(stat.ProjectionAdjustedValue07) As ProjectionStats07,
		SUM(stat.ProjectionAdjustedValue08) As ProjectionStats08,
		SUM(stat.ProjectionAdjustedValue09) As ProjectionStats09,
		SUM(stat.ProjectionAdjustedValue10) As ProjectionStats10,
		SUM(stat.ProjectionAdjustedValue11) As ProjectionStats11,
		SUM(stat.ProjectionAdjustedValue12) As ProjectionStats12
	FROM (SELECT DISTINCT f.DepartmentID, f.GLAccountID, f.StatAccountID FROM itemsToFlex f) fm
		INNER JOIN glRecords uos ON uos.DepartmentID = fm.DepartmentID AND uos.AccountID = fm.GLAccountID
		INNER JOIN statsBySourceDept stat ON fm.StatAccountID = stat.StatAccountID 
			AND fm.DepartmentID = stat.DepartmentID
			AND uos.AccountID = stat.GLAccountID
	GROUP BY uos.GeneralLedgerID
)
GO


---------------------------------------------

